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

lib-jitsi-meet.js 770KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. /* global Strophe, $, Promise */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var AuthenticationEvents = require("./service/authentication/AuthenticationEvents");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  13. var JitsiParticipant = require("./JitsiParticipant");
  14. var Statistics = require("./modules/statistics/statistics");
  15. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  16. var JitsiTrackEvents = require("./JitsiTrackEvents");
  17. /**
  18. * Creates a JitsiConference object with the given name and properties.
  19. * Note: this constructor is not a part of the public API (objects should be
  20. * created using JitsiConnection.createConference).
  21. * @param options.config properties / settings related to the conference that will be created.
  22. * @param options.name the name of the conference
  23. * @param options.connection the JitsiConnection object for this JitsiConference.
  24. * @constructor
  25. */
  26. function JitsiConference(options) {
  27. if(!options.name || options.name.toLowerCase() !== options.name) {
  28. logger.error("Invalid conference name (no conference name passed or it"
  29. + "contains invalid characters like capital letters)!");
  30. return;
  31. }
  32. this.options = options;
  33. this.connection = this.options.connection;
  34. this.xmpp = this.connection.xmpp;
  35. this.eventEmitter = new EventEmitter();
  36. this.room = this.xmpp.createRoom(this.options.name, this.options.config);
  37. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  38. this.rtc = new RTC(this.room, options);
  39. if(!RTC.options.disableAudioLevels)
  40. this.statistics = new Statistics();
  41. setupListeners(this);
  42. this.participants = {};
  43. this.lastDominantSpeaker = null;
  44. this.dtmfManager = null;
  45. this.somebodySupportsDTMF = false;
  46. this.authEnabled = false;
  47. this.authIdentity;
  48. }
  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, 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.lastDominantSpeaker !== id && conference.room) {
  672. conference.lastDominantSpeaker = id;
  673. conference.eventEmitter.emit(JitsiConferenceEvents.DOMINANT_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 dominant speaker was changed.
  760. */
  761. DOMINANT_SPEAKER_CHANGED: "conference.dominantSpeaker",
  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. var Resolutions = require("./service/RTC/Resolutions");
  973. function getLowerResolution(resolution) {
  974. if(!Resolutions[resolution])
  975. return null;
  976. var order = Resolutions[resolution].order;
  977. var res = null;
  978. var resName = null;
  979. for(var i in Resolutions) {
  980. var tmp = Resolutions[i];
  981. if (!res || (res.order < tmp.order && tmp.order < order)) {
  982. resName = i;
  983. res = tmp;
  984. }
  985. }
  986. return resName;
  987. }
  988. /**
  989. * Namespace for the interface of Jitsi Meet Library.
  990. */
  991. var LibJitsiMeet = {
  992. JitsiConnection: JitsiConnection,
  993. events: {
  994. conference: JitsiConferenceEvents,
  995. connection: JitsiConnectionEvents,
  996. track: JitsiTrackEvents
  997. },
  998. errors: {
  999. conference: JitsiConferenceErrors,
  1000. connection: JitsiConnectionErrors,
  1001. track: JitsiTrackErrors
  1002. },
  1003. logLevels: Logger.levels,
  1004. init: function (options) {
  1005. return RTC.init(options || {});
  1006. },
  1007. /**
  1008. * Returns whether the desktop sharing is enabled or not.
  1009. * @returns {boolean}
  1010. */
  1011. isDesktopSharingEnabled: function () {
  1012. return RTC.isDesktopSharingEnabled();
  1013. },
  1014. setLogLevel: function (level) {
  1015. Logger.setLogLevel(level);
  1016. },
  1017. /**
  1018. * Creates the media tracks and returns them trough the callback.
  1019. * @param options Object with properties / settings specifying the tracks which should be created.
  1020. * should be created or some additional configurations about resolution for example.
  1021. * @param {Array} options.devices the devices that will be requested
  1022. * @param {string} options.resolution resolution constraints
  1023. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1024. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1025. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1026. * @param {string} options.cameraDeviceId
  1027. * @param {string} options.micDeviceId
  1028. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1029. * A promise that returns an array of created JitsiTracks if resolved,
  1030. * or a JitsiConferenceError if rejected.
  1031. */
  1032. createLocalTracks: function (options) {
  1033. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1034. function(tracks) {
  1035. if(!RTC.options.disableAudioLevels)
  1036. for(var i = 0; i < tracks.length; i++) {
  1037. var track = tracks[i];
  1038. var mStream = track.getOriginalStream();
  1039. if(track.getType() === "audio"){
  1040. Statistics.startLocalStats(mStream,
  1041. track.setAudioLevel.bind(track));
  1042. track.addEventListener(
  1043. JitsiTrackEvents.TRACK_STOPPED,
  1044. function(){
  1045. Statistics.stopLocalStats(mStream);
  1046. });
  1047. }
  1048. }
  1049. return tracks;
  1050. }).catch(function (error) {
  1051. if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  1052. var oldResolution = options.resolution || '360';
  1053. var newResolution = getLowerResolution(oldResolution);
  1054. if(newResolution === null)
  1055. return Promise.reject(error);
  1056. options.resolution = newResolution;
  1057. return LibJitsiMeet.createLocalTracks(options);
  1058. }
  1059. return Promise.reject(error);
  1060. });
  1061. },
  1062. /**
  1063. * Checks if its possible to enumerate available cameras/micropones.
  1064. * @returns {boolean} true if available, false otherwise.
  1065. */
  1066. isDeviceListAvailable: function () {
  1067. return RTC.isDeviceListAvailable();
  1068. },
  1069. /**
  1070. * Returns true if changing the camera / microphone device is supported and
  1071. * false if not.
  1072. * @returns {boolean} true if available, false otherwise.
  1073. */
  1074. isDeviceChangeAvailable: function () {
  1075. return RTC.isDeviceChangeAvailable();
  1076. },
  1077. enumerateDevices: function (callback) {
  1078. RTC.enumerateDevices(callback);
  1079. }
  1080. };
  1081. require("es6-promise").polyfill()
  1082. //Setups the promise object.
  1083. window.Promise = window.Promise || require("es6-promise").Promise;
  1084. module.exports = LibJitsiMeet;
  1085. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/Resolutions":81,"es6-promise":46,"jitsi-meet-logger":48}],8:[function(require,module,exports){
  1086. /* global Strophe */
  1087. /**
  1088. * Represents a participant in (a member of) a conference.
  1089. */
  1090. function JitsiParticipant(jid, conference, displayName){
  1091. this._jid = jid;
  1092. this._id = Strophe.getResourceFromJid(jid);
  1093. this._conference = conference;
  1094. this._displayName = displayName;
  1095. this._supportsDTMF = false;
  1096. this._tracks = [];
  1097. this._role = 'none';
  1098. }
  1099. /**
  1100. * @returns {JitsiConference} The conference that this participant belongs to.
  1101. */
  1102. JitsiParticipant.prototype.getConference = function() {
  1103. return this._conference;
  1104. };
  1105. /**
  1106. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1107. */
  1108. JitsiParticipant.prototype.getTracks = function() {
  1109. return this._tracks;
  1110. };
  1111. /**
  1112. * @returns {String} The ID of this participant.
  1113. */
  1114. JitsiParticipant.prototype.getId = function() {
  1115. return this._id;
  1116. };
  1117. /**
  1118. * @returns {String} The JID of this participant.
  1119. */
  1120. JitsiParticipant.prototype.getJid = function() {
  1121. return this._jid;
  1122. };
  1123. /**
  1124. * @returns {String} The human-readable display name of this participant.
  1125. */
  1126. JitsiParticipant.prototype.getDisplayName = function() {
  1127. return this._displayName;
  1128. };
  1129. /**
  1130. * @returns {Boolean} Whether this participant is a moderator or not.
  1131. */
  1132. JitsiParticipant.prototype.isModerator = function() {
  1133. return this._role === 'moderator';
  1134. };
  1135. // Gets a link to an etherpad instance advertised by the participant?
  1136. //JitsiParticipant.prototype.getEtherpad = function() {
  1137. //
  1138. //}
  1139. /*
  1140. * @returns {Boolean} Whether this participant has muted their audio.
  1141. */
  1142. JitsiParticipant.prototype.isAudioMuted = function() {
  1143. return this.getTracks().reduce(function (track, isAudioMuted) {
  1144. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1145. }, true);
  1146. };
  1147. /*
  1148. * @returns {Boolean} Whether this participant has muted their video.
  1149. */
  1150. JitsiParticipant.prototype.isVideoMuted = function() {
  1151. return this.getTracks().reduce(function (track, isVideoMuted) {
  1152. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1153. }, true);
  1154. };
  1155. /*
  1156. * @returns {???} The latest statistics reported by this participant
  1157. * (i.e. info used to populate the GSM bars)
  1158. * TODO: do we expose this or handle it internally?
  1159. */
  1160. JitsiParticipant.prototype.getLatestStats = function() {
  1161. };
  1162. /**
  1163. * @returns {String} The role of this participant.
  1164. */
  1165. JitsiParticipant.prototype.getRole = function() {
  1166. return this._role;
  1167. };
  1168. /*
  1169. * @returns {Boolean} Whether this participant is
  1170. * the conference focus (i.e. jicofo).
  1171. */
  1172. JitsiParticipant.prototype.isFocus = function() {
  1173. };
  1174. /*
  1175. * @returns {Boolean} Whether this participant is
  1176. * a conference recorder (i.e. jirecon).
  1177. */
  1178. JitsiParticipant.prototype.isRecorder = function() {
  1179. };
  1180. /*
  1181. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1182. */
  1183. JitsiParticipant.prototype.isSipGateway = function() {
  1184. };
  1185. /**
  1186. * @returns {Boolean} Whether this participant
  1187. * is currently sharing their screen.
  1188. */
  1189. JitsiParticipant.prototype.isScreenSharing = function() {
  1190. };
  1191. /**
  1192. * @returns {String} The user agent of this participant
  1193. * (i.e. browser userAgent string).
  1194. */
  1195. JitsiParticipant.prototype.getUserAgent = function() {
  1196. };
  1197. /**
  1198. * Kicks the participant from the conference (requires certain privileges).
  1199. */
  1200. JitsiParticipant.prototype.kick = function() {
  1201. };
  1202. /**
  1203. * Asks this participant to mute themselves.
  1204. */
  1205. JitsiParticipant.prototype.askToMute = function() {
  1206. };
  1207. JitsiParticipant.prototype.supportsDTMF = function () {
  1208. return this._supportsDTMF;
  1209. };
  1210. module.exports = JitsiParticipant;
  1211. },{}],9:[function(require,module,exports){
  1212. module.exports = {
  1213. /**
  1214. * Returns JitsiTrackErrors based on the error object passed by GUM
  1215. * @param error the error
  1216. * @param {Array} devices Array with the requested devices
  1217. */
  1218. parseError: function (error, devices) {
  1219. devices = devices || [];
  1220. if (typeof error == "object" && error.constraintName && error.name
  1221. && (error.name == "ConstraintNotSatisfiedError" ||
  1222. error.name == "OverconstrainedError") &&
  1223. (error.constraintName == "minWidth" ||
  1224. error.constraintName == "maxWidth" ||
  1225. error.constraintName == "minHeight" ||
  1226. error.constraintName == "maxHeight") &&
  1227. devices.indexOf("video") !== -1) {
  1228. return this.UNSUPPORTED_RESOLUTION;
  1229. } else {
  1230. return this.GENERAL;
  1231. }
  1232. },
  1233. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1234. GENERAL: "gum.general"
  1235. };
  1236. },{}],10:[function(require,module,exports){
  1237. var JitsiTrackEvents = {
  1238. /**
  1239. * A media track mute status was changed.
  1240. */
  1241. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1242. /**
  1243. * Audio levels of a this track was changed.
  1244. */
  1245. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1246. /**
  1247. * The media track was removed to the conference.
  1248. */
  1249. TRACK_STOPPED: "track.stopped"
  1250. };
  1251. module.exports = JitsiTrackEvents;
  1252. },{}],11:[function(require,module,exports){
  1253. (function (__filename){
  1254. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1255. function JitsiDTMFManager (localAudio, peerConnection) {
  1256. var tracks = localAudio._getTracks();
  1257. if (!tracks.length) {
  1258. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1259. }
  1260. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1261. logger.debug("Initialized DTMFSender");
  1262. }
  1263. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1264. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1265. };
  1266. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1267. },{"jitsi-meet-logger":48}],12:[function(require,module,exports){
  1268. (function (__filename){
  1269. /* global config, APP, Strophe */
  1270. // cache datachannels to avoid garbage collection
  1271. // https://code.google.com/p/chromium/issues/detail?id=405545
  1272. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1273. var RTCEvents = require("../../service/RTC/RTCEvents");
  1274. /**
  1275. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1276. * @param peerConnection WebRTC peer connection instance.
  1277. */
  1278. function DataChannels(peerConnection, emitter) {
  1279. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1280. this.eventEmitter = emitter;
  1281. this._dataChannels = [];
  1282. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1283. // Although it's not a requirement to open separate channels from both bridge
  1284. // and peer as single channel can be used for sending and receiving data.
  1285. // So either channel opened by the bridge or the one opened here is enough
  1286. // for communication with the bridge.
  1287. /*var dataChannelOptions =
  1288. {
  1289. reliable: true
  1290. };
  1291. var dataChannel
  1292. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1293. // Can be used only when is in open state
  1294. dataChannel.onopen = function ()
  1295. {
  1296. dataChannel.send("My channel !!!");
  1297. };
  1298. dataChannel.onmessage = function (event)
  1299. {
  1300. var msgData = event.data;
  1301. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1302. };*/
  1303. };
  1304. /**
  1305. * Callback triggered by PeerConnection when new data channel is opened
  1306. * on the bridge.
  1307. * @param event the event info object.
  1308. */
  1309. DataChannels.prototype.onDataChannel = function (event) {
  1310. var dataChannel = event.channel;
  1311. var self = this;
  1312. dataChannel.onopen = function () {
  1313. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1314. // Code sample for sending string and/or binary data
  1315. // Sends String message to the bridge
  1316. //dataChannel.send("Hello bridge!");
  1317. // Sends 12 bytes binary message to the bridge
  1318. //dataChannel.send(new ArrayBuffer(12));
  1319. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1320. };
  1321. dataChannel.onerror = function (error) {
  1322. logger.error("Data Channel Error:", error, dataChannel);
  1323. };
  1324. dataChannel.onmessage = function (event) {
  1325. var data = event.data;
  1326. // JSON
  1327. var obj;
  1328. try {
  1329. obj = JSON.parse(data);
  1330. }
  1331. catch (e) {
  1332. logger.error(
  1333. "Failed to parse data channel message as JSON: ",
  1334. data,
  1335. dataChannel);
  1336. }
  1337. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1338. var colibriClass = obj.colibriClass;
  1339. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1340. // Endpoint ID from the Videobridge.
  1341. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1342. logger.info(
  1343. "Data channel new dominant speaker event: ",
  1344. dominantSpeakerEndpoint);
  1345. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1346. }
  1347. else if ("InLastNChangeEvent" === colibriClass) {
  1348. var oldValue = obj.oldValue;
  1349. var newValue = obj.newValue;
  1350. // Make sure that oldValue and newValue are of type boolean.
  1351. var type;
  1352. if ((type = typeof oldValue) !== 'boolean') {
  1353. if (type === 'string') {
  1354. oldValue = (oldValue == "true");
  1355. } else {
  1356. oldValue = new Boolean(oldValue).valueOf();
  1357. }
  1358. }
  1359. if ((type = typeof newValue) !== 'boolean') {
  1360. if (type === 'string') {
  1361. newValue = (newValue == "true");
  1362. } else {
  1363. newValue = new Boolean(newValue).valueOf();
  1364. }
  1365. }
  1366. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1367. }
  1368. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1369. // The new/latest list of last-n endpoint IDs.
  1370. var lastNEndpoints = obj.lastNEndpoints;
  1371. // The list of endpoint IDs which are entering the list of
  1372. // last-n at this time i.e. were not in the old list of last-n
  1373. // endpoint IDs.
  1374. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1375. logger.info(
  1376. "Data channel new last-n event: ",
  1377. lastNEndpoints, endpointsEnteringLastN, obj);
  1378. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1379. lastNEndpoints, endpointsEnteringLastN, obj);
  1380. }
  1381. else {
  1382. logger.debug("Data channel JSON-formatted message: ", obj);
  1383. // The received message appears to be appropriately formatted
  1384. // (i.e. is a JSON object which assigns a value to the mandatory
  1385. // property colibriClass) so don't just swallow it, expose it to
  1386. // public consumption.
  1387. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1388. }
  1389. }
  1390. };
  1391. dataChannel.onclose = function () {
  1392. logger.info("The Data Channel closed", dataChannel);
  1393. var idx = self._dataChannels.indexOf(dataChannel);
  1394. if (idx > -1)
  1395. self._dataChannels = self._dataChannels.splice(idx, 1);
  1396. };
  1397. this._dataChannels.push(dataChannel);
  1398. };
  1399. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1400. this._onXXXEndpointChanged("selected", userResource);
  1401. }
  1402. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1403. this._onXXXEndpointChanged("pinnned", userResource);
  1404. }
  1405. /**
  1406. * Notifies Videobridge about a change in the value of a specific
  1407. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1408. *
  1409. * @param xxx the name of the endpoint-related property whose value changed
  1410. * @param userResource the new value of the endpoint-related property after the
  1411. * change
  1412. */
  1413. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1414. // Derive the correct words from xxx such as selected and Selected, pinned
  1415. // and Pinned.
  1416. var head = xxx.charAt(0);
  1417. var tail = xxx.substring(1);
  1418. var lower = head.toLowerCase() + tail;
  1419. var upper = head.toUpperCase() + tail;
  1420. // Notify Videobridge about the specified endpoint change.
  1421. console.log(lower + ' endpoint changed: ', userResource);
  1422. this._some(function (dataChannel) {
  1423. if (dataChannel.readyState == 'open') {
  1424. console.log(
  1425. 'sending ' + lower
  1426. + ' endpoint changed notification to the bridge: ',
  1427. userResource);
  1428. var jsonObject = {};
  1429. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1430. jsonObject[lower + "Endpoint"]
  1431. = (userResource ? userResource : null);
  1432. dataChannel.send(JSON.stringify(jsonObject));
  1433. return true;
  1434. }
  1435. });
  1436. }
  1437. DataChannels.prototype._some = function (callback, thisArg) {
  1438. var dataChannels = this._dataChannels;
  1439. if (dataChannels && dataChannels.length !== 0) {
  1440. if (thisArg)
  1441. return dataChannels.some(callback, thisArg);
  1442. else
  1443. return dataChannels.some(callback);
  1444. } else {
  1445. return false;
  1446. }
  1447. }
  1448. module.exports = DataChannels;
  1449. }).call(this,"/modules/RTC/DataChannels.js")
  1450. },{"../../service/RTC/RTCEvents":80,"jitsi-meet-logger":48}],13:[function(require,module,exports){
  1451. var JitsiTrack = require("./JitsiTrack");
  1452. var RTCBrowserType = require("./RTCBrowserType");
  1453. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1454. var RTCUtils = require("./RTCUtils");
  1455. /**
  1456. * Represents a single media track (either audio or video).
  1457. * @constructor
  1458. */
  1459. function JitsiLocalTrack(stream, videoType,
  1460. resolution)
  1461. {
  1462. this.videoType = videoType;
  1463. this.dontFireRemoveEvent = false;
  1464. this.resolution = resolution;
  1465. this.startMuted = false;
  1466. var self = this;
  1467. JitsiTrack.call(this, null, stream,
  1468. function () {
  1469. if(!this.dontFireRemoveEvent)
  1470. this.eventEmitter.emit(
  1471. JitsiTrackEvents.TRACK_STOPPED);
  1472. this.dontFireRemoveEvent = false;
  1473. }.bind(this));
  1474. }
  1475. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1476. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1477. /**
  1478. * Mutes / unmutes the track.
  1479. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1480. */
  1481. JitsiLocalTrack.prototype._setMute = function (mute) {
  1482. if(!this.rtc) {
  1483. this.startMuted = mute;
  1484. return;
  1485. }
  1486. var isAudio = this.type === JitsiTrack.AUDIO;
  1487. this.dontFireRemoveEvent = false;
  1488. if ((window.location.protocol != "https:") ||
  1489. (isAudio) || this.videoType === "desktop" ||
  1490. // FIXME FF does not support 'removeStream' method used to mute
  1491. RTCBrowserType.isFirefox()) {
  1492. var tracks = this._getTracks();
  1493. for (var idx = 0; idx < tracks.length; idx++) {
  1494. tracks[idx].enabled = !mute;
  1495. }
  1496. if(isAudio)
  1497. this.rtc.room.setAudioMute(mute);
  1498. else
  1499. this.rtc.room.setVideoMute(mute);
  1500. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1501. } else {
  1502. if (mute) {
  1503. this.dontFireRemoveEvent = true;
  1504. this.rtc.room.removeStream(this.stream, function () {});
  1505. RTCUtils.stopMediaStream(this.stream);
  1506. if(isAudio)
  1507. this.rtc.room.setAudioMute(mute);
  1508. else
  1509. this.rtc.room.setVideoMute(mute);
  1510. this.stream = null;
  1511. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1512. //FIXME: Maybe here we should set the SRC for the containers to something
  1513. } else {
  1514. var self = this;
  1515. RTCUtils.obtainAudioAndVideoPermissions({
  1516. devices: (isAudio ? ["audio"] : ["video"]),
  1517. resolution: self.resolution})
  1518. .then(function (streams) {
  1519. var stream = null;
  1520. for(var i = 0; i < streams.length; i++) {
  1521. stream = streams[i];
  1522. if(stream.type === self.type) {
  1523. self.stream = stream.stream;
  1524. self.videoType = stream.videoType;
  1525. break;
  1526. }
  1527. }
  1528. if(!stream)
  1529. return;
  1530. for(var i = 0; i < self.containers.length; i++)
  1531. {
  1532. RTCUtils.attachMediaStream(
  1533. self.containers[i], self.stream);
  1534. }
  1535. self.rtc.room.addStream(stream.stream,
  1536. function () {
  1537. if(isAudio)
  1538. self.rtc.room.setAudioMute(mute);
  1539. else
  1540. self.rtc.room.setVideoMute(mute);
  1541. self.eventEmitter.emit(
  1542. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1543. });
  1544. });
  1545. }
  1546. }
  1547. }
  1548. /**
  1549. * Stops sending the media track. And removes it from the HTML.
  1550. * NOTE: Works for local tracks only.
  1551. */
  1552. JitsiLocalTrack.prototype.stop = function () {
  1553. if(!this.stream)
  1554. return;
  1555. if(this.rtc)
  1556. this.rtc.room.removeStream(this.stream, function () {});
  1557. RTCUtils.stopMediaStream(this.stream);
  1558. this.detach();
  1559. }
  1560. /**
  1561. * Returns <tt>true</tt> - if the stream is muted
  1562. * and <tt>false</tt> otherwise.
  1563. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1564. * and <tt>false</tt> otherwise.
  1565. */
  1566. JitsiLocalTrack.prototype.isMuted = function () {
  1567. if (!this.stream)
  1568. return true;
  1569. var tracks = [];
  1570. var isAudio = this.type === JitsiTrack.AUDIO;
  1571. if (isAudio) {
  1572. tracks = this.stream.getAudioTracks();
  1573. } else {
  1574. if (!this.isActive())
  1575. return true;
  1576. tracks = this.stream.getVideoTracks();
  1577. }
  1578. for (var idx = 0; idx < tracks.length; idx++) {
  1579. if(tracks[idx].enabled)
  1580. return false;
  1581. }
  1582. return true;
  1583. };
  1584. /**
  1585. * Private method. Updates rtc property of the track.
  1586. * @param rtc the rtc instance.
  1587. */
  1588. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1589. this.rtc = rtc;
  1590. };
  1591. /**
  1592. * Return true;
  1593. */
  1594. JitsiLocalTrack.prototype.isLocal = function () {
  1595. return true;
  1596. }
  1597. module.exports = JitsiLocalTrack;
  1598. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1599. var JitsiTrack = require("./JitsiTrack");
  1600. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1601. /**
  1602. * Represents a single media track (either audio or video).
  1603. * @param RTC the rtc instance.
  1604. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1605. * @param sid sid for the Media Stream
  1606. * @param ssrc ssrc for the Media Stream
  1607. * @param eventEmitter the event emitter
  1608. * @constructor
  1609. */
  1610. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1611. JitsiTrack.call(this, RTC, data.stream,
  1612. function () {
  1613. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1614. }.bind(this));
  1615. this.rtc = RTC;
  1616. this.sid = sid;
  1617. this.stream = data.stream;
  1618. this.peerjid = data.peerjid;
  1619. this.videoType = data.videoType;
  1620. this.ssrc = ssrc;
  1621. this.muted = false;
  1622. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1623. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1624. this.muted = true;
  1625. }
  1626. }
  1627. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1628. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1629. /**
  1630. * Sets current muted status and fires an events for the change.
  1631. * @param value the muted status.
  1632. */
  1633. JitsiRemoteTrack.prototype.setMute = function (value) {
  1634. this.stream.muted = value;
  1635. this.muted = value;
  1636. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1637. };
  1638. /**
  1639. * Returns the current muted status of the track.
  1640. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1641. */
  1642. JitsiRemoteTrack.prototype.isMuted = function () {
  1643. return this.muted;
  1644. };
  1645. /**
  1646. * Returns the participant id which owns the track.
  1647. * @returns {string} the id of the participants.
  1648. */
  1649. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1650. return Strophe.getResourceFromJid(this.peerjid);
  1651. };
  1652. /**
  1653. * Return false;
  1654. */
  1655. JitsiRemoteTrack.prototype.isLocal = function () {
  1656. return false;
  1657. };
  1658. delete JitsiRemoteTrack.prototype.stop;
  1659. delete JitsiRemoteTrack.prototype.start;
  1660. module.exports = JitsiRemoteTrack;
  1661. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1662. var RTCBrowserType = require("./RTCBrowserType");
  1663. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1664. var EventEmitter = require("events");
  1665. var RTC = require("./RTCUtils");
  1666. /**
  1667. * This implements 'onended' callback normally fired by WebRTC after the stream
  1668. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1669. * @param jitsiTrack our track object holding the original WebRTC stream object
  1670. * to which 'onended' handling will be added.
  1671. */
  1672. function implementOnEndedHandling(jitsiTrack) {
  1673. var stream = jitsiTrack.getOriginalStream();
  1674. var originalStop = stream.stop;
  1675. stream.stop = function () {
  1676. originalStop.apply(stream);
  1677. if (jitsiTrack.isActive()) {
  1678. stream.onended();
  1679. }
  1680. };
  1681. }
  1682. /**
  1683. * Adds onended/oninactive handler to a MediaStream.
  1684. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1685. * @param handler the handler
  1686. */
  1687. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1688. if(RTCBrowserType.isTemasysPluginUsed()) {
  1689. // themasys
  1690. //FIXME: Seems that not working properly.
  1691. if(mediaStream.onended) {
  1692. mediaStream.onended = handler;
  1693. } else if(mediaStream.addEventListener) {
  1694. mediaStream.addEventListener('ended', function () {
  1695. handler(mediaStream);
  1696. });
  1697. } else if(mediaStream.attachEvent) {
  1698. mediaStream.attachEvent('ended', function () {
  1699. handler(mediaStream);
  1700. });
  1701. }
  1702. }
  1703. else {
  1704. if(typeof mediaStream.active !== "undefined")
  1705. mediaStream.oninactive = handler;
  1706. else
  1707. mediaStream.onended = handler;
  1708. }
  1709. }
  1710. /**
  1711. * Represents a single media track (either audio or video).
  1712. * @constructor
  1713. * @param rtc the rtc instance
  1714. * @param stream the stream
  1715. * @param streamInactiveHandler the function that will handle
  1716. * onended/oninactive events of the stream.
  1717. */
  1718. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1719. {
  1720. /**
  1721. * Array with the HTML elements that are displaying the streams.
  1722. * @type {Array}
  1723. */
  1724. this.containers = [];
  1725. this.rtc = rtc;
  1726. this.stream = stream;
  1727. this.eventEmitter = new EventEmitter();
  1728. this.audioLevel = -1;
  1729. this.type = (this.stream.getVideoTracks().length > 0)?
  1730. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1731. if(this.type == "audio") {
  1732. this._getTracks = function () {
  1733. return this.stream.getAudioTracks();
  1734. }.bind(this);
  1735. } else {
  1736. this._getTracks = function () {
  1737. return this.stream.getVideoTracks();
  1738. }.bind(this);
  1739. }
  1740. if (RTCBrowserType.isFirefox() && this.stream) {
  1741. implementOnEndedHandling(this);
  1742. }
  1743. if(stream)
  1744. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1745. }
  1746. /**
  1747. * JitsiTrack video type.
  1748. * @type {string}
  1749. */
  1750. JitsiTrack.VIDEO = "video";
  1751. /**
  1752. * JitsiTrack audio type.
  1753. * @type {string}
  1754. */
  1755. JitsiTrack.AUDIO = "audio";
  1756. /**
  1757. * Returns the type (audio or video) of this track.
  1758. */
  1759. JitsiTrack.prototype.getType = function() {
  1760. return this.type;
  1761. };
  1762. /**
  1763. * Check if this is audiotrack.
  1764. */
  1765. JitsiTrack.prototype.isAudioTrack = function () {
  1766. return this.getType() === JitsiTrack.AUDIO;
  1767. };
  1768. /**
  1769. * Check if this is videotrack.
  1770. */
  1771. JitsiTrack.prototype.isVideoTrack = function () {
  1772. return this.getType() === JitsiTrack.VIDEO;
  1773. };
  1774. /**
  1775. * Returns the RTCMediaStream from the browser (?).
  1776. */
  1777. JitsiTrack.prototype.getOriginalStream = function() {
  1778. return this.stream;
  1779. }
  1780. /**
  1781. * Mutes the track.
  1782. */
  1783. JitsiTrack.prototype.mute = function () {
  1784. this._setMute(true);
  1785. }
  1786. /**
  1787. * Unmutes the stream.
  1788. */
  1789. JitsiTrack.prototype.unmute = function () {
  1790. this._setMute(false);
  1791. }
  1792. /**
  1793. * Attaches the MediaStream of this track to an HTML container (?).
  1794. * Adds the container to the list of containers that are displaying the track.
  1795. * @param container the HTML container
  1796. */
  1797. JitsiTrack.prototype.attach = function (container) {
  1798. if(this.stream)
  1799. require("./RTCUtils").attachMediaStream(container, this.stream);
  1800. this.containers.push(container);
  1801. }
  1802. /**
  1803. * Removes the track from the passed HTML container.
  1804. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1805. */
  1806. JitsiTrack.prototype.detach = function (container) {
  1807. for(var i = 0; i < this.containers.length; i++)
  1808. {
  1809. if(this.containers[i].is(container))
  1810. {
  1811. this.containers.splice(i,1);
  1812. }
  1813. if(!container)
  1814. {
  1815. this.containers[i].find(">video").remove();
  1816. }
  1817. }
  1818. if(container)
  1819. $(container).find(">video").remove();
  1820. }
  1821. /**
  1822. * Stops sending the media track. And removes it from the HTML.
  1823. * NOTE: Works for local tracks only.
  1824. */
  1825. JitsiTrack.prototype.stop = function () {
  1826. }
  1827. /**
  1828. * Returns true if this is a video track and the source of the video is a
  1829. * screen capture as opposed to a camera.
  1830. */
  1831. JitsiTrack.prototype.isScreenSharing = function(){
  1832. }
  1833. /**
  1834. * Returns id of the track.
  1835. * @returns {string} id of the track or null if this is fake track.
  1836. */
  1837. JitsiTrack.prototype._getId = function () {
  1838. var tracks = this.stream.getTracks();
  1839. if(!tracks || tracks.length === 0)
  1840. return null;
  1841. return tracks[0].id;
  1842. };
  1843. /**
  1844. * Returns id of the track.
  1845. * @returns {string} id of the track or null if this is fake track.
  1846. */
  1847. JitsiTrack.prototype.getId = function () {
  1848. return RTC.getStreamID(this.stream);
  1849. };
  1850. /**
  1851. * Checks whether the MediaStream is avtive/not ended.
  1852. * When there is no check for active we don't have information and so
  1853. * will return that stream is active (in case of FF).
  1854. * @returns {boolean} whether MediaStream is active.
  1855. */
  1856. JitsiTrack.prototype.isActive = function () {
  1857. if((typeof this.stream.active !== "undefined"))
  1858. return this.stream.active;
  1859. else
  1860. return true;
  1861. };
  1862. /**
  1863. * Attaches a handler for events(For example - "audio level changed".).
  1864. * All possible event are defined in JitsiTrackEvents.
  1865. * @param eventId the event ID.
  1866. * @param handler handler for the event.
  1867. */
  1868. JitsiTrack.prototype.on = function (eventId, handler) {
  1869. if(this.eventEmitter)
  1870. this.eventEmitter.on(eventId, handler);
  1871. }
  1872. /**
  1873. * Removes event listener
  1874. * @param eventId the event ID.
  1875. * @param [handler] optional, the specific handler to unbind
  1876. */
  1877. JitsiTrack.prototype.off = function (eventId, handler) {
  1878. if(this.eventEmitter)
  1879. this.eventEmitter.removeListener(eventId, handler);
  1880. }
  1881. // Common aliases for event emitter
  1882. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  1883. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  1884. /**
  1885. * Sets the audio level for the stream
  1886. * @param audioLevel the new audio level
  1887. */
  1888. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  1889. if(this.audioLevel !== audioLevel) {
  1890. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1891. audioLevel);
  1892. this.audioLevel = audioLevel;
  1893. }
  1894. }
  1895. module.exports = JitsiTrack;
  1896. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":44}],16:[function(require,module,exports){
  1897. /* global APP */
  1898. var EventEmitter = require("events");
  1899. var RTCBrowserType = require("./RTCBrowserType");
  1900. var RTCUtils = require("./RTCUtils.js");
  1901. var JitsiTrack = require("./JitsiTrack");
  1902. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1903. var DataChannels = require("./DataChannels");
  1904. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1905. var DesktopSharingEventTypes
  1906. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1907. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1908. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1909. function createLocalTracks(streams) {
  1910. var newStreams = []
  1911. for (var i = 0; i < streams.length; i++) {
  1912. var localStream = new JitsiLocalTrack(streams[i].stream,
  1913. streams[i].videoType, streams[i].resolution);
  1914. newStreams.push(localStream);
  1915. if (streams[i].isMuted === true)
  1916. localStream.setMute(true);
  1917. }
  1918. return newStreams;
  1919. }
  1920. function RTC(room, options) {
  1921. this.room = room;
  1922. this.localStreams = [];
  1923. //FIXME: we should start removing those streams.
  1924. //FIXME: We should support multiple streams per jid.
  1925. this.remoteStreams = {};
  1926. this.localAudio = null;
  1927. this.localVideo = null;
  1928. this.eventEmitter = new EventEmitter();
  1929. var self = this;
  1930. this.options = options || {};
  1931. room.addPresenceListener("videomuted", function (values, from) {
  1932. if(self.remoteStreams[from]) {
  1933. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1934. }
  1935. });
  1936. room.addPresenceListener("audiomuted", function (values, from) {
  1937. if(self.remoteStreams[from]) {
  1938. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1939. }
  1940. });
  1941. }
  1942. /**
  1943. * Creates the local MediaStreams.
  1944. * @param {Object} [options] optional parameters
  1945. * @param {Array} options.devices the devices that will be requested
  1946. * @param {string} options.resolution resolution constraints
  1947. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1948. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1949. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1950. * @param {string} options.cameraDeviceId
  1951. * @param {string} options.micDeviceId
  1952. * @returns {*} Promise object that will receive the new JitsiTracks
  1953. */
  1954. RTC.obtainAudioAndVideoPermissions = function (options) {
  1955. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  1956. }
  1957. RTC.prototype.onIncommingCall = function(event) {
  1958. if(this.options.config.openSctp)
  1959. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1960. for(var i = 0; i < this.localStreams.length; i++)
  1961. if(this.localStreams[i])
  1962. {
  1963. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1964. }
  1965. }
  1966. RTC.prototype.selectedEndpoint = function (id) {
  1967. if(this.dataChannels)
  1968. this.dataChannels.handleSelectedEndpointEvent(id);
  1969. }
  1970. RTC.prototype.pinEndpoint = function (id) {
  1971. if(this.dataChannels)
  1972. this.dataChannels.handlePinnedEndpointEvent(id);
  1973. }
  1974. RTC.prototype.addListener = function (type, listener) {
  1975. this.eventEmitter.on(type, listener);
  1976. };
  1977. RTC.prototype.removeListener = function (eventType, listener) {
  1978. this.eventEmitter.removeListener(eventType, listener);
  1979. };
  1980. RTC.addListener = function (eventType, listener) {
  1981. RTCUtils.addListener(eventType, listener);
  1982. }
  1983. RTC.removeListener = function (eventType, listener) {
  1984. RTCUtils.removeListener(eventType, listener)
  1985. }
  1986. RTC.isRTCReady = function () {
  1987. return RTCUtils.isRTCReady();
  1988. }
  1989. RTC.init = function (options) {
  1990. this.options = options || {};
  1991. return RTCUtils.init(this.options);
  1992. }
  1993. RTC.getDeviceAvailability = function () {
  1994. return RTCUtils.getDeviceAvailability();
  1995. }
  1996. RTC.prototype.addLocalStream = function (stream) {
  1997. this.localStreams.push(stream);
  1998. stream._setRTC(this);
  1999. if (stream.type == "audio") {
  2000. this.localAudio = stream;
  2001. } else {
  2002. this.localVideo = stream;
  2003. }
  2004. };
  2005. /**
  2006. * Set mute for all local audio streams attached to the conference.
  2007. * @param value the mute value
  2008. */
  2009. RTC.prototype.setAudioMute = function (value) {
  2010. for(var i = 0; i < this.localStreams.length; i++) {
  2011. var stream = this.localStreams[i];
  2012. if(stream.getType() !== "audio") {
  2013. continue;
  2014. }
  2015. stream._setMute(value);
  2016. }
  2017. }
  2018. RTC.prototype.removeLocalStream = function (stream) {
  2019. for(var i = 0; i < this.localStreams.length; i++) {
  2020. if(this.localStreams[i].getOriginalStream() === stream) {
  2021. delete this.localStreams[i];
  2022. return;
  2023. }
  2024. }
  2025. };
  2026. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2027. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2028. if(!data.peerjid)
  2029. return;
  2030. var jid = Strophe.getResourceFromJid(data.peerjid);
  2031. if(!this.remoteStreams[jid]) {
  2032. this.remoteStreams[jid] = {};
  2033. }
  2034. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2035. return remoteStream;
  2036. };
  2037. RTC.getPCConstraints = function () {
  2038. return RTCUtils.pc_constraints;
  2039. };
  2040. RTC.attachMediaStream = function (elSelector, stream) {
  2041. RTCUtils.attachMediaStream(elSelector, stream);
  2042. };
  2043. RTC.getStreamID = function (stream) {
  2044. return RTCUtils.getStreamID(stream);
  2045. };
  2046. RTC.getVideoSrc = function (element) {
  2047. return RTCUtils.getVideoSrc(element);
  2048. };
  2049. /**
  2050. * Returns true if retrieving the the list of input devices is supported and
  2051. * false if not.
  2052. */
  2053. RTC.isDeviceListAvailable = function () {
  2054. return RTCUtils.isDeviceListAvailable();
  2055. };
  2056. /**
  2057. * Returns true if changing the camera / microphone device is supported and
  2058. * false if not.
  2059. */
  2060. RTC.isDeviceChangeAvailable = function () {
  2061. return RTCUtils.isDeviceChangeAvailable();
  2062. }
  2063. /**
  2064. * Allows to receive list of available cameras/microphones.
  2065. * @param {function} callback would receive array of devices as an argument
  2066. */
  2067. RTC.enumerateDevices = function (callback) {
  2068. RTCUtils.enumerateDevices(callback);
  2069. };
  2070. RTC.setVideoSrc = function (element, src) {
  2071. RTCUtils.setVideoSrc(element, src);
  2072. };
  2073. /**
  2074. * A method to handle stopping of the stream.
  2075. * One point to handle the differences in various implementations.
  2076. * @param mediaStream MediaStream object to stop.
  2077. */
  2078. RTC.stopMediaStream = function (mediaStream) {
  2079. RTCUtils.stopMediaStream(mediaStream);
  2080. };
  2081. /**
  2082. * Returns whether the desktop sharing is enabled or not.
  2083. * @returns {boolean}
  2084. */
  2085. RTC.isDesktopSharingEnabled = function () {
  2086. return RTCUtils.isDesktopSharingEnabled();
  2087. }
  2088. RTC.prototype.getVideoElementName = function () {
  2089. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2090. };
  2091. RTC.prototype.dispose = function() {
  2092. };
  2093. RTC.prototype.switchVideoStreams = function (newStream) {
  2094. this.localVideo.stream = newStream;
  2095. this.localStreams = [];
  2096. //in firefox we have only one stream object
  2097. if (this.localAudio.getOriginalStream() != newStream)
  2098. this.localStreams.push(this.localAudio);
  2099. this.localStreams.push(this.localVideo);
  2100. };
  2101. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2102. if(!jid)
  2103. return;
  2104. var resource = Strophe.getResourceFromJid(jid);
  2105. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2106. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2107. }
  2108. module.exports = RTC;
  2109. },{"../../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){
  2110. var currentBrowser;
  2111. var browserVersion;
  2112. var isAndroid;
  2113. var RTCBrowserType = {
  2114. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2115. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2116. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2117. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2118. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2119. getBrowserType: function () {
  2120. return currentBrowser;
  2121. },
  2122. isChrome: function () {
  2123. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2124. },
  2125. isOpera: function () {
  2126. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2127. },
  2128. isFirefox: function () {
  2129. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2130. },
  2131. isIExplorer: function () {
  2132. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2133. },
  2134. isSafari: function () {
  2135. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2136. },
  2137. isTemasysPluginUsed: function () {
  2138. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2139. },
  2140. getFirefoxVersion: function () {
  2141. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2142. },
  2143. getChromeVersion: function () {
  2144. return RTCBrowserType.isChrome() ? browserVersion : null;
  2145. },
  2146. usesPlanB: function() {
  2147. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2148. RTCBrowserType.isTemasysPluginUsed();
  2149. },
  2150. usesUnifiedPlan: function() {
  2151. return RTCBrowserType.isFirefox();
  2152. },
  2153. /**
  2154. * Whether the browser is running on an android device.
  2155. */
  2156. isAndroid: function() {
  2157. return isAndroid;
  2158. }
  2159. // Add version getters for other browsers when needed
  2160. };
  2161. // detectOpera() must be called before detectChrome() !!!
  2162. // otherwise Opera wil be detected as Chrome
  2163. function detectChrome() {
  2164. if (navigator.webkitGetUserMedia) {
  2165. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2166. var userAgent = navigator.userAgent.toLowerCase();
  2167. // We can assume that user agent is chrome, because it's
  2168. // enforced when 'ext' streaming method is set
  2169. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2170. console.log("This appears to be Chrome, ver: " + ver);
  2171. return ver;
  2172. }
  2173. return null;
  2174. }
  2175. function detectOpera() {
  2176. var userAgent = navigator.userAgent;
  2177. if (userAgent.match(/Opera|OPR/)) {
  2178. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2179. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2180. console.info("This appears to be Opera, ver: " + version);
  2181. return version;
  2182. }
  2183. return null;
  2184. }
  2185. function detectFirefox() {
  2186. if (navigator.mozGetUserMedia) {
  2187. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2188. var version = parseInt(
  2189. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2190. console.log('This appears to be Firefox, ver: ' + version);
  2191. return version;
  2192. }
  2193. return null;
  2194. }
  2195. function detectSafari() {
  2196. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2197. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2198. console.info("This appears to be Safari");
  2199. // FIXME detect Safari version when needed
  2200. return 1;
  2201. }
  2202. return null;
  2203. }
  2204. function detectIE() {
  2205. var version;
  2206. var ua = window.navigator.userAgent;
  2207. var msie = ua.indexOf('MSIE ');
  2208. if (msie > 0) {
  2209. // IE 10 or older => return version number
  2210. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2211. }
  2212. var trident = ua.indexOf('Trident/');
  2213. if (!version && trident > 0) {
  2214. // IE 11 => return version number
  2215. var rv = ua.indexOf('rv:');
  2216. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2217. }
  2218. var edge = ua.indexOf('Edge/');
  2219. if (!version && edge > 0) {
  2220. // IE 12 => return version number
  2221. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2222. }
  2223. if (version) {
  2224. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2225. console.info("This appears to be IExplorer, ver: " + version);
  2226. }
  2227. return version;
  2228. }
  2229. function detectBrowser() {
  2230. var version;
  2231. var detectors = [
  2232. detectOpera,
  2233. detectChrome,
  2234. detectFirefox,
  2235. detectIE,
  2236. detectSafari
  2237. ];
  2238. // Try all browser detectors
  2239. for (var i = 0; i < detectors.length; i++) {
  2240. version = detectors[i]();
  2241. if (version)
  2242. return version;
  2243. }
  2244. console.warn("Browser type defaults to Safari ver 1");
  2245. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2246. return 1;
  2247. }
  2248. browserVersion = detectBrowser();
  2249. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2250. module.exports = RTCBrowserType;
  2251. },{}],18:[function(require,module,exports){
  2252. (function (__filename){
  2253. /* global config, require, attachMediaStream, getUserMedia,
  2254. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2255. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2256. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2257. */
  2258. /* jshint -W101 */
  2259. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2260. var RTCBrowserType = require("./RTCBrowserType");
  2261. var Resolutions = require("../../service/RTC/Resolutions");
  2262. var RTCEvents = require("../../service/RTC/RTCEvents");
  2263. var AdapterJS = require("./adapter.screenshare");
  2264. var SDPUtil = require("../xmpp/SDPUtil");
  2265. var EventEmitter = require("events");
  2266. var screenObtainer = require("./ScreenObtainer");
  2267. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2268. var eventEmitter = new EventEmitter();
  2269. var devices = {
  2270. audio: true,
  2271. video: true
  2272. };
  2273. var rtcReady = false;
  2274. function setResolutionConstraints(constraints, resolution) {
  2275. var isAndroid = RTCBrowserType.isAndroid();
  2276. if (Resolutions[resolution]) {
  2277. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2278. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2279. }
  2280. else if (isAndroid) {
  2281. // FIXME can't remember if the purpose of this was to always request
  2282. // low resolution on Android ? if yes it should be moved up front
  2283. constraints.video.mandatory.minWidth = 320;
  2284. constraints.video.mandatory.minHeight = 240;
  2285. constraints.video.mandatory.maxFrameRate = 15;
  2286. }
  2287. if (constraints.video.mandatory.minWidth)
  2288. constraints.video.mandatory.maxWidth =
  2289. constraints.video.mandatory.minWidth;
  2290. if (constraints.video.mandatory.minHeight)
  2291. constraints.video.mandatory.maxHeight =
  2292. constraints.video.mandatory.minHeight;
  2293. }
  2294. /**
  2295. * @param {string[]} um required user media types
  2296. *
  2297. * @param {Object} [options={}] optional parameters
  2298. * @param {string} options.resolution
  2299. * @param {number} options.bandwidth
  2300. * @param {number} options.fps
  2301. * @param {string} options.desktopStream
  2302. * @param {string} options.cameraDeviceId
  2303. * @param {string} options.micDeviceId
  2304. * @param {bool} firefox_fake_device
  2305. */
  2306. function getConstraints(um, options) {
  2307. var constraints = {audio: false, video: false};
  2308. if (um.indexOf('video') >= 0) {
  2309. // same behaviour as true
  2310. constraints.video = { mandatory: {}, optional: [] };
  2311. if (options.cameraDeviceId) {
  2312. constraints.video.optional.push({
  2313. sourceId: options.cameraDeviceId
  2314. });
  2315. }
  2316. constraints.video.optional.push({ googLeakyBucket: true });
  2317. setResolutionConstraints(constraints, options.resolution);
  2318. }
  2319. if (um.indexOf('audio') >= 0) {
  2320. if (!RTCBrowserType.isFirefox()) {
  2321. // same behaviour as true
  2322. constraints.audio = { mandatory: {}, optional: []};
  2323. if (options.micDeviceId) {
  2324. constraints.audio.optional.push({
  2325. sourceId: options.micDeviceId
  2326. });
  2327. }
  2328. // if it is good enough for hangouts...
  2329. constraints.audio.optional.push(
  2330. {googEchoCancellation: true},
  2331. {googAutoGainControl: true},
  2332. {googNoiseSupression: true},
  2333. {googHighpassFilter: true},
  2334. {googNoisesuppression2: true},
  2335. {googEchoCancellation2: true},
  2336. {googAutoGainControl2: true}
  2337. );
  2338. } else {
  2339. if (options.micDeviceId) {
  2340. constraints.audio = {
  2341. mandatory: {},
  2342. optional: [{
  2343. sourceId: options.micDeviceId
  2344. }]};
  2345. } else {
  2346. constraints.audio = true;
  2347. }
  2348. }
  2349. }
  2350. if (um.indexOf('screen') >= 0) {
  2351. if (RTCBrowserType.isChrome()) {
  2352. constraints.video = {
  2353. mandatory: {
  2354. chromeMediaSource: "screen",
  2355. googLeakyBucket: true,
  2356. maxWidth: window.screen.width,
  2357. maxHeight: window.screen.height,
  2358. maxFrameRate: 3
  2359. },
  2360. optional: []
  2361. };
  2362. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2363. constraints.video = {
  2364. optional: [
  2365. {
  2366. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2367. }
  2368. ]
  2369. };
  2370. } else if (RTCBrowserType.isFirefox()) {
  2371. constraints.video = {
  2372. mozMediaSource: "window",
  2373. mediaSource: "window"
  2374. };
  2375. } else {
  2376. logger.error(
  2377. "'screen' WebRTC media source is supported only in Chrome" +
  2378. " and with Temasys plugin");
  2379. }
  2380. }
  2381. if (um.indexOf('desktop') >= 0) {
  2382. constraints.video = {
  2383. mandatory: {
  2384. chromeMediaSource: "desktop",
  2385. chromeMediaSourceId: options.desktopStream,
  2386. googLeakyBucket: true,
  2387. maxWidth: window.screen.width,
  2388. maxHeight: window.screen.height,
  2389. maxFrameRate: 3
  2390. },
  2391. optional: []
  2392. };
  2393. }
  2394. if (options.bandwidth) {
  2395. if (!constraints.video) {
  2396. //same behaviour as true
  2397. constraints.video = {mandatory: {}, optional: []};
  2398. }
  2399. constraints.video.optional.push({bandwidth: options.bandwidth});
  2400. }
  2401. if (options.fps) {
  2402. // for some cameras it might be necessary to request 30fps
  2403. // so they choose 30fps mjpg over 10fps yuy2
  2404. if (!constraints.video) {
  2405. // same behaviour as true;
  2406. constraints.video = {mandatory: {}, optional: []};
  2407. }
  2408. constraints.video.mandatory.minFrameRate = options.fps;
  2409. }
  2410. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2411. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2412. // this later can be a problem with some of the tests
  2413. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2414. {
  2415. // seems to be fixed now, removing this experimental fix, as having
  2416. // multiple audio tracks brake the tests
  2417. //constraints.audio = true;
  2418. constraints.fake = true;
  2419. }
  2420. return constraints;
  2421. }
  2422. function setAvailableDevices(um, available) {
  2423. if (um.indexOf("video") != -1) {
  2424. devices.video = available;
  2425. }
  2426. if (um.indexOf("audio") != -1) {
  2427. devices.audio = available;
  2428. }
  2429. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2430. }
  2431. // In case of IE we continue from 'onReady' callback
  2432. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2433. // once it is initialized.
  2434. function onReady (options, GUM) {
  2435. rtcReady = true;
  2436. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2437. screenObtainer.init(eventEmitter, options, GUM);
  2438. }
  2439. /**
  2440. * Apply function with arguments if function exists.
  2441. * Do nothing if function not provided.
  2442. * @param {function} [fn] function to apply
  2443. * @param {Array} [args=[]] arguments for function
  2444. */
  2445. function maybeApply(fn, args) {
  2446. if (fn) {
  2447. fn.apply(null, args || []);
  2448. }
  2449. }
  2450. var getUserMediaStatus = {
  2451. initialized: false,
  2452. callbacks: []
  2453. };
  2454. /**
  2455. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2456. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2457. * @param {Function} getUserMedia native function
  2458. * @returns {Function} wrapped function
  2459. */
  2460. function wrapGetUserMedia(getUserMedia) {
  2461. return function (constraints, successCallback, errorCallback) {
  2462. getUserMedia(constraints, function (stream) {
  2463. maybeApply(successCallback, [stream]);
  2464. if (!getUserMediaStatus.initialized) {
  2465. getUserMediaStatus.initialized = true;
  2466. getUserMediaStatus.callbacks.forEach(function (callback) {
  2467. callback();
  2468. });
  2469. getUserMediaStatus.callbacks.length = 0;
  2470. }
  2471. }, function (error) {
  2472. maybeApply(errorCallback, [error]);
  2473. });
  2474. };
  2475. }
  2476. /**
  2477. * Create stub device which equals to auto selected device.
  2478. * @param {string} kind if that should be `audio` or `video` device
  2479. * @returns {Object} stub device description in `enumerateDevices` format
  2480. */
  2481. function createAutoDeviceInfo(kind) {
  2482. return {
  2483. facing: null,
  2484. label: 'Auto',
  2485. kind: kind,
  2486. deviceId: '',
  2487. groupId: null
  2488. };
  2489. }
  2490. /**
  2491. * Execute function after getUserMedia was executed at least once.
  2492. * @param {Function} callback function to execute after getUserMedia
  2493. */
  2494. function afterUserMediaInitialized(callback) {
  2495. if (getUserMediaStatus.initialized) {
  2496. callback();
  2497. } else {
  2498. getUserMediaStatus.callbacks.push(callback);
  2499. }
  2500. }
  2501. /**
  2502. * Wrapper function which makes enumerateDevices to wait
  2503. * until someone executes getUserMedia first time.
  2504. * @param {Function} enumerateDevices native function
  2505. * @returns {Funtion} wrapped function
  2506. */
  2507. function wrapEnumerateDevices(enumerateDevices) {
  2508. return function (callback) {
  2509. // enumerate devices only after initial getUserMedia
  2510. afterUserMediaInitialized(function () {
  2511. enumerateDevices().then(function (devices) {
  2512. //add auto devices
  2513. devices.unshift(
  2514. createAutoDeviceInfo('audioinput'),
  2515. createAutoDeviceInfo('videoinput')
  2516. );
  2517. callback(devices);
  2518. }, function (err) {
  2519. console.error('cannot enumerate devices: ', err);
  2520. // return only auto devices
  2521. callback([createAutoDeviceInfo('audioInput'),
  2522. createAutoDeviceInfo('videoinput')]);
  2523. });
  2524. });
  2525. };
  2526. }
  2527. /**
  2528. * Use old MediaStreamTrack to get devices list and
  2529. * convert it to enumerateDevices format.
  2530. * @param {Function} callback function to call when received devices list.
  2531. */
  2532. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2533. MediaStreamTrack.getSources(function (sources) {
  2534. var devices = sources.map(function (source) {
  2535. var kind = (source.kind || '').toLowerCase();
  2536. return {
  2537. facing: source.facing || null,
  2538. label: source.label,
  2539. kind: kind ? kind + 'input': null,
  2540. deviceId: source.id,
  2541. groupId: source.groupId || null
  2542. };
  2543. });
  2544. //add auto devices
  2545. devices.unshift(
  2546. createAutoDeviceInfo('audioinput'),
  2547. createAutoDeviceInfo('videoinput')
  2548. );
  2549. callback(devices);
  2550. });
  2551. }
  2552. function obtainDevices(options) {
  2553. if(!options.devices || options.devices.length === 0) {
  2554. return options.successCallback(options.streams || {});
  2555. }
  2556. var device = options.devices.splice(0, 1);
  2557. var devices = [];
  2558. devices.push(device);
  2559. options.deviceGUM[device](function (stream) {
  2560. options.streams = options.streams || {};
  2561. options.streams[device] = stream;
  2562. obtainDevices(options);
  2563. },
  2564. function (error) {
  2565. Object.keys(options.streams).forEach(function(device) {
  2566. RTCUtils.stopMediaStream(options.streams[device]);
  2567. });
  2568. logger.error(
  2569. "failed to obtain " + device + " stream - stop", error);
  2570. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  2571. });
  2572. }
  2573. /**
  2574. * Handles the newly created Media Streams.
  2575. * @param streams the new Media Streams
  2576. * @param resolution the resolution of the video streams
  2577. * @returns {*[]} object that describes the new streams
  2578. */
  2579. function handleLocalStream(streams, resolution) {
  2580. var audioStream, videoStream, desktopStream, res = [];
  2581. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2582. // an object with two properties: audioStream, videoStream.
  2583. if (window.webkitMediaStream) {
  2584. var audioVideo = streams.audioVideo;
  2585. if (audioVideo) {
  2586. var audioTracks = audioVideo.getAudioTracks();
  2587. if(audioTracks.length) {
  2588. audioStream = new webkitMediaStream();
  2589. for (var i = 0; i < audioTracks.length; i++) {
  2590. audioStream.addTrack(audioTracks[i]);
  2591. }
  2592. }
  2593. var videoTracks = audioVideo.getVideoTracks();
  2594. if(videoTracks.length) {
  2595. videoStream = new webkitMediaStream();
  2596. for (var j = 0; j < videoTracks.length; j++) {
  2597. videoStream.addTrack(videoTracks[j]);
  2598. }
  2599. }
  2600. }
  2601. if (streams && streams.desktopStream)
  2602. desktopStream = streams.desktopStream;
  2603. }
  2604. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2605. if (streams && streams.audio)
  2606. audioStream = streams.audio;
  2607. if (streams && streams.video)
  2608. videoStream = streams.video;
  2609. if(streams && streams.desktop)
  2610. desktopStream = streams.desktop;
  2611. }
  2612. if (desktopStream)
  2613. res.push({stream: desktopStream,
  2614. type: "video", videoType: "desktop"});
  2615. if(audioStream)
  2616. res.push({stream: audioStream, type: "audio", videoType: null});
  2617. if(videoStream)
  2618. res.push({stream: videoStream, type: "video", videoType: "camera",
  2619. resolution: resolution});
  2620. return res;
  2621. }
  2622. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2623. var RTCUtils = {
  2624. init: function (options) {
  2625. return new Promise(function(resolve, reject) {
  2626. if (RTCBrowserType.isFirefox()) {
  2627. var FFversion = RTCBrowserType.getFirefoxVersion();
  2628. if (FFversion < 40) {
  2629. logger.error(
  2630. "Firefox version too old: " + FFversion +
  2631. ". Required >= 40.");
  2632. reject(new Error("Firefox version too old: " + FFversion +
  2633. ". Required >= 40."));
  2634. return;
  2635. }
  2636. this.peerconnection = mozRTCPeerConnection;
  2637. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2638. this.enumerateDevices = wrapEnumerateDevices(
  2639. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2640. );
  2641. this.pc_constraints = {};
  2642. this.attachMediaStream = function (element, stream) {
  2643. // srcObject is being standardized and FF will eventually
  2644. // support that unprefixed. FF also supports the
  2645. // "element.src = URL.createObjectURL(...)" combo, but that
  2646. // will be deprecated in favour of srcObject.
  2647. //
  2648. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2649. // https://github.com/webrtc/samples/issues/302
  2650. if (!element[0])
  2651. return;
  2652. element[0].mozSrcObject = stream;
  2653. element[0].play();
  2654. };
  2655. this.getStreamID = function (stream) {
  2656. var id = stream.id;
  2657. if (!id) {
  2658. var tracks = stream.getVideoTracks();
  2659. if (!tracks || tracks.length === 0) {
  2660. tracks = stream.getAudioTracks();
  2661. }
  2662. id = tracks[0].id;
  2663. }
  2664. return SDPUtil.filter_special_chars(id);
  2665. };
  2666. this.getVideoSrc = function (element) {
  2667. if (!element)
  2668. return null;
  2669. return element.mozSrcObject;
  2670. };
  2671. this.setVideoSrc = function (element, src) {
  2672. if (element)
  2673. element.mozSrcObject = src;
  2674. };
  2675. RTCSessionDescription = mozRTCSessionDescription;
  2676. RTCIceCandidate = mozRTCIceCandidate;
  2677. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2678. this.peerconnection = webkitRTCPeerConnection;
  2679. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2680. if (navigator.mediaDevices) {
  2681. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2682. this.enumerateDevices = wrapEnumerateDevices(
  2683. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2684. );
  2685. } else {
  2686. this.getUserMedia = getUserMedia;
  2687. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2688. }
  2689. this.attachMediaStream = function (element, stream) {
  2690. // saves the created url for the stream, so we can reuse it
  2691. // and not keep creating urls
  2692. if (!stream.jitsiObjectURL) {
  2693. stream.jitsiObjectURL
  2694. = webkitURL.createObjectURL(stream);
  2695. }
  2696. element.attr('src', stream.jitsiObjectURL);
  2697. };
  2698. this.getStreamID = function (stream) {
  2699. // streams from FF endpoints have the characters '{' and '}'
  2700. // that make jQuery choke.
  2701. return SDPUtil.filter_special_chars(stream.id);
  2702. };
  2703. this.getVideoSrc = function (element) {
  2704. if (!element)
  2705. return null;
  2706. return element.getAttribute("src");
  2707. };
  2708. this.setVideoSrc = function (element, src) {
  2709. if (element)
  2710. element.setAttribute("src", src);
  2711. };
  2712. // DTLS should now be enabled by default but..
  2713. this.pc_constraints = {'optional': [
  2714. {'DtlsSrtpKeyAgreement': 'true'}
  2715. ]};
  2716. if (options.useIPv6) {
  2717. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2718. this.pc_constraints.optional.push({googIPv6: true});
  2719. }
  2720. if (RTCBrowserType.isAndroid()) {
  2721. this.pc_constraints = {}; // disable DTLS on Android
  2722. }
  2723. if (!webkitMediaStream.prototype.getVideoTracks) {
  2724. webkitMediaStream.prototype.getVideoTracks = function () {
  2725. return this.videoTracks;
  2726. };
  2727. }
  2728. if (!webkitMediaStream.prototype.getAudioTracks) {
  2729. webkitMediaStream.prototype.getAudioTracks = function () {
  2730. return this.audioTracks;
  2731. };
  2732. }
  2733. }
  2734. // Detect IE/Safari
  2735. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2736. //AdapterJS.WebRTCPlugin.setLogLevel(
  2737. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2738. var self = this;
  2739. AdapterJS.webRTCReady(function (isPlugin) {
  2740. self.peerconnection = RTCPeerConnection;
  2741. self.getUserMedia = window.getUserMedia;
  2742. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2743. self.attachMediaStream = function (elSel, stream) {
  2744. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2745. return;
  2746. }
  2747. attachMediaStream(elSel[0], stream);
  2748. };
  2749. self.getStreamID = function (stream) {
  2750. var id = SDPUtil.filter_special_chars(stream.label);
  2751. return id;
  2752. };
  2753. self.getVideoSrc = function (element) {
  2754. if (!element) {
  2755. logger.warn("Attempt to get video SRC of null element");
  2756. return null;
  2757. }
  2758. var children = element.children;
  2759. for (var i = 0; i !== children.length; ++i) {
  2760. if (children[i].name === 'streamId') {
  2761. return children[i].value;
  2762. }
  2763. }
  2764. //logger.info(element.id + " SRC: " + src);
  2765. return null;
  2766. };
  2767. self.setVideoSrc = function (element, src) {
  2768. //logger.info("Set video src: ", element, src);
  2769. if (!src) {
  2770. logger.warn("Not attaching video stream, 'src' is null");
  2771. return;
  2772. }
  2773. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2774. var stream = AdapterJS.WebRTCPlugin.plugin
  2775. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2776. attachMediaStream(element, stream);
  2777. };
  2778. onReady(options, self.getUserMediaWithConstraints);
  2779. resolve();
  2780. });
  2781. } else {
  2782. try {
  2783. logger.error('Browser does not appear to be WebRTC-capable');
  2784. } catch (e) {
  2785. }
  2786. reject('Browser does not appear to be WebRTC-capable');
  2787. return;
  2788. }
  2789. // Call onReady() if Temasys plugin is not used
  2790. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2791. onReady(options, this.getUserMediaWithConstraints);
  2792. resolve();
  2793. }
  2794. }.bind(this));
  2795. },
  2796. /**
  2797. * @param {string[]} um required user media types
  2798. * @param {function} success_callback
  2799. * @param {Function} failure_callback
  2800. * @param {Object} [options] optional parameters
  2801. * @param {string} options.resolution
  2802. * @param {number} options.bandwidth
  2803. * @param {number} options.fps
  2804. * @param {string} options.desktopStream
  2805. * @param {string} options.cameraDeviceId
  2806. * @param {string} options.micDeviceId
  2807. **/
  2808. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2809. options = options || {};
  2810. var resolution = options.resolution;
  2811. var constraints = getConstraints(um, options);
  2812. logger.info("Get media constraints", constraints);
  2813. try {
  2814. this.getUserMedia(constraints,
  2815. function (stream) {
  2816. logger.log('onUserMediaSuccess');
  2817. setAvailableDevices(um, true);
  2818. success_callback(stream);
  2819. },
  2820. function (error) {
  2821. setAvailableDevices(um, false);
  2822. logger.warn('Failed to get access to local media. Error ',
  2823. error, constraints);
  2824. if (failure_callback) {
  2825. failure_callback(error, resolution);
  2826. }
  2827. });
  2828. } catch (e) {
  2829. logger.error('GUM failed: ', e);
  2830. if (failure_callback) {
  2831. failure_callback(e);
  2832. }
  2833. }
  2834. },
  2835. /**
  2836. * Creates the local MediaStreams.
  2837. * @param {Object} [options] optional parameters
  2838. * @param {Array} options.devices the devices that will be requested
  2839. * @param {string} options.resolution resolution constraints
  2840. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2841. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2842. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2843. * @param {string} options.cameraDeviceId
  2844. * @param {string} options.micDeviceId
  2845. * @returns {*} Promise object that will receive the new JitsiTracks
  2846. */
  2847. obtainAudioAndVideoPermissions: function (options) {
  2848. var self = this;
  2849. options = options || {};
  2850. return new Promise(function (resolve, reject) {
  2851. var successCallback = function (stream) {
  2852. resolve(handleLocalStream(stream, options.resolution));
  2853. };
  2854. options.devices = options.devices || ['audio', 'video'];
  2855. if(!screenObtainer.isSupported()
  2856. && options.devices.indexOf("desktop") !== -1){
  2857. reject(new Error("Desktop sharing is not supported!"));
  2858. }
  2859. if (RTCBrowserType.isFirefox() ||
  2860. RTCBrowserType.isTemasysPluginUsed()) {
  2861. var GUM = function (device, s, e) {
  2862. this.getUserMediaWithConstraints(device, s, e, options);
  2863. };
  2864. var deviceGUM = {
  2865. "audio": GUM.bind(self, ["audio"]),
  2866. "video": GUM.bind(self, ["video"])
  2867. };
  2868. if(screenObtainer.isSupported()){
  2869. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  2870. screenObtainer);
  2871. }
  2872. // With FF/IE we can't split the stream into audio and video because FF
  2873. // doesn't support media stream constructors. So, we need to get the
  2874. // audio stream separately from the video stream using two distinct GUM
  2875. // calls. Not very user friendly :-( but we don't have many other
  2876. // options neither.
  2877. //
  2878. // Note that we pack those 2 streams in a single object and pass it to
  2879. // the successCallback method.
  2880. obtainDevices({
  2881. devices: options.devices,
  2882. streams: [],
  2883. successCallback: successCallback,
  2884. errorCallback: reject,
  2885. deviceGUM: deviceGUM
  2886. });
  2887. } else {
  2888. var hasDesktop = options.devices.indexOf('desktop') > -1;
  2889. if (hasDesktop) {
  2890. options.devices.splice(options.devices.indexOf("desktop"), 1);
  2891. }
  2892. options.resolution = options.resolution || '360';
  2893. if(options.devices.length) {
  2894. this.getUserMediaWithConstraints(
  2895. options.devices,
  2896. function (stream) {
  2897. if((options.devices.indexOf("audio") !== -1 &&
  2898. !stream.getAudioTracks().length) ||
  2899. (options.devices.indexOf("video") !== -1 &&
  2900. !stream.getVideoTracks().length))
  2901. {
  2902. self.stopMediaStream(stream);
  2903. reject(JitsiTrackErrors.parseError(
  2904. new Error("Unable to get the audio and " +
  2905. "video tracks."),
  2906. options.devices));
  2907. return;
  2908. }
  2909. if(hasDesktop) {
  2910. screenObtainer.obtainStream(
  2911. function (desktopStream) {
  2912. successCallback({audioVideo: stream,
  2913. desktopStream: desktopStream});
  2914. }, function (error) {
  2915. self.stopMediaStream(stream);
  2916. reject(
  2917. JitsiTrackErrors.parseError(error,
  2918. options.devices));
  2919. });
  2920. } else {
  2921. successCallback({audioVideo: stream});
  2922. }
  2923. },
  2924. function (error) {
  2925. reject(JitsiTrackErrors.parseError(error,
  2926. options.devices));
  2927. },
  2928. options);
  2929. } else if (hasDesktop) {
  2930. screenObtainer.obtainStream(
  2931. function (stream) {
  2932. successCallback({desktopStream: stream});
  2933. }, function (error) {
  2934. reject(
  2935. JitsiTrackErrors.parseError(error,
  2936. ["desktop"]));
  2937. });
  2938. }
  2939. }
  2940. }.bind(this));
  2941. },
  2942. addListener: function (eventType, listener) {
  2943. eventEmitter.on(eventType, listener);
  2944. },
  2945. removeListener: function (eventType, listener) {
  2946. eventEmitter.removeListener(eventType, listener);
  2947. },
  2948. getDeviceAvailability: function () {
  2949. return devices;
  2950. },
  2951. isRTCReady: function () {
  2952. return rtcReady;
  2953. },
  2954. /**
  2955. * Checks if its possible to enumerate available cameras/micropones.
  2956. * @returns {boolean} true if available, false otherwise.
  2957. */
  2958. isDeviceListAvailable: function () {
  2959. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2960. if (isEnumerateDevicesAvailable) {
  2961. return true;
  2962. }
  2963. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2964. },
  2965. /**
  2966. * Returns true if changing the camera / microphone device is supported and
  2967. * false if not.
  2968. */
  2969. isDeviceChangeAvailable: function () {
  2970. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2971. RTCBrowserType.isTemasysPluginUsed())
  2972. return true;
  2973. return false;
  2974. },
  2975. /**
  2976. * A method to handle stopping of the stream.
  2977. * One point to handle the differences in various implementations.
  2978. * @param mediaStream MediaStream object to stop.
  2979. */
  2980. stopMediaStream: function (mediaStream) {
  2981. mediaStream.getTracks().forEach(function (track) {
  2982. // stop() not supported with IE
  2983. if (track.stop) {
  2984. track.stop();
  2985. }
  2986. });
  2987. // leave stop for implementation still using it
  2988. if (mediaStream.stop) {
  2989. mediaStream.stop();
  2990. }
  2991. // if we have done createObjectURL, lets clean it
  2992. if (mediaStream.jitsiObjectURL) {
  2993. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  2994. }
  2995. },
  2996. /**
  2997. * Returns whether the desktop sharing is enabled or not.
  2998. * @returns {boolean}
  2999. */
  3000. isDesktopSharingEnabled: function () {
  3001. return screenObtainer.isSupported();
  3002. }
  3003. };
  3004. module.exports = RTCUtils;
  3005. }).call(this,"/modules/RTC/RTCUtils.js")
  3006. },{"../../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){
  3007. (function (__filename){
  3008. /* global chrome, $, alert */
  3009. /* jshint -W003 */
  3010. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3011. var RTCBrowserType = require("./RTCBrowserType");
  3012. var AdapterJS = require("./adapter.screenshare");
  3013. var DesktopSharingEventTypes
  3014. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3015. /**
  3016. * Indicates whether the Chrome desktop sharing extension is installed.
  3017. * @type {boolean}
  3018. */
  3019. var chromeExtInstalled = false;
  3020. /**
  3021. * Indicates whether an update of the Chrome desktop sharing extension is
  3022. * required.
  3023. * @type {boolean}
  3024. */
  3025. var chromeExtUpdateRequired = false;
  3026. /**
  3027. * Whether the jidesha extension for firefox is installed for the domain on
  3028. * which we are running. Null designates an unknown value.
  3029. * @type {null}
  3030. */
  3031. var firefoxExtInstalled = null;
  3032. /**
  3033. * If set to true, detection of an installed firefox extension will be started
  3034. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3035. * user tries to enable screen sharing).
  3036. */
  3037. var reDetectFirefoxExtension = false;
  3038. var GUM = null;
  3039. /**
  3040. * Handles obtaining a stream from a screen capture on different browsers.
  3041. */
  3042. var ScreenObtainer = {
  3043. /**
  3044. * The EventEmitter to use to emit events.
  3045. * @type {null}
  3046. */
  3047. eventEmitter: null,
  3048. obtainStream: null,
  3049. /**
  3050. * Initializes the function used to obtain a screen capture
  3051. * (this.obtainStream).
  3052. *
  3053. * If the browser is Chrome, it uses the value of
  3054. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3055. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3056. * use the "screen" media source (if the value is 'webrtc'),
  3057. * or disable screen capture (if the value is other).
  3058. * Note that for the "screen" media source to work the
  3059. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3060. */
  3061. init: function(eventEmitter, options, gum) {
  3062. this.eventEmitter = eventEmitter;
  3063. var obtainDesktopStream = null;
  3064. this.options = options = options || {};
  3065. GUM = gum;
  3066. if (RTCBrowserType.isFirefox())
  3067. initFirefoxExtensionDetection(options);
  3068. // TODO remove this, options.desktopSharing is deprecated.
  3069. var chromeMethod =
  3070. (options.desktopSharingChromeMethod || options.desktopSharing);
  3071. if (RTCBrowserType.isTemasysPluginUsed()) {
  3072. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3073. logger.info("Screensharing not supported by this plugin " +
  3074. "version");
  3075. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3076. logger.info(
  3077. "Screensharing not available with Temasys plugin on" +
  3078. " this site");
  3079. } else {
  3080. obtainDesktopStream = obtainWebRTCScreen;
  3081. logger.info("Using Temasys plugin for desktop sharing");
  3082. }
  3083. } else if (RTCBrowserType.isChrome()) {
  3084. if (chromeMethod == "ext") {
  3085. if (RTCBrowserType.getChromeVersion() >= 34) {
  3086. obtainDesktopStream =
  3087. this.obtainScreenFromExtension;
  3088. logger.info("Using Chrome extension for desktop sharing");
  3089. initChromeExtension(options);
  3090. } else {
  3091. logger.info("Chrome extension not supported until ver 34");
  3092. }
  3093. } else if (chromeMethod == "webrtc") {
  3094. obtainDesktopStream = obtainWebRTCScreen;
  3095. logger.info("Using Chrome WebRTC for desktop sharing");
  3096. }
  3097. } else if (RTCBrowserType.isFirefox()) {
  3098. if (options.desktopSharingFirefoxDisabled) {
  3099. obtainDesktopStream = null;
  3100. } else if (window.location.protocol === "http:"){
  3101. logger.log("Screen sharing is not supported over HTTP. " +
  3102. "Use of HTTPS is required.");
  3103. obtainDesktopStream = null;
  3104. } else {
  3105. obtainDesktopStream = this.obtainScreenOnFirefox;
  3106. }
  3107. }
  3108. if (!obtainDesktopStream) {
  3109. logger.info("Desktop sharing disabled");
  3110. }
  3111. this.obtainStream = obtainDesktopStream;
  3112. },
  3113. /**
  3114. * Checks whether obtaining a screen capture is supported in the current
  3115. * environment.
  3116. * @returns {boolean}
  3117. */
  3118. isSupported: function() {
  3119. return !!this.obtainStream;
  3120. },
  3121. /**
  3122. * Obtains a screen capture stream on Firefox.
  3123. * @param callback
  3124. * @param errorCallback
  3125. */
  3126. obtainScreenOnFirefox:
  3127. function (callback, errorCallback) {
  3128. var self = this;
  3129. var extensionRequired = false;
  3130. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3131. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3132. RTCBrowserType.getFirefoxVersion() <=
  3133. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3134. extensionRequired = true;
  3135. logger.log("Jidesha extension required on firefox version " +
  3136. RTCBrowserType.getFirefoxVersion());
  3137. }
  3138. if (!extensionRequired || firefoxExtInstalled === true) {
  3139. obtainWebRTCScreen(callback, errorCallback);
  3140. return;
  3141. }
  3142. if (reDetectFirefoxExtension) {
  3143. reDetectFirefoxExtension = false;
  3144. initFirefoxExtensionDetection(this.options);
  3145. }
  3146. // Give it some (more) time to initialize, and assume lack of
  3147. // extension if it hasn't.
  3148. if (firefoxExtInstalled === null) {
  3149. window.setTimeout(
  3150. function() {
  3151. if (firefoxExtInstalled === null)
  3152. firefoxExtInstalled = false;
  3153. self.obtainScreenOnFirefox(callback, errorCallback);
  3154. },
  3155. 300
  3156. );
  3157. logger.log("Waiting for detection of jidesha on firefox to " +
  3158. "finish.");
  3159. return;
  3160. }
  3161. // We need an extension and it isn't installed.
  3162. // Make sure we check for the extension when the user clicks again.
  3163. firefoxExtInstalled = null;
  3164. reDetectFirefoxExtension = true;
  3165. // Prompt the user to install the extension
  3166. this.eventEmitter.emit(
  3167. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  3168. this.options.desktopSharingFirefoxExtensionURL);
  3169. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3170. // stuck in 'switching' mode.
  3171. errorCallback('Firefox extension required.');
  3172. },
  3173. /**
  3174. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3175. * 'desktop' stream for returned stream token.
  3176. */
  3177. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3178. if (chromeExtInstalled) {
  3179. doGetStreamFromExtension(this.options, streamCallback,
  3180. failCallback);
  3181. } else {
  3182. if (chromeExtUpdateRequired) {
  3183. alert(
  3184. 'Jitsi Desktop Streamer requires update. ' +
  3185. 'Changes will take effect after next Chrome restart.');
  3186. }
  3187. chrome.webstore.install(
  3188. getWebStoreInstallUrl(this.options),
  3189. function (arg) {
  3190. logger.log("Extension installed successfully", arg);
  3191. chromeExtInstalled = true;
  3192. // We need to give a moment for the endpoint to become
  3193. // available
  3194. window.setTimeout(function () {
  3195. doGetStreamFromExtension(this.options, streamCallback,
  3196. failCallback);
  3197. }, 500);
  3198. },
  3199. function (arg) {
  3200. logger.log("Failed to install the extension", arg);
  3201. failCallback(arg);
  3202. }
  3203. );
  3204. }
  3205. }
  3206. };
  3207. /**
  3208. * Obtains a desktop stream using getUserMedia.
  3209. * For this to work on Chrome, the
  3210. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3211. *
  3212. * On firefox, the document's domain must be white-listed in the
  3213. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3214. * 'about:config'.
  3215. */
  3216. function obtainWebRTCScreen(streamCallback, failCallback) {
  3217. GUM(
  3218. ['screen'],
  3219. streamCallback,
  3220. failCallback
  3221. );
  3222. }
  3223. /**
  3224. * Constructs inline install URL for Chrome desktop streaming extension.
  3225. * The 'chromeExtensionId' must be defined in options parameter.
  3226. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3227. * @returns {string}
  3228. */
  3229. function getWebStoreInstallUrl(options)
  3230. {
  3231. //TODO remove chromeExtensionId (deprecated)
  3232. return "https://chrome.google.com/webstore/detail/" +
  3233. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3234. }
  3235. /**
  3236. * Checks whether an update of the Chrome extension is required.
  3237. * @param minVersion minimal required version
  3238. * @param extVersion current extension version
  3239. * @returns {boolean}
  3240. */
  3241. function isUpdateRequired(minVersion, extVersion) {
  3242. try {
  3243. var s1 = minVersion.split('.');
  3244. var s2 = extVersion.split('.');
  3245. var len = Math.max(s1.length, s2.length);
  3246. for (var i = 0; i < len; i++) {
  3247. var n1 = 0,
  3248. n2 = 0;
  3249. if (i < s1.length)
  3250. n1 = parseInt(s1[i]);
  3251. if (i < s2.length)
  3252. n2 = parseInt(s2[i]);
  3253. if (isNaN(n1) || isNaN(n2)) {
  3254. return true;
  3255. } else if (n1 !== n2) {
  3256. return n1 > n2;
  3257. }
  3258. }
  3259. // will happen if both versions have identical numbers in
  3260. // their components (even if one of them is longer, has more components)
  3261. return false;
  3262. }
  3263. catch (e) {
  3264. logger.error("Failed to parse extension version", e);
  3265. return true;
  3266. }
  3267. }
  3268. function checkChromeExtInstalled(callback, options) {
  3269. if (!chrome || !chrome.runtime) {
  3270. // No API, so no extension for sure
  3271. callback(false, false);
  3272. return;
  3273. }
  3274. chrome.runtime.sendMessage(
  3275. //TODO: remove chromeExtensionId (deprecated)
  3276. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3277. { getVersion: true },
  3278. function (response) {
  3279. if (!response || !response.version) {
  3280. // Communication failure - assume that no endpoint exists
  3281. logger.warn(
  3282. "Extension not installed?: ", chrome.runtime.lastError);
  3283. callback(false, false);
  3284. return;
  3285. }
  3286. // Check installed extension version
  3287. var extVersion = response.version;
  3288. logger.log('Extension version is: ' + extVersion);
  3289. //TODO: remove minChromeExtVersion (deprecated)
  3290. var updateRequired
  3291. = isUpdateRequired(
  3292. (options.desktopSharingChromeMinExtVersion ||
  3293. options.minChromeExtVersion),
  3294. extVersion);
  3295. callback(!updateRequired, updateRequired);
  3296. }
  3297. );
  3298. }
  3299. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3300. // Sends 'getStream' msg to the extension.
  3301. // Extension id must be defined in the config.
  3302. chrome.runtime.sendMessage(
  3303. //TODO: remove chromeExtensionId (deprecated)
  3304. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3305. {
  3306. getStream: true,
  3307. //TODO: remove desktopSharingSources (deprecated).
  3308. sources: (options.desktopSharingChromeSources ||
  3309. options.desktopSharingSources)
  3310. },
  3311. function (response) {
  3312. if (!response) {
  3313. failCallback(chrome.runtime.lastError);
  3314. return;
  3315. }
  3316. logger.log("Response from extension: " + response);
  3317. if (response.streamId) {
  3318. GUM(
  3319. ['desktop'],
  3320. function (stream) {
  3321. streamCallback(stream);
  3322. },
  3323. failCallback,
  3324. {desktopStream: response.streamId});
  3325. } else {
  3326. failCallback("Extension failed to get the stream");
  3327. }
  3328. }
  3329. );
  3330. }
  3331. /**
  3332. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3333. * config.js to support inline installs. Host site must be selected as main
  3334. * website of published extension.
  3335. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3336. */
  3337. function initInlineInstalls(options)
  3338. {
  3339. $("link[rel=chrome-webstore-item]").attr("href",
  3340. getWebStoreInstallUrl(options));
  3341. }
  3342. function initChromeExtension(options) {
  3343. // Initialize Chrome extension inline installs
  3344. initInlineInstalls(options);
  3345. // Check if extension is installed
  3346. checkChromeExtInstalled(function (installed, updateRequired) {
  3347. chromeExtInstalled = installed;
  3348. chromeExtUpdateRequired = updateRequired;
  3349. logger.info(
  3350. "Chrome extension installed: " + chromeExtInstalled +
  3351. " updateRequired: " + chromeExtUpdateRequired);
  3352. }, options);
  3353. }
  3354. /**
  3355. * Starts the detection of an installed jidesha extension for firefox.
  3356. * @param options supports "desktopSharingFirefoxDisabled",
  3357. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3358. */
  3359. function initFirefoxExtensionDetection(options) {
  3360. if (options.desktopSharingFirefoxDisabled) {
  3361. return;
  3362. }
  3363. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3364. return;
  3365. if (!options.desktopSharingFirefoxExtId) {
  3366. firefoxExtInstalled = false;
  3367. return;
  3368. }
  3369. var img = document.createElement('img');
  3370. img.onload = function(){
  3371. logger.log("Detected firefox screen sharing extension.");
  3372. firefoxExtInstalled = true;
  3373. };
  3374. img.onerror = function(){
  3375. logger.log("Detected lack of firefox screen sharing extension.");
  3376. firefoxExtInstalled = false;
  3377. };
  3378. // The jidesha extension exposes an empty image file under the url:
  3379. // "chrome://EXT_ID/content/DOMAIN.png"
  3380. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3381. // DOMAIN is a domain whitelisted by the extension.
  3382. var src = "chrome://" +
  3383. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3384. "/content/" + document.location.hostname + ".png";
  3385. img.setAttribute('src', src);
  3386. }
  3387. module.exports = ScreenObtainer;
  3388. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3389. },{"../../service/desktopsharing/DesktopSharingEventTypes":84,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":48}],20:[function(require,module,exports){
  3390. (function (__filename){
  3391. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3392. var console = require("jitsi-meet-logger").getLogger(__filename);
  3393. // Adapter's interface.
  3394. var AdapterJS = AdapterJS || {};
  3395. // Browserify compatibility
  3396. if(typeof exports !== 'undefined') {
  3397. module.exports = AdapterJS;
  3398. }
  3399. AdapterJS.options = AdapterJS.options || {};
  3400. // uncomment to get virtual webcams
  3401. // AdapterJS.options.getAllCams = true;
  3402. // uncomment to prevent the install prompt when the plugin in not yet installed
  3403. // AdapterJS.options.hidePluginInstallPrompt = true;
  3404. // AdapterJS version
  3405. AdapterJS.VERSION = '0.12.3';
  3406. // This function will be called when the WebRTC API is ready to be used
  3407. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3408. // the plugin
  3409. // You may Override this function to synchronise the start of your application
  3410. // with the WebRTC API being ready.
  3411. // If you decide not to override use this synchronisation, it may result in
  3412. // an extensive CPU usage on the plugin start (once per tab loaded)
  3413. // Params:
  3414. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3415. //
  3416. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3417. // The WebRTC API is ready.
  3418. // Override me and do whatever you want here
  3419. };
  3420. // Sets a callback function to be called when the WebRTC interface is ready.
  3421. // The first argument is the function to callback.\
  3422. // Throws an error if the first argument is not a function
  3423. AdapterJS.webRTCReady = function (callback) {
  3424. if (typeof callback !== 'function') {
  3425. throw new Error('Callback provided is not a function');
  3426. }
  3427. if (true === AdapterJS.onwebrtcreadyDone) {
  3428. // All WebRTC interfaces are ready, just call the callback
  3429. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3430. } else {
  3431. // will be triggered automatically when your browser/plugin is ready.
  3432. AdapterJS.onwebrtcready = callback;
  3433. }
  3434. };
  3435. // Plugin namespace
  3436. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3437. // The object to store plugin information
  3438. AdapterJS.WebRTCPlugin.pluginInfo = {
  3439. prefix : 'Tem',
  3440. plugName : 'TemWebRTCPlugin',
  3441. pluginId : 'plugin0',
  3442. type : 'application/x-temwebrtcplugin',
  3443. onload : '__TemWebRTCReady0',
  3444. portalLink : 'http://skylink.io/plugin/',
  3445. downloadLink : null, //set below
  3446. companyName: 'Temasys'
  3447. };
  3448. if(!!navigator.platform.match(/^Mac/i)) {
  3449. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3450. }
  3451. else if(!!navigator.platform.match(/^Win/i)) {
  3452. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3453. }
  3454. AdapterJS.WebRTCPlugin.TAGS = {
  3455. NONE : 'none',
  3456. AUDIO : 'audio',
  3457. VIDEO : 'video'
  3458. };
  3459. // Unique identifier of each opened page
  3460. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3461. // Use this whenever you want to call the plugin.
  3462. AdapterJS.WebRTCPlugin.plugin = null;
  3463. // Set log level for the plugin once it is ready.
  3464. // The different values are
  3465. // This is an asynchronous function that will run when the plugin is ready
  3466. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3467. // Defines webrtc's JS interface according to the plugin's implementation.
  3468. // Define plugin Browsers as WebRTC Interface.
  3469. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3470. // This function detects whether or not a plugin is installed.
  3471. // Checks if Not IE (firefox, for example), else if it's IE,
  3472. // we're running IE and do something. If not it is not supported.
  3473. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3474. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3475. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3476. // Inject the HTML DOM object element into the page.
  3477. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3478. // States of readiness that the plugin goes through when
  3479. // being injected and stated
  3480. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3481. NONE : 0, // no plugin use
  3482. INITIALIZING : 1, // Detected need for plugin
  3483. INJECTING : 2, // Injecting plugin
  3484. INJECTED: 3, // Plugin element injected but not usable yet
  3485. READY: 4 // Plugin ready to be used
  3486. };
  3487. // Current state of the plugin. You cannot use the plugin before this is
  3488. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3489. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3490. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3491. // Used to make sure AdapterJS.onwebrtcready is only called once
  3492. AdapterJS.onwebrtcreadyDone = false;
  3493. // Log levels for the plugin.
  3494. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3495. /*
  3496. Log outputs are prefixed in some cases.
  3497. INFO: Information reported by the plugin.
  3498. ERROR: Errors originating from within the plugin.
  3499. WEBRTC: Error originating from within the libWebRTC library
  3500. */
  3501. // From the least verbose to the most verbose
  3502. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3503. NONE : 'NONE',
  3504. ERROR : 'ERROR',
  3505. WARNING : 'WARNING',
  3506. INFO: 'INFO',
  3507. VERBOSE: 'VERBOSE',
  3508. SENSITIVE: 'SENSITIVE'
  3509. };
  3510. // Does a waiting check before proceeding to load the plugin.
  3511. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3512. // This methid will use an interval to wait for the plugin to be ready.
  3513. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3514. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3515. // This function will be called when plugin is ready. It sends necessary
  3516. // details to the plugin.
  3517. // The function will wait for the document to be ready and the set the
  3518. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3519. // indicating that it can start being requested.
  3520. // This function is not in the IE/Safari condition brackets so that
  3521. // TemPluginLoaded function might be called on Chrome/Firefox.
  3522. // This function is the only private function that is not encapsulated to
  3523. // allow the plugin method to be called.
  3524. __TemWebRTCReady0 = function () {
  3525. if (document.readyState === 'complete') {
  3526. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3527. AdapterJS.maybeThroughWebRTCReady();
  3528. } else {
  3529. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3530. if (document.readyState === 'complete') {
  3531. // TODO: update comments, we wait for the document to be ready
  3532. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3533. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3534. AdapterJS.maybeThroughWebRTCReady();
  3535. }
  3536. }, 100);
  3537. }
  3538. };
  3539. AdapterJS.maybeThroughWebRTCReady = function() {
  3540. if (!AdapterJS.onwebrtcreadyDone) {
  3541. AdapterJS.onwebrtcreadyDone = true;
  3542. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3543. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3544. }
  3545. }
  3546. };
  3547. // Text namespace
  3548. AdapterJS.TEXT = {
  3549. PLUGIN: {
  3550. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3551. 'to work on this browser.',
  3552. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3553. BUTTON: 'Install Now'
  3554. },
  3555. REFRESH: {
  3556. REQUIRE_REFRESH: 'Please refresh page',
  3557. BUTTON: 'Refresh Page'
  3558. }
  3559. };
  3560. // The result of ice connection states.
  3561. // - starting: Ice connection is starting.
  3562. // - checking: Ice connection is checking.
  3563. // - connected Ice connection is connected.
  3564. // - completed Ice connection is connected.
  3565. // - done Ice connection has been completed.
  3566. // - disconnected Ice connection has been disconnected.
  3567. // - failed Ice connection has failed.
  3568. // - closed Ice connection is closed.
  3569. AdapterJS._iceConnectionStates = {
  3570. starting : 'starting',
  3571. checking : 'checking',
  3572. connected : 'connected',
  3573. completed : 'connected',
  3574. done : 'completed',
  3575. disconnected : 'disconnected',
  3576. failed : 'failed',
  3577. closed : 'closed'
  3578. };
  3579. //The IceConnection states that has been fired for each peer.
  3580. AdapterJS._iceConnectionFiredStates = [];
  3581. // Check if WebRTC Interface is defined.
  3582. AdapterJS.isDefined = null;
  3583. // This function helps to retrieve the webrtc detected browser information.
  3584. // This sets:
  3585. // - webrtcDetectedBrowser: The browser agent name.
  3586. // - webrtcDetectedVersion: The browser version.
  3587. // - webrtcDetectedType: The types of webRTC support.
  3588. // - 'moz': Mozilla implementation of webRTC.
  3589. // - 'webkit': WebKit implementation of webRTC.
  3590. // - 'plugin': Using the plugin implementation.
  3591. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3592. var hasMatch, checkMatch = navigator.userAgent.match(
  3593. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3594. if (/trident/i.test(checkMatch[1])) {
  3595. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3596. webrtcDetectedBrowser = 'IE';
  3597. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3598. } else if (checkMatch[1] === 'Chrome') {
  3599. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3600. if (hasMatch !== null) {
  3601. webrtcDetectedBrowser = 'opera';
  3602. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3603. }
  3604. }
  3605. if (navigator.userAgent.indexOf('Safari')) {
  3606. if (typeof InstallTrigger !== 'undefined') {
  3607. webrtcDetectedBrowser = 'firefox';
  3608. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3609. webrtcDetectedBrowser = 'IE';
  3610. } else if (
  3611. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3612. webrtcDetectedBrowser = 'safari';
  3613. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3614. webrtcDetectedBrowser = 'opera';
  3615. } else if (!!window.chrome) {
  3616. webrtcDetectedBrowser = 'chrome';
  3617. }
  3618. }
  3619. if (!webrtcDetectedBrowser) {
  3620. webrtcDetectedVersion = checkMatch[1];
  3621. }
  3622. if (!webrtcDetectedVersion) {
  3623. try {
  3624. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3625. [navigator.appName, navigator.appVersion, '-?'];
  3626. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3627. checkMatch.splice(1, 1, hasMatch[1]);
  3628. }
  3629. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3630. } catch (error) { }
  3631. }
  3632. };
  3633. // To fix configuration as some browsers does not support
  3634. // the 'urls' attribute.
  3635. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3636. if (pcConfig === null) {
  3637. return;
  3638. }
  3639. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3640. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3641. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3642. delete pcConfig.iceServers[i].urls;
  3643. }
  3644. }
  3645. };
  3646. AdapterJS.addEvent = function(elem, evnt, func) {
  3647. if (elem.addEventListener) { // W3C DOM
  3648. elem.addEventListener(evnt, func, false);
  3649. } else if (elem.attachEvent) {// OLD IE DOM
  3650. elem.attachEvent('on'+evnt, func);
  3651. } else { // No much to do
  3652. elem[evnt] = func;
  3653. }
  3654. };
  3655. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3656. // only inject once the page is ready
  3657. if (document.readyState !== 'complete') {
  3658. return;
  3659. }
  3660. var w = window;
  3661. var i = document.createElement('iframe');
  3662. i.style.position = 'fixed';
  3663. i.style.top = '-41px';
  3664. i.style.left = 0;
  3665. i.style.right = 0;
  3666. i.style.width = '100%';
  3667. i.style.height = '40px';
  3668. i.style.backgroundColor = '#ffffe1';
  3669. i.style.border = 'none';
  3670. i.style.borderBottom = '1px solid #888888';
  3671. i.style.zIndex = '9999999';
  3672. if(typeof i.style.webkitTransition === 'string') {
  3673. i.style.webkitTransition = 'all .5s ease-out';
  3674. } else if(typeof i.style.transition === 'string') {
  3675. i.style.transition = 'all .5s ease-out';
  3676. }
  3677. document.body.appendChild(i);
  3678. c = (i.contentWindow) ? i.contentWindow :
  3679. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3680. c.document.open();
  3681. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3682. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3683. 'middle; cursor: default;">' + text + '</span>');
  3684. if(buttonText && buttonLink) {
  3685. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3686. c.document.close();
  3687. // On click on okay
  3688. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3689. if (!!displayRefreshBar) {
  3690. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3691. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3692. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3693. }
  3694. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3695. e.preventDefault();
  3696. try {
  3697. event.cancelBubble = true;
  3698. } catch(error) { }
  3699. var pluginInstallInterval = setInterval(function(){
  3700. if(! isIE) {
  3701. navigator.plugins.refresh(false);
  3702. }
  3703. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3704. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3705. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3706. function() { // plugin now installed
  3707. clearInterval(pluginInstallInterval);
  3708. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3709. },
  3710. function() {
  3711. // still no plugin detected, nothing to do
  3712. });
  3713. } , 500);
  3714. });
  3715. // On click on Cancel
  3716. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3717. w.document.body.removeChild(i);
  3718. });
  3719. } else {
  3720. c.document.close();
  3721. }
  3722. setTimeout(function() {
  3723. if(typeof i.style.webkitTransform === 'string') {
  3724. i.style.webkitTransform = 'translateY(40px)';
  3725. } else if(typeof i.style.transform === 'string') {
  3726. i.style.transform = 'translateY(40px)';
  3727. } else {
  3728. i.style.top = '0px';
  3729. }
  3730. }, 300);
  3731. };
  3732. // -----------------------------------------------------------
  3733. // Detected webrtc implementation. Types are:
  3734. // - 'moz': Mozilla implementation of webRTC.
  3735. // - 'webkit': WebKit implementation of webRTC.
  3736. // - 'plugin': Using the plugin implementation.
  3737. webrtcDetectedType = null;
  3738. // Detected webrtc datachannel support. Types are:
  3739. // - 'SCTP': SCTP datachannel support.
  3740. // - 'RTP': RTP datachannel support.
  3741. webrtcDetectedDCSupport = null;
  3742. // Set the settings for creating DataChannels, MediaStream for
  3743. // Cross-browser compability.
  3744. // - This is only for SCTP based support browsers.
  3745. // the 'urls' attribute.
  3746. checkMediaDataChannelSettings =
  3747. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3748. if (typeof callback !== 'function') {
  3749. return;
  3750. }
  3751. var beOfferer = true;
  3752. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3753. // Nightly version does not require MozDontOfferDataChannel for interop
  3754. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3755. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3756. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3757. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3758. // Resends an updated version of constraints for MozDataChannel to work
  3759. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3760. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3761. try {
  3762. delete constraints.mandatory.MozDontOfferDataChannel;
  3763. } catch (error) {
  3764. console.error('Failed deleting MozDontOfferDataChannel');
  3765. console.error(error);
  3766. }
  3767. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3768. constraints.mandatory.MozDontOfferDataChannel = true;
  3769. }
  3770. if (!isLocalFirefox) {
  3771. // temporary measure to remove Moz* constraints in non Firefox browsers
  3772. for (var prop in constraints.mandatory) {
  3773. if (constraints.mandatory.hasOwnProperty(prop)) {
  3774. if (prop.indexOf('Moz') !== -1) {
  3775. delete constraints.mandatory[prop];
  3776. }
  3777. }
  3778. }
  3779. }
  3780. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3781. // interopability of the media stream
  3782. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3783. beOfferer = false;
  3784. }
  3785. callback(beOfferer, constraints);
  3786. };
  3787. // Handles the differences for all browsers ice connection state output.
  3788. // - Tested outcomes are:
  3789. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3790. // - Chrome (answerer) : 'checking' > 'connected'
  3791. // - Firefox (offerer) : 'checking' > 'connected'
  3792. // - Firefox (answerer): 'checking' > 'connected'
  3793. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3794. if (typeof callback !== 'function') {
  3795. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3796. return;
  3797. }
  3798. peerId = (peerId) ? peerId : 'peer';
  3799. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3800. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3801. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3802. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3803. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3804. }
  3805. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3806. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3807. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3808. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3809. setTimeout(function () {
  3810. AdapterJS._iceConnectionFiredStates[peerId]
  3811. .push(AdapterJS._iceConnectionStates.done);
  3812. callback(AdapterJS._iceConnectionStates.done);
  3813. }, 1000);
  3814. }
  3815. callback(iceConnectionState);
  3816. }
  3817. return;
  3818. };
  3819. // Firefox:
  3820. // - Creates iceServer from the url for Firefox.
  3821. // - Create iceServer with stun url.
  3822. // - Create iceServer with turn url.
  3823. // - Ignore the transport parameter from TURN url for FF version <=27.
  3824. // - Return null for createIceServer if transport=tcp.
  3825. // - FF 27 and above supports transport parameters in TURN url,
  3826. // - So passing in the full url to create iceServer.
  3827. // Chrome:
  3828. // - Creates iceServer from the url for Chrome M33 and earlier.
  3829. // - Create iceServer with stun url.
  3830. // - Chrome M28 & above uses below TURN format.
  3831. // Plugin:
  3832. // - Creates Ice Server for Plugin Browsers
  3833. // - If Stun - Create iceServer with stun url.
  3834. // - Else - Create iceServer with turn url
  3835. // - This is a WebRTC Function
  3836. createIceServer = null;
  3837. // Firefox:
  3838. // - Creates IceServers for Firefox
  3839. // - Use .url for FireFox.
  3840. // - Multiple Urls support
  3841. // Chrome:
  3842. // - Creates iceServers from the urls for Chrome M34 and above.
  3843. // - .urls is supported since Chrome M34.
  3844. // - Multiple Urls support
  3845. // Plugin:
  3846. // - Creates Ice Servers for Plugin Browsers
  3847. // - Multiple Urls support
  3848. // - This is a WebRTC Function
  3849. createIceServers = null;
  3850. //------------------------------------------------------------
  3851. //The RTCPeerConnection object.
  3852. RTCPeerConnection = null;
  3853. // Creates RTCSessionDescription object for Plugin Browsers
  3854. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3855. RTCSessionDescription : null;
  3856. // Creates RTCIceCandidate object for Plugin Browsers
  3857. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3858. RTCIceCandidate : null;
  3859. // Get UserMedia (only difference is the prefix).
  3860. // Code from Adam Barth.
  3861. getUserMedia = null;
  3862. // Attach a media stream to an element.
  3863. attachMediaStream = null;
  3864. // Re-attach a media stream to an element.
  3865. reattachMediaStream = null;
  3866. // Detected browser agent name. Types are:
  3867. // - 'firefox': Firefox browser.
  3868. // - 'chrome': Chrome browser.
  3869. // - 'opera': Opera browser.
  3870. // - 'safari': Safari browser.
  3871. // - 'IE' - Internet Explorer browser.
  3872. webrtcDetectedBrowser = null;
  3873. // Detected browser version.
  3874. webrtcDetectedVersion = null;
  3875. // Check for browser types and react accordingly
  3876. if (navigator.mozGetUserMedia) {
  3877. webrtcDetectedBrowser = 'firefox';
  3878. webrtcDetectedVersion = parseInt(navigator
  3879. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3880. webrtcDetectedType = 'moz';
  3881. webrtcDetectedDCSupport = 'SCTP';
  3882. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3883. AdapterJS.maybeFixConfiguration(pcConfig);
  3884. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3885. };
  3886. // The RTCSessionDescription object.
  3887. RTCSessionDescription = mozRTCSessionDescription;
  3888. window.RTCSessionDescription = RTCSessionDescription;
  3889. // The RTCIceCandidate object.
  3890. RTCIceCandidate = mozRTCIceCandidate;
  3891. window.RTCIceCandidate = RTCIceCandidate;
  3892. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  3893. navigator.getUserMedia = window.getUserMedia;
  3894. // Shim for MediaStreamTrack.getSources.
  3895. MediaStreamTrack.getSources = function(successCb) {
  3896. setTimeout(function() {
  3897. var infos = [
  3898. { kind: 'audio', id: 'default', label:'', facing:'' },
  3899. { kind: 'video', id: 'default', label:'', facing:'' }
  3900. ];
  3901. successCb(infos);
  3902. }, 0);
  3903. };
  3904. createIceServer = function (url, username, password) {
  3905. var iceServer = null;
  3906. var url_parts = url.split(':');
  3907. if (url_parts[0].indexOf('stun') === 0) {
  3908. iceServer = { url : url };
  3909. } else if (url_parts[0].indexOf('turn') === 0) {
  3910. if (webrtcDetectedVersion < 27) {
  3911. var turn_url_parts = url.split('?');
  3912. if (turn_url_parts.length === 1 ||
  3913. turn_url_parts[1].indexOf('transport=udp') === 0) {
  3914. iceServer = {
  3915. url : turn_url_parts[0],
  3916. credential : password,
  3917. username : username
  3918. };
  3919. }
  3920. } else {
  3921. iceServer = {
  3922. url : url,
  3923. credential : password,
  3924. username : username
  3925. };
  3926. }
  3927. }
  3928. return iceServer;
  3929. };
  3930. createIceServers = function (urls, username, password) {
  3931. var iceServers = [];
  3932. for (var i = 0; i < urls.length; i++) {
  3933. var iceServer = createIceServer(urls[i], username, password);
  3934. if (iceServer !== null) {
  3935. iceServers.push(iceServer);
  3936. }
  3937. }
  3938. return iceServers;
  3939. };
  3940. attachMediaStream = function (element, stream) {
  3941. element.mozSrcObject = stream;
  3942. if (stream !== null)
  3943. element.play();
  3944. return element;
  3945. };
  3946. reattachMediaStream = function (to, from) {
  3947. to.mozSrcObject = from.mozSrcObject;
  3948. to.play();
  3949. return to;
  3950. };
  3951. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  3952. if (!callback) {
  3953. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  3954. ': 1 argument required, but only 0 present.');
  3955. }
  3956. return callback([]);
  3957. };
  3958. // Fake get{Video,Audio}Tracks
  3959. if (!MediaStream.prototype.getVideoTracks) {
  3960. MediaStream.prototype.getVideoTracks = function () {
  3961. return [];
  3962. };
  3963. }
  3964. if (!MediaStream.prototype.getAudioTracks) {
  3965. MediaStream.prototype.getAudioTracks = function () {
  3966. return [];
  3967. };
  3968. }
  3969. AdapterJS.maybeThroughWebRTCReady();
  3970. } else if (navigator.webkitGetUserMedia) {
  3971. webrtcDetectedBrowser = 'chrome';
  3972. webrtcDetectedType = 'webkit';
  3973. webrtcDetectedVersion = parseInt(navigator
  3974. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  3975. // check if browser is opera 20+
  3976. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3977. if (checkIfOpera !== null) {
  3978. webrtcDetectedBrowser = 'opera';
  3979. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  3980. }
  3981. // check browser datachannel support
  3982. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  3983. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  3984. webrtcDetectedDCSupport = 'SCTP';
  3985. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  3986. webrtcDetectedVersion > 24) {
  3987. webrtcDetectedDCSupport = 'RTP';
  3988. } else {
  3989. webrtcDetectedDCSupport = '';
  3990. }
  3991. createIceServer = function (url, username, password) {
  3992. var iceServer = null;
  3993. var url_parts = url.split(':');
  3994. if (url_parts[0].indexOf('stun') === 0) {
  3995. iceServer = { 'url' : url };
  3996. } else if (url_parts[0].indexOf('turn') === 0) {
  3997. iceServer = {
  3998. 'url' : url,
  3999. 'credential' : password,
  4000. 'username' : username
  4001. };
  4002. }
  4003. return iceServer;
  4004. };
  4005. createIceServers = function (urls, username, password) {
  4006. var iceServers = [];
  4007. if (webrtcDetectedVersion >= 34) {
  4008. iceServers = {
  4009. 'urls' : urls,
  4010. 'credential' : password,
  4011. 'username' : username
  4012. };
  4013. } else {
  4014. for (var i = 0; i < urls.length; i++) {
  4015. var iceServer = createIceServer(urls[i], username, password);
  4016. if (iceServer !== null) {
  4017. iceServers.push(iceServer);
  4018. }
  4019. }
  4020. }
  4021. return iceServers;
  4022. };
  4023. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4024. if (webrtcDetectedVersion < 34) {
  4025. AdapterJS.maybeFixConfiguration(pcConfig);
  4026. }
  4027. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4028. };
  4029. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4030. navigator.getUserMedia = window.getUserMedia;
  4031. attachMediaStream = function (element, stream) {
  4032. if (typeof element.srcObject !== 'undefined') {
  4033. element.srcObject = stream;
  4034. } else if (typeof element.mozSrcObject !== 'undefined') {
  4035. element.mozSrcObject = stream;
  4036. } else if (typeof element.src !== 'undefined') {
  4037. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4038. } else {
  4039. console.log('Error attaching stream to element.');
  4040. }
  4041. return element;
  4042. };
  4043. reattachMediaStream = function (to, from) {
  4044. to.src = from.src;
  4045. return to;
  4046. };
  4047. AdapterJS.maybeThroughWebRTCReady();
  4048. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4049. /Edge\/(\d+).(\d+)$/)) {
  4050. webrtcDetectedBrowser = 'edge';
  4051. webrtcDetectedVersion =
  4052. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4053. // the minimum version still supported by adapter.
  4054. webrtcMinimumVersion = 12;
  4055. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4056. attachMediaStream = function(element, stream) {
  4057. element.srcObject = stream;
  4058. return element;
  4059. };
  4060. reattachMediaStream = function(to, from) {
  4061. to.srcObject = from.srcObject;
  4062. return to;
  4063. };
  4064. AdapterJS.maybeThroughWebRTCReady();
  4065. } else { // TRY TO USE PLUGIN
  4066. // IE 9 is not offering an implementation of console.log until you open a console
  4067. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4068. /* jshint -W020 */
  4069. console = {} || console;
  4070. // Implemented based on console specs from MDN
  4071. // You may override these functions
  4072. console.log = function (arg) {};
  4073. console.info = function (arg) {};
  4074. console.error = function (arg) {};
  4075. console.dir = function (arg) {};
  4076. console.exception = function (arg) {};
  4077. console.trace = function (arg) {};
  4078. console.warn = function (arg) {};
  4079. console.count = function (arg) {};
  4080. console.debug = function (arg) {};
  4081. console.count = function (arg) {};
  4082. console.time = function (arg) {};
  4083. console.timeEnd = function (arg) {};
  4084. console.group = function (arg) {};
  4085. console.groupCollapsed = function (arg) {};
  4086. console.groupEnd = function (arg) {};
  4087. /* jshint +W020 */
  4088. }
  4089. webrtcDetectedType = 'plugin';
  4090. webrtcDetectedDCSupport = 'plugin';
  4091. AdapterJS.parseWebrtcDetectedBrowser();
  4092. isIE = webrtcDetectedBrowser === 'IE';
  4093. /* jshint -W035 */
  4094. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4095. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4096. /* empty because it needs to prevent the function from running. */
  4097. }
  4098. };
  4099. /* jshint +W035 */
  4100. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4101. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4102. // Call immediately if possible
  4103. // Once the plugin is set, the code will always take this path
  4104. callback();
  4105. } else {
  4106. // otherwise start a 100ms interval
  4107. var checkPluginReadyState = setInterval(function () {
  4108. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4109. clearInterval(checkPluginReadyState);
  4110. callback();
  4111. }
  4112. }, 100);
  4113. }
  4114. };
  4115. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4116. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4117. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4118. });
  4119. };
  4120. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4121. // only inject once the page is ready
  4122. if (document.readyState !== 'complete') {
  4123. return;
  4124. }
  4125. // Prevent multiple injections
  4126. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4127. return;
  4128. }
  4129. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4130. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4131. var frag = document.createDocumentFragment();
  4132. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4133. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4134. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4135. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4136. '<param name="pluginId" value="' +
  4137. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4138. '<param name="windowless" value="false" /> ' +
  4139. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4140. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4141. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4142. // uncomment to be able to use virtual cams
  4143. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4144. '</object>';
  4145. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4146. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4147. }
  4148. document.body.appendChild(frag);
  4149. // Need to re-fetch the plugin
  4150. AdapterJS.WebRTCPlugin.plugin =
  4151. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4152. } else {
  4153. // Load Plugin
  4154. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4155. AdapterJS.WebRTCPlugin.plugin.id =
  4156. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4157. // IE will only start the plugin if it's ACTUALLY visible
  4158. if (isIE) {
  4159. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4160. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4161. } else { // The size of the plugin on Safari should be 0x0px
  4162. // so that the autorisation prompt is at the top
  4163. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4164. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4165. }
  4166. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4167. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4168. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4169. '<param name="pluginId" value="' +
  4170. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4171. '<param name="windowless" value="false" /> ' +
  4172. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4173. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4174. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4175. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4176. }
  4177. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4178. };
  4179. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4180. function (comName, plugName, installedCb, notInstalledCb) {
  4181. if (!isIE) {
  4182. var pluginArray = navigator.plugins;
  4183. for (var i = 0; i < pluginArray.length; i++) {
  4184. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4185. installedCb();
  4186. return;
  4187. }
  4188. }
  4189. notInstalledCb();
  4190. } else {
  4191. try {
  4192. var axo = new ActiveXObject(comName + '.' + plugName);
  4193. } catch (e) {
  4194. notInstalledCb();
  4195. return;
  4196. }
  4197. installedCb();
  4198. }
  4199. };
  4200. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4201. if (AdapterJS.WebRTCPlugin.pluginState ===
  4202. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4203. console.error("AdapterJS - WebRTC interface has already been defined");
  4204. return;
  4205. }
  4206. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4207. AdapterJS.isDefined = function (variable) {
  4208. return variable !== null && variable !== undefined;
  4209. };
  4210. createIceServer = function (url, username, password) {
  4211. var iceServer = null;
  4212. var url_parts = url.split(':');
  4213. if (url_parts[0].indexOf('stun') === 0) {
  4214. iceServer = {
  4215. 'url' : url,
  4216. 'hasCredentials' : false
  4217. };
  4218. } else if (url_parts[0].indexOf('turn') === 0) {
  4219. iceServer = {
  4220. 'url' : url,
  4221. 'hasCredentials' : true,
  4222. 'credential' : password,
  4223. 'username' : username
  4224. };
  4225. }
  4226. return iceServer;
  4227. };
  4228. createIceServers = function (urls, username, password) {
  4229. var iceServers = [];
  4230. for (var i = 0; i < urls.length; ++i) {
  4231. iceServers.push(createIceServer(urls[i], username, password));
  4232. }
  4233. return iceServers;
  4234. };
  4235. RTCSessionDescription = function (info) {
  4236. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4237. return AdapterJS.WebRTCPlugin.plugin.
  4238. ConstructSessionDescription(info.type, info.sdp);
  4239. };
  4240. RTCPeerConnection = function (servers, constraints) {
  4241. var iceServers = null;
  4242. if (servers) {
  4243. iceServers = servers.iceServers;
  4244. for (var i = 0; i < iceServers.length; i++) {
  4245. if (iceServers[i].urls && !iceServers[i].url) {
  4246. iceServers[i].url = iceServers[i].urls;
  4247. }
  4248. iceServers[i].hasCredentials = AdapterJS.
  4249. isDefined(iceServers[i].username) &&
  4250. AdapterJS.isDefined(iceServers[i].credential);
  4251. }
  4252. }
  4253. var mandatory = (constraints && constraints.mandatory) ?
  4254. constraints.mandatory : null;
  4255. var optional = (constraints && constraints.optional) ?
  4256. constraints.optional : null;
  4257. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4258. return AdapterJS.WebRTCPlugin.plugin.
  4259. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4260. iceServers, mandatory, optional);
  4261. };
  4262. MediaStreamTrack = {};
  4263. MediaStreamTrack.getSources = function (callback) {
  4264. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4265. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4266. });
  4267. };
  4268. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4269. constraints.audio = constraints.audio || false;
  4270. constraints.video = constraints.video || false;
  4271. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4272. AdapterJS.WebRTCPlugin.plugin.
  4273. getUserMedia(constraints, successCallback, failureCallback);
  4274. });
  4275. };
  4276. window.navigator.getUserMedia = window.getUserMedia;
  4277. attachMediaStream = function (element, stream) {
  4278. if (!element || !element.parentNode) {
  4279. return;
  4280. }
  4281. var streamId;
  4282. if (stream === null) {
  4283. streamId = '';
  4284. } else {
  4285. if (typeof stream.enableSoundTracks !== 'undefined') {
  4286. stream.enableSoundTracks(true);
  4287. }
  4288. streamId = stream.id;
  4289. }
  4290. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4291. var nodeName = element.nodeName.toLowerCase();
  4292. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4293. var tag;
  4294. switch(nodeName) {
  4295. case 'audio':
  4296. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4297. break;
  4298. case 'video':
  4299. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4300. break;
  4301. default:
  4302. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4303. }
  4304. var frag = document.createDocumentFragment();
  4305. var temp = document.createElement('div');
  4306. var classHTML = '';
  4307. if (element.className) {
  4308. classHTML = 'class="' + element.className + '" ';
  4309. } else if (element.attributes && element.attributes['class']) {
  4310. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4311. }
  4312. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4313. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4314. '<param name="pluginId" value="' + elementId + '" /> ' +
  4315. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4316. '<param name="windowless" value="true" /> ' +
  4317. '<param name="streamId" value="' + streamId + '" /> ' +
  4318. '<param name="tag" value="' + tag + '" /> ' +
  4319. '</object>';
  4320. while (temp.firstChild) {
  4321. frag.appendChild(temp.firstChild);
  4322. }
  4323. var height = '';
  4324. var width = '';
  4325. if (element.clientWidth || element.clientHeight) {
  4326. width = element.clientWidth;
  4327. height = element.clientHeight;
  4328. }
  4329. else if (element.width || element.height) {
  4330. width = element.width;
  4331. height = element.height;
  4332. }
  4333. element.parentNode.insertBefore(frag, element);
  4334. frag = document.getElementById(elementId);
  4335. frag.width = width;
  4336. frag.height = height;
  4337. element.parentNode.removeChild(element);
  4338. } else { // already an <object> tag, just change the stream id
  4339. var children = element.children;
  4340. for (var i = 0; i !== children.length; ++i) {
  4341. if (children[i].name === 'streamId') {
  4342. children[i].value = streamId;
  4343. break;
  4344. }
  4345. }
  4346. element.setStreamId(streamId);
  4347. }
  4348. var newElement = document.getElementById(elementId);
  4349. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4350. return newElement;
  4351. };
  4352. reattachMediaStream = function (to, from) {
  4353. var stream = null;
  4354. var children = from.children;
  4355. for (var i = 0; i !== children.length; ++i) {
  4356. if (children[i].name === 'streamId') {
  4357. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4358. stream = AdapterJS.WebRTCPlugin.plugin
  4359. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4360. break;
  4361. }
  4362. }
  4363. if (stream !== null) {
  4364. return attachMediaStream(to, stream);
  4365. } else {
  4366. console.log('Could not find the stream associated with this element');
  4367. }
  4368. };
  4369. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4370. properties = Object.getOwnPropertyNames( prototype );
  4371. for(prop in properties) {
  4372. propName = properties[prop];
  4373. if (typeof(propName.slice) === 'function') {
  4374. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4375. if (isIE) {
  4376. destElem.attachEvent(propName,srcElem[propName]);
  4377. } else {
  4378. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4379. }
  4380. } else {
  4381. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4382. }
  4383. }
  4384. }
  4385. var subPrototype = Object.getPrototypeOf(prototype)
  4386. if(subPrototype != null) {
  4387. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4388. }
  4389. }
  4390. RTCIceCandidate = function (candidate) {
  4391. if (!candidate.sdpMid) {
  4392. candidate.sdpMid = '';
  4393. }
  4394. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4395. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4396. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4397. );
  4398. };
  4399. // inject plugin
  4400. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4401. AdapterJS.WebRTCPlugin.injectPlugin();
  4402. };
  4403. // This function will be called if the plugin is needed (browser different
  4404. // from Chrome or Firefox), but the plugin is not installed.
  4405. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4406. function() {
  4407. AdapterJS.addEvent(document,
  4408. 'readystatechange',
  4409. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4410. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4411. };
  4412. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4413. if (AdapterJS.options.hidePluginInstallPrompt) {
  4414. return;
  4415. }
  4416. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4417. if(downloadLink) { // if download link
  4418. var popupString;
  4419. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4420. popupString = 'This website requires you to install the ' +
  4421. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4422. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4423. ' WebRTC Plugin</a>' +
  4424. ' to work on this browser.';
  4425. } else { // no portal link, just print a generic explanation
  4426. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4427. }
  4428. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4429. } else { // no download link, just print a generic explanation
  4430. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4431. }
  4432. };
  4433. // Try to detect the plugin and act accordingly
  4434. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4435. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4436. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4437. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4438. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4439. }
  4440. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4441. },{"jitsi-meet-logger":48}],21:[function(require,module,exports){
  4442. (function (__filename){
  4443. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4444. function supportsLocalStorage() {
  4445. try {
  4446. return 'localStorage' in window && window.localStorage !== null;
  4447. } catch (e) {
  4448. logger.log("localstorage is not supported");
  4449. return false;
  4450. }
  4451. }
  4452. function generateUniqueId() {
  4453. function _p8() {
  4454. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4455. }
  4456. return _p8() + _p8() + _p8() + _p8();
  4457. }
  4458. function Settings(conferenceID) {
  4459. this.displayName = '';
  4460. this.userId;
  4461. this.confSettings = null;
  4462. this.conferenceID = conferenceID;
  4463. if (supportsLocalStorage()) {
  4464. if(!window.localStorage.getItem(conferenceID))
  4465. this.confSettings = {};
  4466. else
  4467. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4468. if(!this.confSettings.jitsiMeetId) {
  4469. this.confSettings.jitsiMeetId = generateUniqueId();
  4470. logger.log("generated id",
  4471. this.confSettings.jitsiMeetId);
  4472. this.save();
  4473. }
  4474. this.userId = this.confSettings.jitsiMeetId || '';
  4475. this.displayName = this.confSettings.displayname || '';
  4476. } else {
  4477. logger.log("local storage is not supported");
  4478. this.userId = generateUniqueId();
  4479. }
  4480. }
  4481. Settings.prototype.save = function () {
  4482. if(!supportsLocalStorage())
  4483. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4484. }
  4485. Settings.prototype.setDisplayName = function (newDisplayName) {
  4486. this.displayName = newDisplayName;
  4487. if(this.confSettings != null)
  4488. this.confSettings.displayname = displayName;
  4489. this.save();
  4490. return this.displayName;
  4491. },
  4492. Settings.prototype.getSettings = function () {
  4493. return {
  4494. displayName: this.displayName,
  4495. uid: this.userId
  4496. };
  4497. },
  4498. module.exports = Settings;
  4499. }).call(this,"/modules/settings/Settings.js")
  4500. },{"jitsi-meet-logger":48}],22:[function(require,module,exports){
  4501. /* global config */
  4502. /**
  4503. * Provides statistics for the local stream.
  4504. */
  4505. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4506. /**
  4507. * Size of the webaudio analyzer buffer.
  4508. * @type {number}
  4509. */
  4510. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4511. /**
  4512. * Value of the webaudio analyzer smoothing time parameter.
  4513. * @type {number}
  4514. */
  4515. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4516. /**
  4517. * Converts time domain data array to audio level.
  4518. * @param samples the time domain data array.
  4519. * @returns {number} the audio level
  4520. */
  4521. function timeDomainDataToAudioLevel(samples) {
  4522. var maxVolume = 0;
  4523. var length = samples.length;
  4524. for (var i = 0; i < length; i++) {
  4525. if (maxVolume < samples[i])
  4526. maxVolume = samples[i];
  4527. }
  4528. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4529. }
  4530. /**
  4531. * Animates audio level change
  4532. * @param newLevel the new audio level
  4533. * @param lastLevel the last audio level
  4534. * @returns {Number} the audio level to be set
  4535. */
  4536. function animateLevel(newLevel, lastLevel) {
  4537. var value = 0;
  4538. var diff = lastLevel - newLevel;
  4539. if(diff > 0.2) {
  4540. value = lastLevel - 0.2;
  4541. }
  4542. else if(diff < -0.4) {
  4543. value = lastLevel + 0.4;
  4544. }
  4545. else {
  4546. value = newLevel;
  4547. }
  4548. return parseFloat(value.toFixed(3));
  4549. }
  4550. /**
  4551. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4552. *
  4553. * @param stream the local stream
  4554. * @param interval stats refresh interval given in ms.
  4555. * @param callback function that receives the audio levels.
  4556. * @constructor
  4557. */
  4558. function LocalStatsCollector(stream, interval, callback) {
  4559. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4560. this.stream = stream;
  4561. this.intervalId = null;
  4562. this.intervalMilis = interval;
  4563. this.audioLevel = 0;
  4564. this.callback = callback;
  4565. }
  4566. /**
  4567. * Starts the collecting the statistics.
  4568. */
  4569. LocalStatsCollector.prototype.start = function () {
  4570. if (!window.AudioContext ||
  4571. RTCBrowserType.isTemasysPluginUsed())
  4572. return;
  4573. var context = new AudioContext();
  4574. var analyser = context.createAnalyser();
  4575. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4576. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4577. var source = context.createMediaStreamSource(this.stream);
  4578. source.connect(analyser);
  4579. var self = this;
  4580. this.intervalId = setInterval(
  4581. function () {
  4582. var array = new Uint8Array(analyser.frequencyBinCount);
  4583. analyser.getByteTimeDomainData(array);
  4584. var audioLevel = timeDomainDataToAudioLevel(array);
  4585. if (audioLevel != self.audioLevel) {
  4586. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4587. self.callback(self.audioLevel);
  4588. }
  4589. },
  4590. this.intervalMilis
  4591. );
  4592. };
  4593. /**
  4594. * Stops collecting the statistics.
  4595. */
  4596. LocalStatsCollector.prototype.stop = function () {
  4597. if (this.intervalId) {
  4598. clearInterval(this.intervalId);
  4599. this.intervalId = null;
  4600. }
  4601. };
  4602. module.exports = LocalStatsCollector;
  4603. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4604. (function (__filename){
  4605. /* global require, ssrc2jid */
  4606. /* jshint -W117 */
  4607. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4608. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4609. var StatisticsEvents = require("../../service/statistics/Events");
  4610. /* Whether we support the browser we are running into for logging statistics */
  4611. var browserSupported = RTCBrowserType.isChrome() ||
  4612. RTCBrowserType.isOpera();
  4613. var keyMap = {};
  4614. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4615. "ssrc": "ssrc",
  4616. "packetsReceived": "packetsReceived",
  4617. "packetsLost": "packetsLost",
  4618. "packetsSent": "packetsSent",
  4619. "bytesReceived": "bytesReceived",
  4620. "bytesSent": "bytesSent"
  4621. };
  4622. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4623. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4624. "sendBandwidth": "googAvailableSendBandwidth",
  4625. "remoteAddress": "googRemoteAddress",
  4626. "transportType": "googTransportType",
  4627. "localAddress": "googLocalAddress",
  4628. "activeConnection": "googActiveConnection",
  4629. "ssrc": "ssrc",
  4630. "packetsReceived": "packetsReceived",
  4631. "packetsSent": "packetsSent",
  4632. "packetsLost": "packetsLost",
  4633. "bytesReceived": "bytesReceived",
  4634. "bytesSent": "bytesSent",
  4635. "googFrameHeightReceived": "googFrameHeightReceived",
  4636. "googFrameWidthReceived": "googFrameWidthReceived",
  4637. "googFrameHeightSent": "googFrameHeightSent",
  4638. "googFrameWidthSent": "googFrameWidthSent",
  4639. "audioInputLevel": "audioInputLevel",
  4640. "audioOutputLevel": "audioOutputLevel"
  4641. };
  4642. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4643. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4644. /**
  4645. * Calculates packet lost percent using the number of lost packets and the
  4646. * number of all packet.
  4647. * @param lostPackets the number of lost packets
  4648. * @param totalPackets the number of all packets.
  4649. * @returns {number} packet loss percent
  4650. */
  4651. function calculatePacketLoss(lostPackets, totalPackets) {
  4652. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4653. return 0;
  4654. return Math.round((lostPackets/totalPackets)*100);
  4655. }
  4656. function getStatValue(item, name) {
  4657. var browserType = RTCBrowserType.getBrowserType();
  4658. if (!keyMap[browserType][name])
  4659. throw "The property isn't supported!";
  4660. var key = keyMap[browserType][name];
  4661. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4662. item.stat(key) : item[key];
  4663. }
  4664. function formatAudioLevel(audioLevel) {
  4665. return Math.min(Math.max(audioLevel, 0), 1);
  4666. }
  4667. /**
  4668. * Checks whether a certain record should be included in the logged statistics.
  4669. */
  4670. function acceptStat(reportId, reportType, statName) {
  4671. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4672. return false;
  4673. if (reportType == "ssrc") {
  4674. if (statName == "googTrackId" ||
  4675. statName == "transportId" ||
  4676. statName == "ssrc")
  4677. return false;
  4678. }
  4679. return true;
  4680. }
  4681. /**
  4682. * Checks whether a certain record should be included in the logged statistics.
  4683. */
  4684. function acceptReport(id, type) {
  4685. if (id.substring(0, 15) == "googCertificate" ||
  4686. id.substring(0, 9) == "googTrack" ||
  4687. id.substring(0, 20) == "googLibjingleSession")
  4688. return false;
  4689. if (type == "googComponent")
  4690. return false;
  4691. return true;
  4692. }
  4693. /**
  4694. * Peer statistics data holder.
  4695. * @constructor
  4696. */
  4697. function PeerStats()
  4698. {
  4699. this.ssrc2Loss = {};
  4700. this.ssrc2AudioLevel = {};
  4701. this.ssrc2bitrate = {};
  4702. this.ssrc2resolution = {};
  4703. }
  4704. /**
  4705. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4706. * represented by this instance.
  4707. * @param lossRate new packet loss rate value to be set.
  4708. */
  4709. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4710. {
  4711. this.ssrc2Loss = lossRate;
  4712. };
  4713. /**
  4714. * Sets resolution that belong to the ssrc
  4715. * represented by this instance.
  4716. * @param resolution new resolution value to be set.
  4717. */
  4718. PeerStats.prototype.setSsrcResolution = function (resolution)
  4719. {
  4720. if(resolution === null && this.ssrc2resolution[ssrc])
  4721. {
  4722. delete this.ssrc2resolution[ssrc];
  4723. }
  4724. else if(resolution !== null)
  4725. this.ssrc2resolution[ssrc] = resolution;
  4726. };
  4727. /**
  4728. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4729. * represented by this instance.
  4730. * @param ssrc audio or video RTP stream SSRC.
  4731. * @param bitrate new bitrate value to be set.
  4732. */
  4733. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4734. {
  4735. if(this.ssrc2bitrate[ssrc])
  4736. {
  4737. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4738. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4739. }
  4740. else {
  4741. this.ssrc2bitrate[ssrc] = bitrate;
  4742. }
  4743. };
  4744. /**
  4745. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4746. * the stream which belongs to the peer represented by this instance.
  4747. * @param ssrc RTP stream SSRC for which current audio level value will be
  4748. * updated.
  4749. * @param audioLevel the new audio level value to be set. Value is truncated to
  4750. * fit the range from 0 to 1.
  4751. */
  4752. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4753. {
  4754. // Range limit 0 - 1
  4755. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4756. };
  4757. function ConferenceStats() {
  4758. /**
  4759. * The bandwidth
  4760. * @type {{}}
  4761. */
  4762. this.bandwidth = {};
  4763. /**
  4764. * The bit rate
  4765. * @type {{}}
  4766. */
  4767. this.bitrate = {};
  4768. /**
  4769. * The packet loss rate
  4770. * @type {{}}
  4771. */
  4772. this.packetLoss = null;
  4773. /**
  4774. * Array with the transport information.
  4775. * @type {Array}
  4776. */
  4777. this.transport = [];
  4778. }
  4779. /**
  4780. * <tt>StatsCollector</tt> registers for stats updates of given
  4781. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4782. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4783. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4784. * instance as an event source.
  4785. *
  4786. * @param peerconnection webRTC peer connection object.
  4787. * @param interval stats refresh interval given in ms.
  4788. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4789. * called on stats update.
  4790. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4791. * @constructor
  4792. */
  4793. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4794. {
  4795. this.peerconnection = peerconnection;
  4796. this.baselineAudioLevelsReport = null;
  4797. this.currentAudioLevelsReport = null;
  4798. this.currentStatsReport = null;
  4799. this.baselineStatsReport = null;
  4800. this.audioLevelsIntervalId = null;
  4801. this.eventEmitter = eventEmitter;
  4802. this.config = config || {};
  4803. this.conferenceStats = new ConferenceStats();
  4804. /**
  4805. * Gather PeerConnection stats once every this many milliseconds.
  4806. */
  4807. this.GATHER_INTERVAL = 15000;
  4808. /**
  4809. * Log stats via the focus once every this many milliseconds.
  4810. */
  4811. this.LOG_INTERVAL = 60000;
  4812. /**
  4813. * Gather stats and store them in this.statsToBeLogged.
  4814. */
  4815. this.gatherStatsIntervalId = null;
  4816. /**
  4817. * Send the stats already saved in this.statsToBeLogged to be logged via
  4818. * the focus.
  4819. */
  4820. this.logStatsIntervalId = null;
  4821. /**
  4822. * Stores the statistics which will be send to the focus to be logged.
  4823. */
  4824. this.statsToBeLogged =
  4825. {
  4826. timestamps: [],
  4827. stats: {}
  4828. };
  4829. // Updates stats interval
  4830. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4831. this.statsIntervalId = null;
  4832. this.statsIntervalMilis = statsInterval;
  4833. // Map of ssrcs to PeerStats
  4834. this.ssrc2stats = {};
  4835. }
  4836. module.exports = StatsCollector;
  4837. /**
  4838. * Stops stats updates.
  4839. */
  4840. StatsCollector.prototype.stop = function () {
  4841. if (this.audioLevelsIntervalId) {
  4842. clearInterval(this.audioLevelsIntervalId);
  4843. this.audioLevelsIntervalId = null;
  4844. }
  4845. if (this.statsIntervalId)
  4846. {
  4847. clearInterval(this.statsIntervalId);
  4848. this.statsIntervalId = null;
  4849. }
  4850. if(this.logStatsIntervalId)
  4851. {
  4852. clearInterval(this.logStatsIntervalId);
  4853. this.logStatsIntervalId = null;
  4854. }
  4855. if(this.gatherStatsIntervalId)
  4856. {
  4857. clearInterval(this.gatherStatsIntervalId);
  4858. this.gatherStatsIntervalId = null;
  4859. }
  4860. };
  4861. /**
  4862. * Callback passed to <tt>getStats</tt> method.
  4863. * @param error an error that occurred on <tt>getStats</tt> call.
  4864. */
  4865. StatsCollector.prototype.errorCallback = function (error)
  4866. {
  4867. logger.error("Get stats error", error);
  4868. this.stop();
  4869. };
  4870. /**
  4871. * Starts stats updates.
  4872. */
  4873. StatsCollector.prototype.start = function ()
  4874. {
  4875. var self = this;
  4876. this.audioLevelsIntervalId = setInterval(
  4877. function () {
  4878. // Interval updates
  4879. self.peerconnection.getStats(
  4880. function (report) {
  4881. var results = null;
  4882. if (!report || !report.result ||
  4883. typeof report.result != 'function') {
  4884. results = report;
  4885. }
  4886. else {
  4887. results = report.result();
  4888. }
  4889. //logger.error("Got interval report", results);
  4890. self.currentAudioLevelsReport = results;
  4891. self.processAudioLevelReport();
  4892. self.baselineAudioLevelsReport =
  4893. self.currentAudioLevelsReport;
  4894. },
  4895. self.errorCallback
  4896. );
  4897. },
  4898. self.audioLevelsIntervalMilis
  4899. );
  4900. // if (!this.config.disableStats && browserSupported) {
  4901. // this.statsIntervalId = setInterval(
  4902. // function () {
  4903. // // Interval updates
  4904. // self.peerconnection.getStats(
  4905. // function (report) {
  4906. // var results = null;
  4907. // if (!report || !report.result ||
  4908. // typeof report.result != 'function') {
  4909. // //firefox
  4910. // results = report;
  4911. // }
  4912. // else {
  4913. // //chrome
  4914. // results = report.result();
  4915. // }
  4916. // //logger.error("Got interval report", results);
  4917. // self.currentStatsReport = results;
  4918. // try {
  4919. // self.processStatsReport();
  4920. // }
  4921. // catch (e) {
  4922. // logger.error("Unsupported key:" + e, e);
  4923. // }
  4924. //
  4925. // self.baselineStatsReport = self.currentStatsReport;
  4926. // },
  4927. // self.errorCallback
  4928. // );
  4929. // },
  4930. // self.statsIntervalMilis
  4931. // );
  4932. // }
  4933. //
  4934. // if (this.config.logStats && browserSupported) {
  4935. // this.gatherStatsIntervalId = setInterval(
  4936. // function () {
  4937. // self.peerconnection.getStats(
  4938. // function (report) {
  4939. // self.addStatsToBeLogged(report.result());
  4940. // },
  4941. // function () {
  4942. // }
  4943. // );
  4944. // },
  4945. // this.GATHER_INTERVAL
  4946. // );
  4947. //
  4948. // this.logStatsIntervalId = setInterval(
  4949. // function() { self.logStats(); },
  4950. // this.LOG_INTERVAL);
  4951. // }
  4952. };
  4953. /**
  4954. * Converts the stats to the format used for logging, and saves the data in
  4955. * this.statsToBeLogged.
  4956. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4957. */
  4958. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4959. var self = this;
  4960. var num_records = this.statsToBeLogged.timestamps.length;
  4961. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4962. reports.map(function (report) {
  4963. if (!acceptReport(report.id, report.type))
  4964. return;
  4965. var stat = self.statsToBeLogged.stats[report.id];
  4966. if (!stat) {
  4967. stat = self.statsToBeLogged.stats[report.id] = {};
  4968. }
  4969. stat.type = report.type;
  4970. report.names().map(function (name) {
  4971. if (!acceptStat(report.id, report.type, name))
  4972. return;
  4973. var values = stat[name];
  4974. if (!values) {
  4975. values = stat[name] = [];
  4976. }
  4977. while (values.length < num_records) {
  4978. values.push(null);
  4979. }
  4980. values.push(report.stat(name));
  4981. });
  4982. });
  4983. };
  4984. //FIXME:
  4985. //StatsCollector.prototype.logStats = function () {
  4986. //
  4987. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4988. // return;
  4989. // // Reset the stats
  4990. // this.statsToBeLogged.stats = {};
  4991. // this.statsToBeLogged.timestamps = [];
  4992. //};
  4993. /**
  4994. * Stats processing logic.
  4995. */
  4996. StatsCollector.prototype.processStatsReport = function () {
  4997. if (!this.baselineStatsReport) {
  4998. return;
  4999. }
  5000. for (var idx in this.currentStatsReport) {
  5001. var now = this.currentStatsReport[idx];
  5002. try {
  5003. if (getStatValue(now, 'receiveBandwidth') ||
  5004. getStatValue(now, 'sendBandwidth')) {
  5005. this.conferenceStats.bandwidth = {
  5006. "download": Math.round(
  5007. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5008. "upload": Math.round(
  5009. (getStatValue(now, 'sendBandwidth')) / 1000)
  5010. };
  5011. }
  5012. }
  5013. catch(e){/*not supported*/}
  5014. if(now.type == 'googCandidatePair')
  5015. {
  5016. var ip, type, localIP, active;
  5017. try {
  5018. ip = getStatValue(now, 'remoteAddress');
  5019. type = getStatValue(now, "transportType");
  5020. localIP = getStatValue(now, "localAddress");
  5021. active = getStatValue(now, "activeConnection");
  5022. }
  5023. catch(e){/*not supported*/}
  5024. if(!ip || !type || !localIP || active != "true")
  5025. continue;
  5026. var addressSaved = false;
  5027. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5028. {
  5029. if(this.conferenceStats.transport[i].ip == ip &&
  5030. this.conferenceStats.transport[i].type == type &&
  5031. this.conferenceStats.transport[i].localip == localIP)
  5032. {
  5033. addressSaved = true;
  5034. }
  5035. }
  5036. if(addressSaved)
  5037. continue;
  5038. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5039. continue;
  5040. }
  5041. if(now.type == "candidatepair")
  5042. {
  5043. if(now.state == "succeeded")
  5044. continue;
  5045. var local = this.currentStatsReport[now.localCandidateId];
  5046. var remote = this.currentStatsReport[now.remoteCandidateId];
  5047. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5048. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5049. }
  5050. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5051. now.type != "inboundrtp") {
  5052. continue;
  5053. }
  5054. var before = this.baselineStatsReport[idx];
  5055. if (!before) {
  5056. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5057. continue;
  5058. }
  5059. var ssrc = getStatValue(now, 'ssrc');
  5060. if(!ssrc)
  5061. continue;
  5062. var ssrcStats = this.ssrc2stats[ssrc];
  5063. if (!ssrcStats) {
  5064. ssrcStats = new PeerStats();
  5065. this.ssrc2stats[ssrc] = ssrcStats;
  5066. }
  5067. var isDownloadStream = true;
  5068. var key = 'packetsReceived';
  5069. var packetsNow = getStatValue(now, key);
  5070. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5071. isDownloadStream = false;
  5072. key = 'packetsSent';
  5073. packetsNow = getStatValue(now, key);
  5074. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5075. console.warn("No packetsReceived nor packetsSent stat found");
  5076. continue;
  5077. }
  5078. }
  5079. if (!packetsNow || packetsNow < 0)
  5080. packetsNow = 0;
  5081. var packetsBefore = getStatValue(before, key);
  5082. if (!packetsBefore || packetsBefore < 0)
  5083. packetsBefore = 0;
  5084. var packetRate = packetsNow - packetsBefore;
  5085. if (!packetRate || packetRate < 0)
  5086. packetRate = 0;
  5087. var currentLoss = getStatValue(now, 'packetsLost');
  5088. if (!currentLoss || currentLoss < 0)
  5089. currentLoss = 0;
  5090. var previousLoss = getStatValue(before, 'packetsLost');
  5091. if (!previousLoss || previousLoss < 0)
  5092. previousLoss = 0;
  5093. var lossRate = currentLoss - previousLoss;
  5094. if (!lossRate || lossRate < 0)
  5095. lossRate = 0;
  5096. var packetsTotal = (packetRate + lossRate);
  5097. ssrcStats.setSsrcLoss(ssrc,
  5098. {"packetsTotal": packetsTotal,
  5099. "packetsLost": lossRate,
  5100. "isDownloadStream": isDownloadStream});
  5101. var bytesReceived = 0, bytesSent = 0;
  5102. if(getStatValue(now, "bytesReceived")) {
  5103. bytesReceived = getStatValue(now, "bytesReceived") -
  5104. getStatValue(before, "bytesReceived");
  5105. }
  5106. if (getStatValue(now, "bytesSent")) {
  5107. bytesSent = getStatValue(now, "bytesSent") -
  5108. getStatValue(before, "bytesSent");
  5109. }
  5110. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5111. if (bytesReceived <= 0 || time <= 0) {
  5112. bytesReceived = 0;
  5113. } else {
  5114. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5115. }
  5116. if (bytesSent <= 0 || time <= 0) {
  5117. bytesSent = 0;
  5118. } else {
  5119. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5120. }
  5121. ssrcStats.setSsrcBitrate(ssrc, {
  5122. "download": bytesReceived,
  5123. "upload": bytesSent});
  5124. var resolution = {height: null, width: null};
  5125. try {
  5126. if (getStatValue(now, "googFrameHeightReceived") &&
  5127. getStatValue(now, "googFrameWidthReceived")) {
  5128. resolution.height =
  5129. getStatValue(now, "googFrameHeightReceived");
  5130. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5131. }
  5132. else if (getStatValue(now, "googFrameHeightSent") &&
  5133. getStatValue(now, "googFrameWidthSent")) {
  5134. resolution.height = getStatValue(now, "googFrameHeightSent");
  5135. resolution.width = getStatValue(now, "googFrameWidthSent");
  5136. }
  5137. }
  5138. catch(e){/*not supported*/}
  5139. if (resolution.height && resolution.width) {
  5140. ssrcStats.setSsrcResolution(ssrc, resolution);
  5141. } else {
  5142. ssrcStats.setSsrcResolution(ssrc, null);
  5143. }
  5144. }
  5145. var self = this;
  5146. // Jid stats
  5147. var totalPackets = {download: 0, upload: 0};
  5148. var lostPackets = {download: 0, upload: 0};
  5149. var bitrateDownload = 0;
  5150. var bitrateUpload = 0;
  5151. var resolutions = {};
  5152. Object.keys(this.ssrc2stats).forEach(
  5153. function (jid) {
  5154. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5155. function (ssrc) {
  5156. var type = "upload";
  5157. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5158. type = "download";
  5159. totalPackets[type] +=
  5160. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5161. lostPackets[type] +=
  5162. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5163. }
  5164. );
  5165. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5166. function (ssrc) {
  5167. bitrateDownload +=
  5168. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5169. bitrateUpload +=
  5170. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5171. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5172. }
  5173. );
  5174. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5175. }
  5176. );
  5177. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5178. this.conferenceStats.packetLoss = {
  5179. total:
  5180. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5181. totalPackets.download + totalPackets.upload),
  5182. download:
  5183. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5184. upload:
  5185. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5186. };
  5187. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5188. {
  5189. "bitrate": this.conferenceStats.bitrate,
  5190. "packetLoss": this.conferenceStats.packetLoss,
  5191. "bandwidth": this.conferenceStats.bandwidth,
  5192. "resolution": resolutions,
  5193. "transport": this.conferenceStats.transport
  5194. });
  5195. this.conferenceStats.transport = [];
  5196. };
  5197. /**
  5198. * Stats processing logic.
  5199. */
  5200. StatsCollector.prototype.processAudioLevelReport = function () {
  5201. if (!this.baselineAudioLevelsReport) {
  5202. return;
  5203. }
  5204. for (var idx in this.currentAudioLevelsReport) {
  5205. var now = this.currentAudioLevelsReport[idx];
  5206. //if we don't have "packetsReceived" this is local stream
  5207. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5208. continue;
  5209. }
  5210. var before = this.baselineAudioLevelsReport[idx];
  5211. if (!before) {
  5212. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5213. continue;
  5214. }
  5215. var ssrc = getStatValue(now, 'ssrc');
  5216. if (!ssrc) {
  5217. if((Date.now() - now.timestamp) < 3000)
  5218. logger.warn("No ssrc: ");
  5219. continue;
  5220. }
  5221. var ssrcStats = this.ssrc2stats[ssrc];
  5222. if (!ssrcStats) {
  5223. ssrcStats = new PeerStats();
  5224. this.ssrc2stats[ssrc] = ssrcStats;
  5225. }
  5226. // Audio level
  5227. var audioLevel = null;
  5228. try {
  5229. audioLevel = getStatValue(now, 'audioInputLevel');
  5230. if (!audioLevel)
  5231. audioLevel = getStatValue(now, 'audioOutputLevel');
  5232. }
  5233. catch(e) {/*not supported*/
  5234. logger.warn("Audio Levels are not available in the statistics.");
  5235. clearInterval(this.audioLevelsIntervalId);
  5236. return;
  5237. }
  5238. if (audioLevel) {
  5239. // TODO: can't find specs about what this value really is,
  5240. // but it seems to vary between 0 and around 32k.
  5241. audioLevel = audioLevel / 32767;
  5242. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5243. this.eventEmitter.emit(
  5244. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5245. }
  5246. }
  5247. };
  5248. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5249. },{"../../service/statistics/Events":85,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],24:[function(require,module,exports){
  5250. /* global require, APP */
  5251. var LocalStats = require("./LocalStatsCollector.js");
  5252. var RTPStats = require("./RTPStatsCollector.js");
  5253. var EventEmitter = require("events");
  5254. var StatisticsEvents = require("../../service/statistics/Events");
  5255. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  5256. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5257. //var CallStats = require("./CallStats");
  5258. //var RTCEvents = require("../../service/RTC/RTCEvents");
  5259. //
  5260. //function onDisposeConference(onUnload) {
  5261. // CallStats.sendTerminateEvent();
  5262. // stopRemote();
  5263. // if(onUnload) {
  5264. // stopLocal();
  5265. // eventEmitter.removeAllListeners();
  5266. // }
  5267. //}
  5268. var eventEmitter = new EventEmitter();
  5269. function Statistics() {
  5270. this.rtpStats = null;
  5271. this.eventEmitter = new EventEmitter();
  5272. }
  5273. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5274. if (this.rtpStats) {
  5275. this.rtpStats.stop();
  5276. }
  5277. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5278. this.rtpStats.start();
  5279. }
  5280. Statistics.localStats = [];
  5281. Statistics.startLocalStats = function (stream, callback) {
  5282. var localStats = new LocalStats(stream, 200, callback);
  5283. this.localStats.push(localStats);
  5284. localStats.start();
  5285. }
  5286. Statistics.prototype.addAudioLevelListener = function(listener)
  5287. {
  5288. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5289. }
  5290. Statistics.prototype.removeAudioLevelListener = function(listener)
  5291. {
  5292. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5293. }
  5294. Statistics.prototype.dispose = function () {
  5295. Statistics.stopAllLocalStats();
  5296. this.stopRemote();
  5297. if(this.eventEmitter)
  5298. this.eventEmitter.removeAllListeners();
  5299. if(eventEmitter)
  5300. eventEmitter.removeAllListeners();
  5301. }
  5302. Statistics.stopAllLocalStats = function () {
  5303. for(var i = 0; i < this.localStats.length; i++)
  5304. this.localStats[i].stop();
  5305. this.localStats = [];
  5306. }
  5307. Statistics.stopLocalStats = function (stream) {
  5308. for(var i = 0; i < Statistics.localStats.length; i++)
  5309. if(Statistics.localStats[i].stream === stream){
  5310. var localStats = Statistics.localStats.splice(i, 1);
  5311. localStats.stop();
  5312. break;
  5313. }
  5314. }
  5315. Statistics.prototype.stopRemote = function () {
  5316. if (this.rtpStats) {
  5317. this.rtpStats.stop();
  5318. this.eventEmitter.emit(StatisticsEvents.STOP);
  5319. this.rtpStats = null;
  5320. }
  5321. };
  5322. /**
  5323. * Obtains audio level reported in the stats for specified peer.
  5324. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5325. * audio level.
  5326. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5327. * level.
  5328. * @returns {*} a float form 0 to 1 that represents current audio level or
  5329. * <tt>null</tt> if for any reason the value is not available
  5330. * at this time.
  5331. */
  5332. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5333. var peerStats = this.rtpStats.jid2stats[peerJid];
  5334. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5335. };
  5336. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5337. //
  5338. //var statistics = {
  5339. // /**
  5340. // * Indicates that this audio level is for local jid.
  5341. // * @type {string}
  5342. // */
  5343. // LOCAL_JID: 'local',
  5344. //
  5345. // addConnectionStatsListener: function(listener)
  5346. // {
  5347. // eventEmitter.on("statistics.connectionstats", listener);
  5348. // },
  5349. //
  5350. // removeConnectionStatsListener: function(listener)
  5351. // {
  5352. // eventEmitter.removeListener("statistics.connectionstats", listener);
  5353. // },
  5354. //
  5355. //
  5356. // addRemoteStatsStopListener: function(listener)
  5357. // {
  5358. // eventEmitter.on("statistics.stop", listener);
  5359. // },
  5360. //
  5361. // removeRemoteStatsStopListener: function(listener)
  5362. // {
  5363. // eventEmitter.removeListener("statistics.stop", listener);
  5364. // },
  5365. //
  5366. //
  5367. // stopRemoteStatistics: function()
  5368. // {
  5369. // stopRemote();
  5370. // },
  5371. //
  5372. //// Already implemented with the constructor
  5373. // start: function () {
  5374. // APP.RTC.addStreamListener(onStreamCreated,
  5375. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5376. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5377. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5378. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5379. // startRemoteStats(event.peerconnection);
  5380. //// CallStats.init(event);
  5381. // });
  5382. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5383. //// CallStats.init(session);
  5384. //// });
  5385. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5386. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5387. //// CallStats.sendMuteEvent(mute, "audio");
  5388. //// });
  5389. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5390. //// CallStats.sendSetupFailedEvent();
  5391. //// });
  5392. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5393. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5394. //// CallStats.sendMuteEvent(mute, "video");
  5395. //// });
  5396. // }
  5397. //};
  5398. module.exports = Statistics;
  5399. },{"../../service/statistics/Events":85,"../../service/statistics/constants":86,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":44}],25:[function(require,module,exports){
  5400. /**
  5401. /**
  5402. * @const
  5403. */
  5404. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5405. /**
  5406. * Hexadecimal digits.
  5407. * @const
  5408. */
  5409. var HEX_DIGITS = '0123456789abcdef';
  5410. /**
  5411. * Generates random int within the range [min, max]
  5412. * @param min the minimum value for the generated number
  5413. * @param max the maximum value for the generated number
  5414. * @returns random int number
  5415. */
  5416. function randomInt(min, max) {
  5417. return Math.floor(Math.random() * (max - min + 1)) + min;
  5418. }
  5419. /**
  5420. * Get random element from array or string.
  5421. * @param {Array|string} arr source
  5422. * @returns array element or string character
  5423. */
  5424. function randomElement(arr) {
  5425. return arr[randomInt(0, arr.length - 1)];
  5426. }
  5427. /**
  5428. * Generate random alphanumeric string.
  5429. * @param {number} length expected string length
  5430. * @returns {string} random string of specified length
  5431. */
  5432. function randomAlphanumStr(length) {
  5433. var result = '';
  5434. for (var i = 0; i < length; i += 1) {
  5435. result += randomElement(ALPHANUM);
  5436. }
  5437. return result;
  5438. }
  5439. /**
  5440. * Exported interface.
  5441. */
  5442. var RandomUtil = {
  5443. /**
  5444. * Returns a random hex digit.
  5445. * @returns {*}
  5446. */
  5447. randomHexDigit: function() {
  5448. return randomElement(HEX_DIGITS);
  5449. },
  5450. /**
  5451. * Returns a random string of hex digits with length 'len'.
  5452. * @param len the length.
  5453. */
  5454. randomHexString: function (len) {
  5455. var ret = '';
  5456. while (len--) {
  5457. ret += this.randomHexDigit();
  5458. }
  5459. return ret;
  5460. },
  5461. randomElement: randomElement,
  5462. randomAlphanumStr: randomAlphanumStr
  5463. };
  5464. module.exports = RandomUtil;
  5465. },{}],26:[function(require,module,exports){
  5466. (function (__filename){
  5467. /* global Strophe, $, $pres, $iq, $msg */
  5468. /* jshint -W101,-W069 */
  5469. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5470. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5471. var Moderator = require("./moderator");
  5472. var EventEmitter = require("events");
  5473. var Recorder = require("./recording");
  5474. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  5475. var parser = {
  5476. packet2JSON: function (packet, nodes) {
  5477. var self = this;
  5478. $(packet).children().each(function (index) {
  5479. var tagName = $(this).prop("tagName");
  5480. var node = {
  5481. tagName: tagName
  5482. };
  5483. node.attributes = {};
  5484. $($(this)[0].attributes).each(function( index, attr ) {
  5485. node.attributes[ attr.name ] = attr.value;
  5486. });
  5487. var text = Strophe.getText($(this)[0]);
  5488. if (text) {
  5489. node.value = text;
  5490. }
  5491. node.children = [];
  5492. nodes.push(node);
  5493. self.packet2JSON($(this), node.children);
  5494. });
  5495. },
  5496. JSON2packet: function (nodes, packet) {
  5497. for(var i = 0; i < nodes.length; i++) {
  5498. var node = nodes[i];
  5499. if(!node || node === null){
  5500. continue;
  5501. }
  5502. packet.c(node.tagName, node.attributes);
  5503. if(node.value)
  5504. packet.t(node.value);
  5505. if(node.children)
  5506. this.JSON2packet(node.children, packet);
  5507. packet.up();
  5508. }
  5509. // packet.up();
  5510. }
  5511. };
  5512. /**
  5513. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5514. * @param pres the presence JSON
  5515. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5516. */
  5517. function filterNodeFromPresenceJSON(pres, nodeName){
  5518. var res = [];
  5519. for(var i = 0; i < pres.length; i++)
  5520. if(pres[i].tagName === nodeName)
  5521. res.push(pres[i]);
  5522. return res;
  5523. }
  5524. function ChatRoom(connection, jid, password, XMPP, options) {
  5525. this.eventEmitter = new EventEmitter();
  5526. this.xmpp = XMPP;
  5527. this.connection = connection;
  5528. this.roomjid = Strophe.getBareJidFromJid(jid);
  5529. this.myroomjid = jid;
  5530. this.password = password;
  5531. logger.info("Joined MUC as " + this.myroomjid);
  5532. this.members = {};
  5533. this.presMap = {};
  5534. this.presHandlers = {};
  5535. this.joined = false;
  5536. this.role = 'none';
  5537. this.focusMucJid = null;
  5538. this.bridgeIsDown = false;
  5539. this.options = options || {};
  5540. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5541. this.initPresenceMap();
  5542. this.session = null;
  5543. var self = this;
  5544. this.lastPresences = {};
  5545. this.phoneNumber = null;
  5546. this.phonePin = null;
  5547. }
  5548. ChatRoom.prototype.initPresenceMap = function () {
  5549. this.presMap['to'] = this.myroomjid;
  5550. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5551. this.presMap["nodes"] = [];
  5552. this.presMap["nodes"].push( {
  5553. "tagName": "user-agent",
  5554. "value": navigator.userAgent,
  5555. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5556. });
  5557. };
  5558. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5559. this.presMap["nodes"].push( {
  5560. "tagName": "devices",
  5561. "children": [
  5562. {
  5563. "tagName": "audio",
  5564. "value": devices.audio,
  5565. },
  5566. {
  5567. "tagName": "video",
  5568. "value": devices.video,
  5569. }
  5570. ]
  5571. });
  5572. };
  5573. ChatRoom.prototype.join = function (password) {
  5574. if(password)
  5575. this.password = password;
  5576. var self = this;
  5577. this.moderator.allocateConferenceFocus(function()
  5578. {
  5579. self.sendPresence(true);
  5580. }.bind(this));
  5581. };
  5582. ChatRoom.prototype.sendPresence = function (fromJoin) {
  5583. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  5584. // Too early to send presence - not initialized
  5585. return;
  5586. }
  5587. var pres = $pres({to: this.presMap['to'] });
  5588. pres.c('x', {xmlns: this.presMap['xns']});
  5589. if (this.password) {
  5590. pres.c('password').t(this.password).up();
  5591. }
  5592. pres.up();
  5593. // Send XEP-0115 'c' stanza that contains our capabilities info
  5594. if (this.connection.caps) {
  5595. this.connection.caps.node = this.xmpp.options.clientNode;
  5596. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5597. }
  5598. parser.JSON2packet(this.presMap.nodes, pres);
  5599. this.connection.send(pres);
  5600. };
  5601. ChatRoom.prototype.doLeave = function () {
  5602. logger.log("do leave", this.myroomjid);
  5603. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5604. this.presMap.length = 0;
  5605. this.connection.send(pres);
  5606. };
  5607. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5608. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5609. var getForm = $iq({type: 'get', to: this.roomjid})
  5610. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5611. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5612. var self = this;
  5613. this.connection.sendIQ(getForm, function (form) {
  5614. if (!$(form).find(
  5615. '>query>x[xmlns="jabber:x:data"]' +
  5616. '>field[var="muc#roomconfig_whois"]').length) {
  5617. logger.error('non-anonymous rooms not supported');
  5618. return;
  5619. }
  5620. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5621. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5622. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5623. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5624. .c('value')
  5625. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5626. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5627. .c('value').t('anyone').up().up();
  5628. self.connection.sendIQ(formSubmit);
  5629. }, function (error) {
  5630. logger.error("Error getting room configuration form");
  5631. });
  5632. };
  5633. ChatRoom.prototype.onPresence = function (pres) {
  5634. var from = pres.getAttribute('from');
  5635. // Parse roles.
  5636. var member = {};
  5637. member.show = $(pres).find('>show').text();
  5638. member.status = $(pres).find('>status').text();
  5639. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5640. member.affiliation = tmp.attr('affiliation');
  5641. member.role = tmp.attr('role');
  5642. // Focus recognition
  5643. member.jid = tmp.attr('jid');
  5644. member.isFocus = false;
  5645. if (member.jid
  5646. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5647. member.isFocus = true;
  5648. }
  5649. $(pres).find(">x").remove();
  5650. var nodes = [];
  5651. parser.packet2JSON(pres, nodes);
  5652. this.lastPresences[from] = nodes;
  5653. var jibri = null;
  5654. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  5655. // events
  5656. for(var i = 0; i < nodes.length; i++)
  5657. {
  5658. var node = nodes[i];
  5659. switch(node.tagName)
  5660. {
  5661. case "nick":
  5662. member.nick = node.value;
  5663. break;
  5664. case "userId":
  5665. member.id = node.value;
  5666. break;
  5667. }
  5668. }
  5669. if (from == this.myroomjid) {
  5670. if (member.affiliation == 'owner'
  5671. && this.role !== member.role) {
  5672. this.role = member.role;
  5673. this.eventEmitter.emit(
  5674. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5675. }
  5676. if (!this.joined) {
  5677. this.joined = true;
  5678. console.log("(TIME) MUC joined:\t", window.performance.now());
  5679. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  5680. }
  5681. } else if (this.members[from] === undefined) {
  5682. // new participant
  5683. this.members[from] = member;
  5684. logger.log('entered', from, member);
  5685. if (member.isFocus) {
  5686. this.focusMucJid = from;
  5687. if(!this.recording) {
  5688. this.recording = new Recorder(this.options.recordingType,
  5689. this.eventEmitter, this.connection, this.focusMucJid,
  5690. this.options.jirecon, this.roomjid);
  5691. if(this.lastJibri)
  5692. this.recording.handleJibriPresence(this.lastJibri);
  5693. }
  5694. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5695. }
  5696. else {
  5697. this.eventEmitter.emit(
  5698. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick);
  5699. }
  5700. } else {
  5701. // Presence update for existing participant
  5702. // Watch role change:
  5703. if (this.members[from].role != member.role) {
  5704. this.members[from].role = member.role;
  5705. this.eventEmitter.emit(
  5706. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5707. }
  5708. // store the new display name
  5709. if(member.displayName)
  5710. this.members[from].displayName = member.displayName;
  5711. }
  5712. // after we had fired member or room joined events, lets fire events
  5713. // for the rest info we got in presence
  5714. for(var i = 0; i < nodes.length; i++)
  5715. {
  5716. var node = nodes[i];
  5717. switch(node.tagName)
  5718. {
  5719. case "nick":
  5720. if(!member.isFocus) {
  5721. var displayName = !this.xmpp.options.displayJids
  5722. ? member.nick : Strophe.getResourceFromJid(from);
  5723. if (displayName && displayName.length > 0) {
  5724. this.eventEmitter.emit(
  5725. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5726. }
  5727. }
  5728. break;
  5729. case "bridgeIsDown":
  5730. if(!this.bridgeIsDown) {
  5731. this.bridgeIsDown = true;
  5732. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5733. }
  5734. break;
  5735. case "jibri-recording-status":
  5736. var jibri = node;
  5737. break;
  5738. case "call-control":
  5739. var att = node.attributes;
  5740. if(!att)
  5741. break;
  5742. this.phoneNumber = att.phone || null;
  5743. this.phonePin = att.pin || null;
  5744. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  5745. break;
  5746. default :
  5747. this.processNode(node, from);
  5748. }
  5749. }
  5750. if(!member.isFocus)
  5751. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id);
  5752. // Trigger status message update
  5753. if (member.status) {
  5754. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5755. }
  5756. if(jibri)
  5757. {
  5758. this.lastJibri = jibri;
  5759. if(this.recording)
  5760. this.recording.handleJibriPresence(jibri);
  5761. }
  5762. };
  5763. ChatRoom.prototype.processNode = function (node, from) {
  5764. if(this.presHandlers[node.tagName])
  5765. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  5766. };
  5767. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5768. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5769. msg.c('body', body).up();
  5770. if (nickname) {
  5771. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5772. }
  5773. this.connection.send(msg);
  5774. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5775. };
  5776. ChatRoom.prototype.setSubject = function (subject) {
  5777. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5778. msg.c('subject', subject);
  5779. this.connection.send(msg);
  5780. logger.log("topic changed to " + subject);
  5781. };
  5782. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5783. delete this.lastPresences[jid];
  5784. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5785. this.moderator.onMucMemberLeft(jid);
  5786. };
  5787. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5788. // room destroyed ?
  5789. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5790. '>destroy').length) {
  5791. var reason;
  5792. var reasonSelect = $(pres).find(
  5793. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5794. '>destroy>reason');
  5795. if (reasonSelect.length) {
  5796. reason = reasonSelect.text();
  5797. }
  5798. this.xmpp.leaveRoom(this.roomjid);
  5799. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5800. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5801. return true;
  5802. }
  5803. // Status code 110 indicates that this notification is "self-presence".
  5804. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5805. delete this.members[from];
  5806. this.onParticipantLeft(from);
  5807. }
  5808. // If the status code is 110 this means we're leaving and we would like
  5809. // to remove everyone else from our view, so we trigger the event.
  5810. else if (Object.keys(this.members).length > 1) {
  5811. for (var i in this.members) {
  5812. var member = this.members[i];
  5813. delete this.members[i];
  5814. this.onParticipantLeft(member);
  5815. }
  5816. }
  5817. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5818. if (this.myroomjid === from) {
  5819. this.xmpp.leaveRoom(this.roomjid);
  5820. this.eventEmitter.emit(XMPPEvents.KICKED);
  5821. }
  5822. }
  5823. };
  5824. ChatRoom.prototype.onMessage = function (msg, from) {
  5825. var nick =
  5826. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5827. .text() ||
  5828. Strophe.getResourceFromJid(from);
  5829. var txt = $(msg).find('>body').text();
  5830. var type = msg.getAttribute("type");
  5831. if (type == "error") {
  5832. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5833. $(msg).find('>text').text(), txt);
  5834. return true;
  5835. }
  5836. var subject = $(msg).find('>subject');
  5837. if (subject.length) {
  5838. var subjectText = subject.text();
  5839. if (subjectText || subjectText === "") {
  5840. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5841. logger.log("Subject is changed to " + subjectText);
  5842. }
  5843. }
  5844. // xep-0203 delay
  5845. var stamp = $(msg).find('>delay').attr('stamp');
  5846. if (!stamp) {
  5847. // or xep-0091 delay, UTC timestamp
  5848. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5849. if (stamp) {
  5850. // the format is CCYYMMDDThh:mm:ss
  5851. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5852. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5853. }
  5854. }
  5855. if (txt) {
  5856. logger.log('chat', nick, txt);
  5857. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5858. from, nick, txt, this.myroomjid, stamp);
  5859. }
  5860. };
  5861. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5862. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5863. logger.log('on password required', from);
  5864. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5865. } else if ($(pres).find(
  5866. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5867. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5868. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5869. // enter the room by replying with 'not-authorized'. This would
  5870. // result in reconnection from authorized domain.
  5871. // We're either missing Jicofo/Prosody config for anonymous
  5872. // domains or something is wrong.
  5873. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5874. } else {
  5875. logger.warn('onPresError ', pres);
  5876. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5877. }
  5878. } else {
  5879. logger.warn('onPresError ', pres);
  5880. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5881. }
  5882. };
  5883. ChatRoom.prototype.kick = function (jid) {
  5884. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5885. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5886. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5887. .c('reason').t('You have been kicked.').up().up().up();
  5888. this.connection.sendIQ(
  5889. kickIQ,
  5890. function (result) {
  5891. logger.log('Kick participant with jid: ', jid, result);
  5892. },
  5893. function (error) {
  5894. logger.log('Kick participant error: ', error);
  5895. });
  5896. };
  5897. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5898. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5899. var ob = this;
  5900. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5901. function (res) {
  5902. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5903. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5904. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5905. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5906. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5907. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5908. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5909. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5910. ob.connection.sendIQ(formsubmit,
  5911. onSuccess,
  5912. onError);
  5913. } else {
  5914. onNotSupported();
  5915. }
  5916. }, onError);
  5917. };
  5918. ChatRoom.prototype.addToPresence = function (key, values) {
  5919. values.tagName = key;
  5920. this.presMap["nodes"].push(values);
  5921. };
  5922. ChatRoom.prototype.removeFromPresence = function (key) {
  5923. for(var i = 0; i < this.presMap.nodes.length; i++)
  5924. {
  5925. if(key === this.presMap.nodes[i].tagName)
  5926. this.presMap.nodes.splice(i, 1);
  5927. }
  5928. };
  5929. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5930. this.presHandlers[name] = handler;
  5931. };
  5932. ChatRoom.prototype.removePresenceListener = function (name) {
  5933. delete this.presHandlers[name];
  5934. };
  5935. ChatRoom.prototype.isModerator = function () {
  5936. return this.role === 'moderator';
  5937. };
  5938. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5939. if (this.members[peerJid]) {
  5940. return this.members[peerJid].role;
  5941. }
  5942. return null;
  5943. };
  5944. ChatRoom.prototype.setJingleSession = function(session){
  5945. this.session = session;
  5946. this.session.room = this;
  5947. };
  5948. ChatRoom.prototype.removeStream = function (stream, callback) {
  5949. if(!this.session)
  5950. return;
  5951. this.session.removeStream(stream, callback);
  5952. };
  5953. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5954. if(this.session) {
  5955. // FIXME: will block switchInProgress on true value in case of exception
  5956. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5957. } else {
  5958. // We are done immediately
  5959. logger.warn("No conference handler or conference not started yet");
  5960. callback();
  5961. }
  5962. };
  5963. ChatRoom.prototype.addStream = function (stream, callback) {
  5964. if(this.session) {
  5965. // FIXME: will block switchInProgress on true value in case of exception
  5966. this.session.addStream(stream, callback);
  5967. } else {
  5968. // We are done immediately
  5969. logger.warn("No conference handler or conference not started yet");
  5970. callback();
  5971. }
  5972. };
  5973. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5974. var self = this;
  5975. var localCallback = function (mute) {
  5976. self.sendVideoInfoPresence(mute);
  5977. if(callback)
  5978. callback(mute);
  5979. };
  5980. if(this.session)
  5981. {
  5982. this.session.setVideoMute(
  5983. mute, localCallback, options);
  5984. }
  5985. else {
  5986. localCallback(mute);
  5987. }
  5988. };
  5989. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5990. //This will be for remote streams only
  5991. // if (this.forceMuted && !mute) {
  5992. // logger.info("Asking focus for unmute");
  5993. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5994. // // FIXME: wait for result before resetting muted status
  5995. // this.forceMuted = false;
  5996. // }
  5997. return this.sendAudioInfoPresence(mute, callback);
  5998. };
  5999. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  6000. this.removeFromPresence("audiomuted");
  6001. this.addToPresence("audiomuted",
  6002. {attributes:
  6003. {"audions": "http://jitsi.org/jitmeet/audio"},
  6004. value: mute.toString()});
  6005. };
  6006. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  6007. this.addAudioInfoToPresence(mute);
  6008. if(this.connection) {
  6009. this.sendPresence();
  6010. }
  6011. if(callback)
  6012. callback();
  6013. };
  6014. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  6015. this.removeFromPresence("videomuted");
  6016. this.addToPresence("videomuted",
  6017. {attributes:
  6018. {"videons": "http://jitsi.org/jitmeet/video"},
  6019. value: mute.toString()});
  6020. };
  6021. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  6022. this.addVideoInfoToPresence(mute);
  6023. if(!this.connection)
  6024. return;
  6025. this.sendPresence();
  6026. };
  6027. ChatRoom.prototype.addListener = function(type, listener) {
  6028. this.eventEmitter.on(type, listener);
  6029. };
  6030. ChatRoom.prototype.removeListener = function (type, listener) {
  6031. this.eventEmitter.removeListener(type, listener);
  6032. };
  6033. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  6034. if(this.lastPresences[data.peerjid])
  6035. {
  6036. var pres = this.lastPresences[data.peerjid];
  6037. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  6038. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  6039. data.videomuted = ((videomuted.length > 0
  6040. && videomuted[0]
  6041. && videomuted[0]["value"] === "true")? true : false);
  6042. data.audiomuted = ((audiomuted.length > 0
  6043. && audiomuted[0]
  6044. && audiomuted[0]["value"] === "true")? true : false);
  6045. }
  6046. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  6047. };
  6048. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  6049. if (!this.session)
  6050. return null;
  6051. return this.session.getSsrcOwner(ssrc);
  6052. };
  6053. /**
  6054. * Returns true if the recording is supproted and false if not.
  6055. */
  6056. ChatRoom.prototype.isRecordingSupported = function () {
  6057. if(this.recording)
  6058. return this.recording.isSupported();
  6059. return false;
  6060. };
  6061. /**
  6062. * Returns null if the recording is not supported, "on" if the recording started
  6063. * and "off" if the recording is not started.
  6064. */
  6065. ChatRoom.prototype.getRecordingState = function () {
  6066. if(this.recording)
  6067. return this.recording.getState();
  6068. return "off";
  6069. }
  6070. /**
  6071. * Returns the url of the recorded video.
  6072. */
  6073. ChatRoom.prototype.getRecordingURL = function () {
  6074. if(this.recording)
  6075. return this.recording.getURL();
  6076. return null;
  6077. }
  6078. /**
  6079. * Starts/stops the recording
  6080. * @param token token for authentication
  6081. * @param statusChangeHandler {function} receives the new status as argument.
  6082. */
  6083. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  6084. if(this.recording)
  6085. return this.recording.toggleRecording(options, statusChangeHandler);
  6086. return statusChangeHandler("error",
  6087. new Error("The conference is not created yet!"));
  6088. }
  6089. /**
  6090. * Returns true if the SIP calls are supported and false otherwise
  6091. */
  6092. ChatRoom.prototype.isSIPCallingSupported = function () {
  6093. if(this.moderator)
  6094. return this.moderator.isSipGatewayEnabled();
  6095. return false;
  6096. }
  6097. /**
  6098. * Dials a number.
  6099. * @param number the number
  6100. */
  6101. ChatRoom.prototype.dial = function (number) {
  6102. return this.connection.rayo.dial(number, "fromnumber",
  6103. Strophe.getNodeFromJid(this.myroomjid), this.password,
  6104. this.focusMucJid);
  6105. }
  6106. /**
  6107. * Hangup an existing call
  6108. */
  6109. ChatRoom.prototype.hangup = function () {
  6110. return this.connection.rayo.hangup();
  6111. }
  6112. /**
  6113. * Returns the phone number for joining the conference.
  6114. */
  6115. ChatRoom.prototype.getPhoneNumber = function () {
  6116. return this.phoneNumber;
  6117. }
  6118. /**
  6119. * Returns the pin for joining the conference with phone.
  6120. */
  6121. ChatRoom.prototype.getPhonePin = function () {
  6122. return this.phonePin;
  6123. }
  6124. /**
  6125. * Returns the connection state for the current session.
  6126. */
  6127. ChatRoom.prototype.getConnectionState = function () {
  6128. if(!this.session)
  6129. return null;
  6130. return this.session.getIceConnectionState();
  6131. }
  6132. /**
  6133. * Mutes remote participant.
  6134. * @param jid of the participant
  6135. * @param mute
  6136. */
  6137. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  6138. logger.info("set mute", mute);
  6139. var iqToFocus = $iq(
  6140. {to: this.focusMucJid, type: 'set'})
  6141. .c('mute', {
  6142. xmlns: 'http://jitsi.org/jitmeet/audio',
  6143. jid: jid
  6144. })
  6145. .t(mute.toString())
  6146. .up();
  6147. this.connection.sendIQ(
  6148. iqToFocus,
  6149. function (result) {
  6150. logger.log('set mute', result);
  6151. },
  6152. function (error) {
  6153. logger.log('set mute error', error);
  6154. });
  6155. }
  6156. ChatRoom.prototype.onMute = function (iq) {
  6157. var from = iq.getAttribute('from');
  6158. if (from !== this.focusMucJid) {
  6159. logger.warn("Ignored mute from non focus peer");
  6160. return false;
  6161. }
  6162. var mute = $(iq).find('mute');
  6163. if (mute.length) {
  6164. var doMuteAudio = mute.text() === "true";
  6165. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  6166. }
  6167. return true;
  6168. }
  6169. module.exports = ChatRoom;
  6170. }).call(this,"/modules/xmpp/ChatRoom.js")
  6171. },{"../../service/xmpp/XMPPEvents":87,"./moderator":34,"./recording":35,"events":44,"jitsi-meet-logger":48}],27:[function(require,module,exports){
  6172. (function (__filename){
  6173. /*
  6174. * JingleSession provides an API to manage a single Jingle session. We will
  6175. * have different implementations depending on the underlying interface used
  6176. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  6177. */
  6178. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6179. function JingleSession(me, sid, connection, service, eventEmitter) {
  6180. /**
  6181. * Our JID.
  6182. */
  6183. this.me = me;
  6184. /**
  6185. * The Jingle session identifier.
  6186. */
  6187. this.sid = sid;
  6188. /**
  6189. * The XMPP connection.
  6190. */
  6191. this.connection = connection;
  6192. /**
  6193. * The XMPP service.
  6194. */
  6195. this.service = service;
  6196. /**
  6197. * The event emitter.
  6198. */
  6199. this.eventEmitter = eventEmitter;
  6200. /**
  6201. * Whether to use dripping or not. Dripping is sending trickle candidates
  6202. * not one-by-one.
  6203. * Note: currently we do not support 'false'.
  6204. */
  6205. this.usedrip = true;
  6206. /**
  6207. * When dripping is used, stores ICE candidates which are to be sent.
  6208. */
  6209. this.drip_container = [];
  6210. // Media constraints. Is this WebRTC only?
  6211. this.media_constraints = null;
  6212. // ICE servers config (RTCConfiguration?).
  6213. this.ice_config = {};
  6214. // The chat room instance associated with the session.
  6215. this.room = null;
  6216. }
  6217. /**
  6218. * Prepares this object to initiate a session.
  6219. * @param peerjid the JID of the remote peer.
  6220. * @param isInitiator whether we will be the Jingle initiator.
  6221. * @param media_constraints
  6222. * @param ice_config
  6223. */
  6224. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  6225. media_constraints, ice_config) {
  6226. this.media_constraints = media_constraints;
  6227. this.ice_config = ice_config;
  6228. if (this.state !== null) {
  6229. logger.error('attempt to initiate on session ' + this.sid +
  6230. 'in state ' + this.state);
  6231. return;
  6232. }
  6233. this.state = 'pending';
  6234. this.initiator = isInitiator ? this.me : peerjid;
  6235. this.responder = !isInitiator ? this.me : peerjid;
  6236. this.peerjid = peerjid;
  6237. this.doInitialize();
  6238. };
  6239. /**
  6240. * Finishes initialization.
  6241. */
  6242. JingleSession.prototype.doInitialize = function() {};
  6243. /**
  6244. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  6245. * Note: currently only used on transport-info
  6246. */
  6247. JingleSession.prototype.addIceCandidates = function(contents) {};
  6248. /**
  6249. * Handles an 'add-source' event.
  6250. *
  6251. * @param contents an array of Jingle 'content' elements.
  6252. */
  6253. JingleSession.prototype.addSources = function(contents) {};
  6254. /**
  6255. * Handles a 'remove-source' event.
  6256. *
  6257. * @param contents an array of Jingle 'content' elements.
  6258. */
  6259. JingleSession.prototype.removeSources = function(contents) {};
  6260. /**
  6261. * Terminates this Jingle session (stops sending media and closes the streams?)
  6262. */
  6263. JingleSession.prototype.terminate = function() {};
  6264. /**
  6265. * Sends a Jingle session-terminate message to the peer and terminates the
  6266. * session.
  6267. * @param reason
  6268. * @param text
  6269. */
  6270. JingleSession.prototype.sendTerminate = function(reason, text) {};
  6271. /**
  6272. * Handles an offer from the remote peer (prepares to accept a session).
  6273. * @param jingle the 'jingle' XML element.
  6274. */
  6275. JingleSession.prototype.setOffer = function(jingle) {};
  6276. /**
  6277. * Handles an answer from the remote peer (prepares to accept a session).
  6278. * @param jingle the 'jingle' XML element.
  6279. */
  6280. JingleSession.prototype.setAnswer = function(jingle) {};
  6281. module.exports = JingleSession;
  6282. }).call(this,"/modules/xmpp/JingleSession.js")
  6283. },{"jitsi-meet-logger":48}],28:[function(require,module,exports){
  6284. (function (__filename){
  6285. /* jshint -W117 */
  6286. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6287. var JingleSession = require("./JingleSession");
  6288. var TraceablePeerConnection = require("./TraceablePeerConnection");
  6289. var SDPDiffer = require("./SDPDiffer");
  6290. var SDPUtil = require("./SDPUtil");
  6291. var SDP = require("./SDP");
  6292. var async = require("async");
  6293. var transform = require("sdp-transform");
  6294. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6295. var RTCBrowserType = require("../RTC/RTCBrowserType");
  6296. var SSRCReplacement = require("./LocalSSRCReplacement");
  6297. var RTC = require("../RTC/RTC");
  6298. // Jingle stuff
  6299. function JingleSessionPC(me, sid, connection, service) {
  6300. JingleSession.call(this, me, sid, connection, service);
  6301. this.initiator = null;
  6302. this.responder = null;
  6303. this.peerjid = null;
  6304. this.state = null;
  6305. this.localSDP = null;
  6306. this.remoteSDP = null;
  6307. this.relayedStreams = [];
  6308. this.usetrickle = true;
  6309. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  6310. this.hadstuncandidate = false;
  6311. this.hadturncandidate = false;
  6312. this.lasticecandidate = false;
  6313. this.statsinterval = null;
  6314. this.reason = null;
  6315. this.addssrc = [];
  6316. this.removessrc = [];
  6317. this.pendingop = null;
  6318. this.switchstreams = false;
  6319. this.addingStreams = false;
  6320. this.wait = true;
  6321. /**
  6322. * A map that stores SSRCs of local streams
  6323. * @type {{}} maps media type('audio' or 'video') to SSRC number
  6324. */
  6325. this.localStreamsSSRC = {};
  6326. this.ssrcOwners = {};
  6327. this.ssrcVideoTypes = {};
  6328. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  6329. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  6330. /**
  6331. * The indicator which determines whether the (local) video has been muted
  6332. * in response to a user command in contrast to an automatic decision made
  6333. * by the application logic.
  6334. */
  6335. this.videoMuteByUser = false;
  6336. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  6337. // We start with the queue paused. We resume it when the signaling state is
  6338. // stable and the ice connection state is connected.
  6339. this.modifySourcesQueue.pause();
  6340. }
  6341. //XXX this is badly broken...
  6342. JingleSessionPC.prototype = JingleSession.prototype;
  6343. JingleSessionPC.prototype.constructor = JingleSessionPC;
  6344. JingleSessionPC.prototype.setOffer = function(offer) {
  6345. this.setRemoteDescription(offer, 'offer');
  6346. };
  6347. JingleSessionPC.prototype.setAnswer = function(answer) {
  6348. this.setRemoteDescription(answer, 'answer');
  6349. };
  6350. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  6351. var signalingState = this.peerconnection.signalingState;
  6352. var iceConnectionState = this.peerconnection.iceConnectionState;
  6353. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  6354. this.modifySourcesQueue.resume();
  6355. } else {
  6356. this.modifySourcesQueue.pause();
  6357. }
  6358. };
  6359. JingleSessionPC.prototype.doInitialize = function () {
  6360. var self = this;
  6361. this.hadstuncandidate = false;
  6362. this.hadturncandidate = false;
  6363. this.lasticecandidate = false;
  6364. // True if reconnect is in progress
  6365. this.isreconnect = false;
  6366. // Set to true if the connection was ever stable
  6367. this.wasstable = false;
  6368. this.peerconnection = new TraceablePeerConnection(
  6369. this.connection.jingle.ice_config,
  6370. RTC.getPCConstraints(),
  6371. this);
  6372. this.peerconnection.onicecandidate = function (event) {
  6373. var protocol;
  6374. if (event && event.candidate) {
  6375. protocol = (typeof event.candidate.protocol === 'string')
  6376. ? event.candidate.protocol.toLowerCase() : '';
  6377. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6378. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6379. return;
  6380. }
  6381. }
  6382. self.sendIceCandidate(event.candidate);
  6383. };
  6384. this.peerconnection.onaddstream = function (event) {
  6385. if (event.stream.id !== 'default') {
  6386. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  6387. self.remoteStreamAdded(event);
  6388. } else {
  6389. // This is a recvonly stream. Clients that implement Unified Plan,
  6390. // such as Firefox use recvonly "streams/channels/tracks" for
  6391. // receiving remote stream/tracks, as opposed to Plan B where there
  6392. // are only 3 channels: audio, video and data.
  6393. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  6394. }
  6395. };
  6396. this.peerconnection.onremovestream = function (event) {
  6397. // Remove the stream from remoteStreams
  6398. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  6399. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  6400. };
  6401. this.peerconnection.onsignalingstatechange = function (event) {
  6402. if (!(self && self.peerconnection)) return;
  6403. if (self.peerconnection.signalingState === 'stable') {
  6404. self.wasstable = true;
  6405. }
  6406. self.updateModifySourcesQueue();
  6407. };
  6408. /**
  6409. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  6410. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  6411. * RTCPeerConnection.iceConnectionState changes.
  6412. *
  6413. * @param event the event containing information about the change
  6414. */
  6415. this.peerconnection.oniceconnectionstatechange = function (event) {
  6416. if (!(self && self.peerconnection)) return;
  6417. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  6418. ":\t", window.performance.now());
  6419. self.updateModifySourcesQueue();
  6420. switch (self.peerconnection.iceConnectionState) {
  6421. case 'connected':
  6422. // Informs interested parties that the connection has been restored.
  6423. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  6424. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  6425. self.isreconnect = false;
  6426. break;
  6427. case 'disconnected':
  6428. self.isreconnect = true;
  6429. // Informs interested parties that the connection has been interrupted.
  6430. if (self.wasstable)
  6431. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  6432. break;
  6433. case 'failed':
  6434. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6435. break;
  6436. }
  6437. onIceConnectionStateChange(self.sid, self);
  6438. };
  6439. this.peerconnection.onnegotiationneeded = function (event) {
  6440. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  6441. };
  6442. this.relayedStreams.forEach(function(stream) {
  6443. self.peerconnection.addStream(stream);
  6444. });
  6445. };
  6446. function onIceConnectionStateChange(sid, session) {
  6447. switch (session.peerconnection.iceConnectionState) {
  6448. case 'checking':
  6449. session.timeChecking = (new Date()).getTime();
  6450. session.firstconnect = true;
  6451. break;
  6452. case 'completed': // on caller side
  6453. case 'connected':
  6454. if (session.firstconnect) {
  6455. session.firstconnect = false;
  6456. var metadata = {};
  6457. metadata.setupTime
  6458. = (new Date()).getTime() - session.timeChecking;
  6459. session.peerconnection.getStats(function (res) {
  6460. if(res && res.result) {
  6461. res.result().forEach(function (report) {
  6462. if (report.type == 'googCandidatePair' &&
  6463. report.stat('googActiveConnection') == 'true') {
  6464. metadata.localCandidateType
  6465. = report.stat('googLocalCandidateType');
  6466. metadata.remoteCandidateType
  6467. = report.stat('googRemoteCandidateType');
  6468. // log pair as well so we can get nice pie
  6469. // charts
  6470. metadata.candidatePair
  6471. = report.stat('googLocalCandidateType') +
  6472. ';' +
  6473. report.stat('googRemoteCandidateType');
  6474. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  6475. {
  6476. metadata.ipv6 = true;
  6477. }
  6478. }
  6479. });
  6480. }
  6481. });
  6482. }
  6483. break;
  6484. }
  6485. }
  6486. JingleSessionPC.prototype.accept = function () {
  6487. this.state = 'active';
  6488. var pranswer = this.peerconnection.localDescription;
  6489. if (!pranswer || pranswer.type != 'pranswer') {
  6490. return;
  6491. }
  6492. logger.log('going from pranswer to answer');
  6493. if (this.usetrickle) {
  6494. // remove candidates already sent from session-accept
  6495. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  6496. for (var i = 0; i < lines.length; i++) {
  6497. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  6498. }
  6499. }
  6500. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  6501. // FIXME: change any inactive to sendrecv or whatever they were originally
  6502. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  6503. }
  6504. var prsdp = new SDP(pranswer.sdp);
  6505. if (self.webrtcIceTcpDisable) {
  6506. prsdp.removeTcpCandidates = true;
  6507. }
  6508. if (self.webrtcIceUdpDisable) {
  6509. prsdp.removeUdpCandidates = true;
  6510. }
  6511. var accept = $iq({to: this.peerjid,
  6512. type: 'set'})
  6513. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6514. action: 'session-accept',
  6515. initiator: this.initiator,
  6516. responder: this.responder,
  6517. sid: this.sid });
  6518. // FIXME why do we generate session-accept in 3 different places ?
  6519. prsdp.toJingle(
  6520. accept,
  6521. this.initiator == this.me ? 'initiator' : 'responder');
  6522. var sdp = this.peerconnection.localDescription.sdp;
  6523. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6524. // FIXME: change any inactive to sendrecv or whatever they were originally
  6525. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6526. }
  6527. var self = this;
  6528. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6529. function () {
  6530. //logger.log('setLocalDescription success');
  6531. self.setLocalDescription();
  6532. SSRCReplacement.processSessionInit(accept);
  6533. self.connection.sendIQ(accept,
  6534. function () {
  6535. var ack = {};
  6536. ack.source = 'answer';
  6537. $(document).trigger('ack.jingle', [self.sid, ack]);
  6538. },
  6539. function (stanza) {
  6540. var error = ($(stanza).find('error').length) ? {
  6541. code: $(stanza).find('error').attr('code'),
  6542. reason: $(stanza).find('error :first')[0].tagName
  6543. }:{};
  6544. error.source = 'answer';
  6545. JingleSessionPC.onJingleError(self.sid, error);
  6546. },
  6547. 10000);
  6548. },
  6549. function (e) {
  6550. logger.error('setLocalDescription failed', e);
  6551. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6552. }
  6553. );
  6554. };
  6555. JingleSessionPC.prototype.terminate = function (reason) {
  6556. this.state = 'ended';
  6557. this.reason = reason;
  6558. this.peerconnection.close();
  6559. if (this.statsinterval !== null) {
  6560. window.clearInterval(this.statsinterval);
  6561. this.statsinterval = null;
  6562. }
  6563. };
  6564. JingleSessionPC.prototype.active = function () {
  6565. return this.state == 'active';
  6566. };
  6567. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6568. var self = this;
  6569. if (candidate && !this.lasticecandidate) {
  6570. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6571. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6572. if (!(ice && jcand)) {
  6573. logger.error('failed to get ice && jcand');
  6574. return;
  6575. }
  6576. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6577. if (jcand.type === 'srflx') {
  6578. this.hadstuncandidate = true;
  6579. } else if (jcand.type === 'relay') {
  6580. this.hadturncandidate = true;
  6581. }
  6582. if (this.usetrickle) {
  6583. if (this.usedrip) {
  6584. if (this.drip_container.length === 0) {
  6585. // start 20ms callout
  6586. window.setTimeout(function () {
  6587. if (self.drip_container.length === 0) return;
  6588. self.sendIceCandidates(self.drip_container);
  6589. self.drip_container = [];
  6590. }, 20);
  6591. }
  6592. this.drip_container.push(candidate);
  6593. return;
  6594. } else {
  6595. self.sendIceCandidate([candidate]);
  6596. }
  6597. }
  6598. } else {
  6599. //logger.log('sendIceCandidate: last candidate.');
  6600. if (!this.usetrickle) {
  6601. //logger.log('should send full offer now...');
  6602. //FIXME why do we generate session-accept in 3 different places ?
  6603. var init = $iq({to: this.peerjid,
  6604. type: 'set'})
  6605. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6606. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6607. initiator: this.initiator,
  6608. sid: this.sid});
  6609. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6610. if (self.webrtcIceTcpDisable) {
  6611. this.localSDP.removeTcpCandidates = true;
  6612. }
  6613. if (self.webrtcIceUdpDisable) {
  6614. this.localSDP.removeUdpCandidates = true;
  6615. }
  6616. var sendJingle = function (ssrc) {
  6617. if(!ssrc)
  6618. ssrc = {};
  6619. self.localSDP.toJingle(
  6620. init,
  6621. self.initiator == self.me ? 'initiator' : 'responder',
  6622. ssrc);
  6623. SSRCReplacement.processSessionInit(init);
  6624. self.connection.sendIQ(init,
  6625. function () {
  6626. //logger.log('session initiate ack');
  6627. var ack = {};
  6628. ack.source = 'offer';
  6629. $(document).trigger('ack.jingle', [self.sid, ack]);
  6630. },
  6631. function (stanza) {
  6632. self.state = 'error';
  6633. self.peerconnection.close();
  6634. var error = ($(stanza).find('error').length) ? {
  6635. code: $(stanza).find('error').attr('code'),
  6636. reason: $(stanza).find('error :first')[0].tagName,
  6637. }:{};
  6638. error.source = 'offer';
  6639. JingleSessionPC.onJingleError(self.sid, error);
  6640. },
  6641. 10000);
  6642. };
  6643. sendJingle();
  6644. }
  6645. this.lasticecandidate = true;
  6646. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6647. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6648. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6649. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6650. }
  6651. }
  6652. };
  6653. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6654. logger.log('sendIceCandidates', candidates);
  6655. var cand = $iq({to: this.peerjid, type: 'set'})
  6656. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6657. action: 'transport-info',
  6658. initiator: this.initiator,
  6659. sid: this.sid});
  6660. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6661. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6662. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6663. if (cands.length > 0) {
  6664. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6665. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6666. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6667. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6668. }).c('transport', ice);
  6669. for (var i = 0; i < cands.length; i++) {
  6670. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6671. }
  6672. // add fingerprint
  6673. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6674. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6675. tmp.required = true;
  6676. cand.c(
  6677. 'fingerprint',
  6678. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6679. .t(tmp.fingerprint);
  6680. delete tmp.fingerprint;
  6681. cand.attrs(tmp);
  6682. cand.up();
  6683. }
  6684. cand.up(); // transport
  6685. cand.up(); // content
  6686. }
  6687. }
  6688. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6689. //logger.log('was this the last candidate', this.lasticecandidate);
  6690. this.connection.sendIQ(cand,
  6691. function () {
  6692. var ack = {};
  6693. ack.source = 'transportinfo';
  6694. $(document).trigger('ack.jingle', [this.sid, ack]);
  6695. },
  6696. function (stanza) {
  6697. var error = ($(stanza).find('error').length) ? {
  6698. code: $(stanza).find('error').attr('code'),
  6699. reason: $(stanza).find('error :first')[0].tagName,
  6700. }:{};
  6701. error.source = 'transportinfo';
  6702. JingleSessionPC.onJingleError(this.sid, error);
  6703. },
  6704. 10000);
  6705. };
  6706. JingleSessionPC.prototype.sendOffer = function () {
  6707. //logger.log('sendOffer...');
  6708. var self = this;
  6709. this.peerconnection.createOffer(function (sdp) {
  6710. self.createdOffer(sdp);
  6711. },
  6712. function (e) {
  6713. logger.error('createOffer failed', e);
  6714. },
  6715. this.media_constraints
  6716. );
  6717. };
  6718. // FIXME createdOffer is never used in jitsi-meet
  6719. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6720. //logger.log('createdOffer', sdp);
  6721. var self = this;
  6722. this.localSDP = new SDP(sdp.sdp);
  6723. //this.localSDP.mangle();
  6724. var sendJingle = function () {
  6725. var init = $iq({to: this.peerjid,
  6726. type: 'set'})
  6727. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6728. action: 'session-initiate',
  6729. initiator: this.initiator,
  6730. sid: this.sid});
  6731. self.localSDP.toJingle(
  6732. init,
  6733. this.initiator == this.me ? 'initiator' : 'responder');
  6734. SSRCReplacement.processSessionInit(init);
  6735. self.connection.sendIQ(init,
  6736. function () {
  6737. var ack = {};
  6738. ack.source = 'offer';
  6739. $(document).trigger('ack.jingle', [self.sid, ack]);
  6740. },
  6741. function (stanza) {
  6742. self.state = 'error';
  6743. self.peerconnection.close();
  6744. var error = ($(stanza).find('error').length) ? {
  6745. code: $(stanza).find('error').attr('code'),
  6746. reason: $(stanza).find('error :first')[0].tagName,
  6747. }:{};
  6748. error.source = 'offer';
  6749. JingleSessionPC.onJingleError(self.sid, error);
  6750. },
  6751. 10000);
  6752. }
  6753. sdp.sdp = this.localSDP.raw;
  6754. this.peerconnection.setLocalDescription(sdp,
  6755. function () {
  6756. if(self.usetrickle)
  6757. {
  6758. sendJingle();
  6759. }
  6760. self.setLocalDescription();
  6761. //logger.log('setLocalDescription success');
  6762. },
  6763. function (e) {
  6764. logger.error('setLocalDescription failed', e);
  6765. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6766. }
  6767. );
  6768. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6769. for (var i = 0; i < cands.length; i++) {
  6770. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6771. if (cand.type == 'srflx') {
  6772. this.hadstuncandidate = true;
  6773. } else if (cand.type == 'relay') {
  6774. this.hadturncandidate = true;
  6775. }
  6776. }
  6777. };
  6778. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6779. var self = this;
  6780. $(contents).each(function (idx, content) {
  6781. var name = $(content).attr('name');
  6782. var mediaType = this.getAttribute('name');
  6783. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6784. ssrcs.each(function () {
  6785. var ssrc = this.getAttribute('ssrc');
  6786. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6787. function () {
  6788. var owner = this.getAttribute('owner');
  6789. self.ssrcOwners[ssrc] = owner;
  6790. }
  6791. );
  6792. });
  6793. });
  6794. };
  6795. /**
  6796. * Returns the SSRC of local audio stream.
  6797. * @param mediaType 'audio' or 'video' media type
  6798. * @returns {*} the SSRC number of local audio or video stream.
  6799. */
  6800. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6801. return this.localStreamsSSRC[mediaType];
  6802. };
  6803. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6804. return this.ssrcOwners[ssrc];
  6805. };
  6806. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6807. //logger.log('setting remote description... ', desctype);
  6808. this.remoteSDP = new SDP('');
  6809. if (self.webrtcIceTcpDisable) {
  6810. this.remoteSDP.removeTcpCandidates = true;
  6811. }
  6812. if (self.webrtcIceUdpDisable) {
  6813. this.remoteSDP.removeUdpCandidates = true;
  6814. }
  6815. this.remoteSDP.fromJingle(elem);
  6816. this.readSsrcInfo($(elem).find(">content"));
  6817. if (this.peerconnection.remoteDescription) {
  6818. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6819. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6820. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6821. for (var i = 0; i < pranswer.media.length; i++) {
  6822. // make sure we have ice ufrag and pwd
  6823. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6824. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6825. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6826. } else {
  6827. logger.warn('no ice ufrag?');
  6828. }
  6829. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6830. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6831. } else {
  6832. logger.warn('no ice pwd?');
  6833. }
  6834. }
  6835. // copy over candidates
  6836. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6837. for (var j = 0; j < lines.length; j++) {
  6838. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6839. }
  6840. }
  6841. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6842. }
  6843. }
  6844. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6845. this.peerconnection.setRemoteDescription(remotedesc,
  6846. function () {
  6847. //logger.log('setRemoteDescription success');
  6848. },
  6849. function (e) {
  6850. logger.error('setRemoteDescription error', e);
  6851. JingleSessionPC.onJingleFatalError(self, e);
  6852. }
  6853. );
  6854. };
  6855. /**
  6856. * Adds remote ICE candidates to this Jingle session.
  6857. * @param elem An array of Jingle "content" elements?
  6858. */
  6859. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6860. var self = this;
  6861. if (this.peerconnection.signalingState == 'closed') {
  6862. return;
  6863. }
  6864. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6865. logger.log('trickle ice candidate arriving before session accept...');
  6866. // create a PRANSWER for setRemoteDescription
  6867. if (!this.remoteSDP) {
  6868. var cobbled = 'v=0\r\n' +
  6869. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6870. 's=-\r\n' +
  6871. 't=0 0\r\n';
  6872. // first, take some things from the local description
  6873. for (var i = 0; i < this.localSDP.media.length; i++) {
  6874. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6875. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6876. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6877. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6878. }
  6879. cobbled += 'a=inactive\r\n';
  6880. }
  6881. this.remoteSDP = new SDP(cobbled);
  6882. }
  6883. // then add things like ice and dtls from remote candidate
  6884. elem.each(function () {
  6885. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6886. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6887. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6888. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6889. var tmp = $(this).find('transport');
  6890. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6891. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6892. tmp = $(this).find('transport>fingerprint');
  6893. if (tmp.length) {
  6894. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6895. } else {
  6896. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6897. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6898. }
  6899. break;
  6900. }
  6901. }
  6902. }
  6903. });
  6904. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6905. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6906. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6907. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6908. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6909. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6910. }).length == this.remoteSDP.media.length;
  6911. if (iscomplete) {
  6912. logger.log('setting pranswer');
  6913. try {
  6914. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6915. function() {
  6916. },
  6917. function(e) {
  6918. logger.log('setRemoteDescription pranswer failed', e.toString());
  6919. });
  6920. } catch (e) {
  6921. logger.error('setting pranswer failed', e);
  6922. }
  6923. } else {
  6924. //logger.log('not yet setting pranswer');
  6925. }
  6926. }
  6927. // operate on each content element
  6928. elem.each(function () {
  6929. // would love to deactivate this, but firefox still requires it
  6930. var idx = -1;
  6931. var i;
  6932. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6933. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6934. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6935. idx = i;
  6936. break;
  6937. }
  6938. }
  6939. if (idx == -1) { // fall back to localdescription
  6940. for (i = 0; i < self.localSDP.media.length; i++) {
  6941. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6942. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6943. idx = i;
  6944. break;
  6945. }
  6946. }
  6947. }
  6948. var name = $(this).attr('name');
  6949. // TODO: check ice-pwd and ice-ufrag?
  6950. $(this).find('transport>candidate').each(function () {
  6951. var line, candidate;
  6952. var protocol = this.getAttribute('protocol');
  6953. protocol =
  6954. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6955. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6956. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6957. return;
  6958. }
  6959. line = SDPUtil.candidateFromJingle(this);
  6960. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6961. sdpMid: name,
  6962. candidate: line});
  6963. try {
  6964. self.peerconnection.addIceCandidate(candidate);
  6965. } catch (e) {
  6966. logger.error('addIceCandidate failed', e.toString(), line);
  6967. }
  6968. });
  6969. });
  6970. };
  6971. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6972. //logger.log('createAnswer', provisional);
  6973. var self = this;
  6974. this.peerconnection.createAnswer(
  6975. function (sdp) {
  6976. self.createdAnswer(sdp, provisional);
  6977. },
  6978. function (e) {
  6979. logger.error('createAnswer failed', e);
  6980. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6981. },
  6982. this.media_constraints
  6983. );
  6984. };
  6985. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6986. //logger.log('createAnswer callback');
  6987. var self = this;
  6988. this.localSDP = new SDP(sdp.sdp);
  6989. //this.localSDP.mangle();
  6990. this.usepranswer = provisional === true;
  6991. if (this.usetrickle) {
  6992. if (this.usepranswer) {
  6993. sdp.type = 'pranswer';
  6994. for (var i = 0; i < this.localSDP.media.length; i++) {
  6995. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6996. }
  6997. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6998. }
  6999. }
  7000. var self = this;
  7001. var sendJingle = function (ssrcs) {
  7002. // FIXME why do we generate session-accept in 3 different places ?
  7003. var accept = $iq({to: self.peerjid,
  7004. type: 'set'})
  7005. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7006. action: 'session-accept',
  7007. initiator: self.initiator,
  7008. responder: self.responder,
  7009. sid: self.sid });
  7010. if (self.webrtcIceTcpDisable) {
  7011. self.localSDP.removeTcpCandidates = true;
  7012. }
  7013. if (self.webrtcIceUdpDisable) {
  7014. self.localSDP.removeUdpCandidates = true;
  7015. }
  7016. self.localSDP.toJingle(
  7017. accept,
  7018. self.initiator == self.me ? 'initiator' : 'responder',
  7019. ssrcs);
  7020. SSRCReplacement.processSessionInit(accept);
  7021. self.connection.sendIQ(accept,
  7022. function () {
  7023. var ack = {};
  7024. ack.source = 'answer';
  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. error.source = 'answer';
  7033. JingleSessionPC.onJingleError(self.sid, error);
  7034. },
  7035. 10000);
  7036. }
  7037. sdp.sdp = this.localSDP.raw;
  7038. this.peerconnection.setLocalDescription(sdp,
  7039. function () {
  7040. //logger.log('setLocalDescription success');
  7041. if (self.usetrickle && !self.usepranswer) {
  7042. sendJingle();
  7043. }
  7044. self.setLocalDescription();
  7045. },
  7046. function (e) {
  7047. logger.error('setLocalDescription failed', e);
  7048. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7049. }
  7050. );
  7051. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  7052. for (var j = 0; j < cands.length; j++) {
  7053. var cand = SDPUtil.parse_icecandidate(cands[j]);
  7054. if (cand.type == 'srflx') {
  7055. this.hadstuncandidate = true;
  7056. } else if (cand.type == 'relay') {
  7057. this.hadturncandidate = true;
  7058. }
  7059. }
  7060. };
  7061. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  7062. var self = this,
  7063. term = $iq({to: this.peerjid,
  7064. type: 'set'})
  7065. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7066. action: 'session-terminate',
  7067. initiator: this.initiator,
  7068. sid: this.sid})
  7069. .c('reason')
  7070. .c(reason || 'success');
  7071. if (text) {
  7072. term.up().c('text').t(text);
  7073. }
  7074. this.connection.sendIQ(term,
  7075. function () {
  7076. self.peerconnection.close();
  7077. self.peerconnection = null;
  7078. self.terminate();
  7079. var ack = {};
  7080. ack.source = 'terminate';
  7081. $(document).trigger('ack.jingle', [self.sid, ack]);
  7082. },
  7083. function (stanza) {
  7084. var error = ($(stanza).find('error').length) ? {
  7085. code: $(stanza).find('error').attr('code'),
  7086. reason: $(stanza).find('error :first')[0].tagName,
  7087. }:{};
  7088. $(document).trigger('ack.jingle', [self.sid, error]);
  7089. },
  7090. 10000);
  7091. if (this.statsinterval !== null) {
  7092. window.clearInterval(this.statsinterval);
  7093. this.statsinterval = null;
  7094. }
  7095. };
  7096. /**
  7097. * Handles a Jingle source-add message for this Jingle session.
  7098. * @param elem An array of Jingle "content" elements.
  7099. */
  7100. JingleSessionPC.prototype.addSource = function (elem) {
  7101. var self = this;
  7102. // FIXME: dirty waiting
  7103. if (!this.peerconnection.localDescription)
  7104. {
  7105. logger.warn("addSource - localDescription not ready yet")
  7106. setTimeout(function()
  7107. {
  7108. self.addSource(elem);
  7109. },
  7110. 200
  7111. );
  7112. return;
  7113. }
  7114. logger.log('addssrc', new Date().getTime());
  7115. logger.log('ice', this.peerconnection.iceConnectionState);
  7116. this.readSsrcInfo(elem);
  7117. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7118. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7119. $(elem).each(function (idx, content) {
  7120. var name = $(content).attr('name');
  7121. var lines = '';
  7122. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7123. var semantics = this.getAttribute('semantics');
  7124. var ssrcs = $(this).find('>source').map(function () {
  7125. return this.getAttribute('ssrc');
  7126. }).get();
  7127. if (ssrcs.length) {
  7128. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7129. }
  7130. });
  7131. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7132. tmp.each(function () {
  7133. var ssrc = $(this).attr('ssrc');
  7134. if(mySdp.containsSSRC(ssrc)){
  7135. /**
  7136. * This happens when multiple participants change their streams at the same time and
  7137. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  7138. * addssrc are scheduled for update IQ. See
  7139. */
  7140. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  7141. return;
  7142. }
  7143. if (sdp.containsSSRC(ssrc)) {
  7144. logger.warn("Source-add request for existing SSRC: " + ssrc);
  7145. return;
  7146. }
  7147. $(this).find('>parameter').each(function () {
  7148. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7149. if ($(this).attr('value') && $(this).attr('value').length)
  7150. lines += ':' + $(this).attr('value');
  7151. lines += '\r\n';
  7152. });
  7153. });
  7154. sdp.media.forEach(function(media, idx) {
  7155. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7156. return;
  7157. sdp.media[idx] += lines;
  7158. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  7159. self.addssrc[idx] += lines;
  7160. });
  7161. sdp.raw = sdp.session + sdp.media.join('');
  7162. });
  7163. this.modifySourcesQueue.push(function() {
  7164. // When a source is added and if this is FF, a new channel is allocated
  7165. // for receiving the added source. We need to diffuse the SSRC of this
  7166. // new recvonly channel to the rest of the peers.
  7167. logger.log('modify sources done');
  7168. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7169. logger.log("SDPs", mySdp, newSdp);
  7170. self.notifyMySSRCUpdate(mySdp, newSdp);
  7171. });
  7172. };
  7173. /**
  7174. * Handles a Jingle source-remove message for this Jingle session.
  7175. * @param elem An array of Jingle "content" elements.
  7176. */
  7177. JingleSessionPC.prototype.removeSource = function (elem) {
  7178. var self = this;
  7179. // FIXME: dirty waiting
  7180. if (!this.peerconnection.localDescription) {
  7181. logger.warn("removeSource - localDescription not ready yet");
  7182. setTimeout(function() {
  7183. self.removeSource(elem);
  7184. },
  7185. 200
  7186. );
  7187. return;
  7188. }
  7189. logger.log('removessrc', new Date().getTime());
  7190. logger.log('ice', this.peerconnection.iceConnectionState);
  7191. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7192. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  7193. $(elem).each(function (idx, content) {
  7194. var name = $(content).attr('name');
  7195. var lines = '';
  7196. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7197. var semantics = this.getAttribute('semantics');
  7198. var ssrcs = $(this).find('>source').map(function () {
  7199. return this.getAttribute('ssrc');
  7200. }).get();
  7201. if (ssrcs.length) {
  7202. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7203. }
  7204. });
  7205. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  7206. tmp.each(function () {
  7207. var ssrc = $(this).attr('ssrc');
  7208. // This should never happen, but can be useful for bug detection
  7209. if(mySdp.containsSSRC(ssrc)){
  7210. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  7211. return;
  7212. }
  7213. $(this).find('>parameter').each(function () {
  7214. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  7215. if ($(this).attr('value') && $(this).attr('value').length)
  7216. lines += ':' + $(this).attr('value');
  7217. lines += '\r\n';
  7218. });
  7219. });
  7220. sdp.media.forEach(function(media, idx) {
  7221. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  7222. return;
  7223. sdp.media[idx] += lines;
  7224. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  7225. self.removessrc[idx] += lines;
  7226. });
  7227. sdp.raw = sdp.session + sdp.media.join('');
  7228. });
  7229. this.modifySourcesQueue.push(function() {
  7230. // When a source is removed and if this is FF, the recvonly channel that
  7231. // receives the remote stream is deactivated . We need to diffuse the
  7232. // recvonly SSRC removal to the rest of the peers.
  7233. logger.log('modify sources done');
  7234. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7235. logger.log("SDPs", mySdp, newSdp);
  7236. self.notifyMySSRCUpdate(mySdp, newSdp);
  7237. });
  7238. };
  7239. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  7240. var self = this;
  7241. if (this.peerconnection.signalingState == 'closed') return;
  7242. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  7243. || this.switchstreams || this.addingStreams)){
  7244. // There is nothing to do since scheduled job might have been executed by another succeeding call
  7245. this.setLocalDescription();
  7246. if(successCallback){
  7247. successCallback();
  7248. }
  7249. queueCallback();
  7250. return;
  7251. }
  7252. // Reset switch streams flags
  7253. this.switchstreams = false;
  7254. this.addingStreams = false;
  7255. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  7256. // add sources
  7257. this.addssrc.forEach(function(lines, idx) {
  7258. sdp.media[idx] += lines;
  7259. });
  7260. this.addssrc = [];
  7261. // remove sources
  7262. this.removessrc.forEach(function(lines, idx) {
  7263. lines = lines.split('\r\n');
  7264. lines.pop(); // remove empty last element;
  7265. lines.forEach(function(line) {
  7266. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  7267. });
  7268. });
  7269. this.removessrc = [];
  7270. sdp.raw = sdp.session + sdp.media.join('');
  7271. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  7272. function() {
  7273. if(self.signalingState == 'closed') {
  7274. logger.error("createAnswer attempt on closed state");
  7275. queueCallback("createAnswer attempt on closed state");
  7276. return;
  7277. }
  7278. self.peerconnection.createAnswer(
  7279. function(modifiedAnswer) {
  7280. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  7281. if (self.pendingop !== null) {
  7282. var sdp = new SDP(modifiedAnswer.sdp);
  7283. if (sdp.media.length > 1) {
  7284. switch(self.pendingop) {
  7285. case 'mute':
  7286. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  7287. break;
  7288. case 'unmute':
  7289. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  7290. break;
  7291. }
  7292. sdp.raw = sdp.session + sdp.media.join('');
  7293. modifiedAnswer.sdp = sdp.raw;
  7294. }
  7295. self.pendingop = null;
  7296. }
  7297. // FIXME: pushing down an answer while ice connection state
  7298. // is still checking is bad...
  7299. //logger.log(self.peerconnection.iceConnectionState);
  7300. // trying to work around another chrome bug
  7301. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  7302. self.peerconnection.setLocalDescription(modifiedAnswer,
  7303. function() {
  7304. //logger.log('modified setLocalDescription ok');
  7305. self.setLocalDescription();
  7306. if(successCallback){
  7307. successCallback();
  7308. }
  7309. queueCallback();
  7310. },
  7311. function(error) {
  7312. logger.error('modified setLocalDescription failed', error);
  7313. queueCallback(error);
  7314. }
  7315. );
  7316. },
  7317. function(error) {
  7318. logger.error('modified answer failed', error);
  7319. queueCallback(error);
  7320. }
  7321. );
  7322. },
  7323. function(error) {
  7324. logger.error('modify failed', error);
  7325. queueCallback(error);
  7326. }
  7327. );
  7328. };
  7329. /**
  7330. * Switches video streams.
  7331. * @param newStream new stream that will be used as video of this session.
  7332. * @param oldStream old video stream of this session.
  7333. * @param successCallback callback executed after successful stream switch.
  7334. * @param isAudio whether the streams are audio (if true) or video (if false).
  7335. */
  7336. JingleSessionPC.prototype.switchStreams =
  7337. function (newStream, oldStream, successCallback, isAudio) {
  7338. var self = this;
  7339. var sender, newTrack;
  7340. var senderKind = isAudio ? 'audio' : 'video';
  7341. // Remember SDP to figure out added/removed SSRCs
  7342. var oldSdp = null;
  7343. if (self.peerconnection) {
  7344. if (self.peerconnection.localDescription) {
  7345. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7346. }
  7347. if (RTCBrowserType.getBrowserType() ===
  7348. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  7349. // On Firefox we don't replace MediaStreams as this messes up the
  7350. // m-lines (which can't be removed in Plan Unified) and brings a lot
  7351. // of complications. Instead, we use the RTPSender and replace just
  7352. // the track.
  7353. // Find the right sender (for audio or video)
  7354. self.peerconnection.peerconnection.getSenders().some(function (s) {
  7355. if (s.track && s.track.kind === senderKind) {
  7356. sender = s;
  7357. return true;
  7358. }
  7359. });
  7360. if (sender) {
  7361. // We assume that our streams have a single track, either audio
  7362. // or video.
  7363. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  7364. newStream.getVideoTracks()[0];
  7365. sender.replaceTrack(newTrack)
  7366. .then(function() {
  7367. console.log("Replaced a track, isAudio=" + isAudio);
  7368. })
  7369. .catch(function(err) {
  7370. console.log("Failed to replace a track: " + err);
  7371. });
  7372. } else {
  7373. console.log("Cannot switch tracks: no RTPSender.");
  7374. }
  7375. } else {
  7376. self.peerconnection.removeStream(oldStream, true);
  7377. if (newStream) {
  7378. self.peerconnection.addStream(newStream);
  7379. }
  7380. }
  7381. }
  7382. // Conference is not active
  7383. if (!oldSdp) {
  7384. successCallback();
  7385. return;
  7386. }
  7387. self.switchstreams = true;
  7388. self.modifySourcesQueue.push(function() {
  7389. logger.log('modify sources done');
  7390. successCallback();
  7391. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7392. logger.log("SDPs", oldSdp, newSdp);
  7393. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7394. });
  7395. };
  7396. /**
  7397. * Adds streams.
  7398. * @param stream new stream that will be added.
  7399. * @param success_callback callback executed after successful stream addition.
  7400. */
  7401. JingleSessionPC.prototype.addStream = function (stream, callback) {
  7402. var self = this;
  7403. // Remember SDP to figure out added/removed SSRCs
  7404. var oldSdp = null;
  7405. if(this.peerconnection) {
  7406. if(this.peerconnection.localDescription) {
  7407. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7408. }
  7409. if(stream)
  7410. this.peerconnection.addStream(stream);
  7411. }
  7412. // Conference is not active
  7413. if(!oldSdp || !this.peerconnection) {
  7414. callback();
  7415. return;
  7416. }
  7417. this.addingStreams = true;
  7418. this.modifySourcesQueue.push(function() {
  7419. logger.log('modify sources done');
  7420. callback();
  7421. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7422. logger.log("SDPs", oldSdp, newSdp);
  7423. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7424. });
  7425. }
  7426. /**
  7427. * Remove streams.
  7428. * @param stream stream that will be removed.
  7429. * @param success_callback callback executed after successful stream addition.
  7430. */
  7431. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  7432. var self = this;
  7433. // Remember SDP to figure out added/removed SSRCs
  7434. var oldSdp = null;
  7435. if(this.peerconnection) {
  7436. if(this.peerconnection.localDescription) {
  7437. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  7438. }
  7439. if(stream)
  7440. this.peerconnection.removeStream(stream);
  7441. }
  7442. // Conference is not active
  7443. if(!oldSdp || !this.peerconnection) {
  7444. callback();
  7445. return;
  7446. }
  7447. this.addingStreams = true;
  7448. this.modifySourcesQueue.push(function() {
  7449. logger.log('modify sources done');
  7450. callback();
  7451. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7452. logger.log("SDPs", oldSdp, newSdp);
  7453. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7454. });
  7455. }
  7456. /**
  7457. * Figures out added/removed ssrcs and send update IQs.
  7458. * @param old_sdp SDP object for old description.
  7459. * @param new_sdp SDP object for new description.
  7460. */
  7461. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  7462. if (!(this.peerconnection.signalingState == 'stable' &&
  7463. this.peerconnection.iceConnectionState == 'connected')){
  7464. logger.log("Too early to send updates");
  7465. return;
  7466. }
  7467. // send source-remove IQ.
  7468. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  7469. var remove = $iq({to: this.peerjid, type: 'set'})
  7470. .c('jingle', {
  7471. xmlns: 'urn:xmpp:jingle:1',
  7472. action: 'source-remove',
  7473. initiator: this.initiator,
  7474. sid: this.sid
  7475. }
  7476. );
  7477. var removed = sdpDiffer.toJingle(remove);
  7478. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  7479. // it in the current form
  7480. if (removed)
  7481. remove = SSRCReplacement.processSourceRemove(remove);
  7482. if (removed && remove) {
  7483. logger.info("Sending source-remove", remove);
  7484. this.connection.sendIQ(remove,
  7485. function (res) {
  7486. logger.info('got remove result', res);
  7487. },
  7488. function (err) {
  7489. logger.error('got remove error', err);
  7490. }
  7491. );
  7492. } else {
  7493. logger.log('removal not necessary');
  7494. }
  7495. // send source-add IQ.
  7496. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  7497. var add = $iq({to: this.peerjid, type: 'set'})
  7498. .c('jingle', {
  7499. xmlns: 'urn:xmpp:jingle:1',
  7500. action: 'source-add',
  7501. initiator: this.initiator,
  7502. sid: this.sid
  7503. }
  7504. );
  7505. var added = sdpDiffer.toJingle(add);
  7506. // Let 'source-add' IQ through the hack and see if we're allowed to send
  7507. // it in the current form
  7508. if (added)
  7509. add = SSRCReplacement.processSourceAdd(add);
  7510. if (added && add) {
  7511. logger.info("Sending source-add", add);
  7512. this.connection.sendIQ(add,
  7513. function (res) {
  7514. logger.info('got add result', res);
  7515. },
  7516. function (err) {
  7517. logger.error('got add error', err);
  7518. }
  7519. );
  7520. } else {
  7521. logger.log('addition not necessary');
  7522. }
  7523. };
  7524. /**
  7525. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7526. *
  7527. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7528. * tracks; otherwise, <tt>false</tt>
  7529. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7530. * tracks have been enabled/disabled. The function may, optionally, return
  7531. * another function which is to be invoked after the whole mute/unmute operation
  7532. * has completed successfully.
  7533. * @param options an object which specifies optional arguments such as the
  7534. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7535. * specifies whether the method was initiated in response to a user command (in
  7536. * contrast to an automatic decision made by the application logic)
  7537. */
  7538. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7539. var byUser;
  7540. if (options) {
  7541. byUser = options.byUser;
  7542. if (typeof byUser === 'undefined') {
  7543. byUser = true;
  7544. }
  7545. } else {
  7546. byUser = true;
  7547. }
  7548. // The user's command to mute the (local) video takes precedence over any
  7549. // automatic decision made by the application logic.
  7550. if (byUser) {
  7551. this.videoMuteByUser = mute;
  7552. } else if (this.videoMuteByUser) {
  7553. return;
  7554. }
  7555. this.hardMuteVideo(mute);
  7556. var self = this;
  7557. var oldSdp = null;
  7558. if(self.peerconnection) {
  7559. if(self.peerconnection.localDescription) {
  7560. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7561. }
  7562. }
  7563. this.modifySourcesQueue.push(function() {
  7564. logger.log('modify sources done');
  7565. callback(mute);
  7566. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7567. logger.log("SDPs", oldSdp, newSdp);
  7568. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7569. });
  7570. };
  7571. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7572. this.pendingop = muted ? 'mute' : 'unmute';
  7573. };
  7574. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7575. var info = $iq({to: this.peerjid,
  7576. type: 'set'})
  7577. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7578. action: 'session-info',
  7579. initiator: this.initiator,
  7580. sid: this.sid });
  7581. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7582. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7583. if (content) {
  7584. info.attrs({'name': content});
  7585. }
  7586. this.connection.send(info);
  7587. };
  7588. JingleSessionPC.prototype.sendRinging = function () {
  7589. var info = $iq({to: this.peerjid,
  7590. type: 'set'})
  7591. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7592. action: 'session-info',
  7593. initiator: this.initiator,
  7594. sid: this.sid });
  7595. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7596. this.connection.send(info);
  7597. };
  7598. JingleSessionPC.prototype.getStats = function (interval) {
  7599. var self = this;
  7600. var recv = {audio: 0, video: 0};
  7601. var lost = {audio: 0, video: 0};
  7602. var lastrecv = {audio: 0, video: 0};
  7603. var lastlost = {audio: 0, video: 0};
  7604. var loss = {audio: 0, video: 0};
  7605. var delta = {audio: 0, video: 0};
  7606. this.statsinterval = window.setInterval(function () {
  7607. if (self && self.peerconnection && self.peerconnection.getStats) {
  7608. self.peerconnection.getStats(function (stats) {
  7609. var results = stats.result();
  7610. // TODO: there are so much statistics you can get from this..
  7611. for (var i = 0; i < results.length; ++i) {
  7612. if (results[i].type == 'ssrc') {
  7613. var packetsrecv = results[i].stat('packetsReceived');
  7614. var packetslost = results[i].stat('packetsLost');
  7615. if (packetsrecv && packetslost) {
  7616. packetsrecv = parseInt(packetsrecv, 10);
  7617. packetslost = parseInt(packetslost, 10);
  7618. if (results[i].stat('googFrameRateReceived')) {
  7619. lastlost.video = lost.video;
  7620. lastrecv.video = recv.video;
  7621. recv.video = packetsrecv;
  7622. lost.video = packetslost;
  7623. } else {
  7624. lastlost.audio = lost.audio;
  7625. lastrecv.audio = recv.audio;
  7626. recv.audio = packetsrecv;
  7627. lost.audio = packetslost;
  7628. }
  7629. }
  7630. }
  7631. }
  7632. delta.audio = recv.audio - lastrecv.audio;
  7633. delta.video = recv.video - lastrecv.video;
  7634. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7635. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7636. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7637. });
  7638. }
  7639. }, interval || 3000);
  7640. return this.statsinterval;
  7641. };
  7642. JingleSessionPC.onJingleError = function (session, error)
  7643. {
  7644. logger.error("Jingle error", error);
  7645. }
  7646. JingleSessionPC.onJingleFatalError = function (session, error)
  7647. {
  7648. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7649. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7650. }
  7651. JingleSessionPC.prototype.setLocalDescription = function () {
  7652. var self = this;
  7653. var newssrcs = [];
  7654. if(!this.peerconnection.localDescription)
  7655. return;
  7656. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7657. var i;
  7658. session.media.forEach(function (media) {
  7659. if (media.ssrcs && media.ssrcs.length > 0) {
  7660. // TODO(gp) maybe exclude FID streams?
  7661. media.ssrcs.forEach(function (ssrc) {
  7662. if (ssrc.attribute !== 'cname') {
  7663. return;
  7664. }
  7665. newssrcs.push({
  7666. 'ssrc': ssrc.id,
  7667. 'type': media.type
  7668. });
  7669. // FIXME allows for only one SSRC per media type
  7670. self.localStreamsSSRC[media.type] = ssrc.id;
  7671. });
  7672. }
  7673. });
  7674. logger.log('new ssrcs', newssrcs);
  7675. // Bind us as local SSRCs owner
  7676. if (newssrcs.length > 0) {
  7677. for (i = 0; i < newssrcs.length; i++) {
  7678. var ssrc = newssrcs[i].ssrc;
  7679. var myJid = self.me;
  7680. self.ssrcOwners[ssrc] = myJid;
  7681. }
  7682. }
  7683. }
  7684. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7685. JingleSessionPC.prototype.sendKeyframe = function () {
  7686. var pc = this.peerconnection;
  7687. logger.log('sendkeyframe', pc.iceConnectionState);
  7688. if (pc.iceConnectionState !== 'connected') return; // safe...
  7689. var self = this;
  7690. pc.setRemoteDescription(
  7691. pc.remoteDescription,
  7692. function () {
  7693. pc.createAnswer(
  7694. function (modifiedAnswer) {
  7695. pc.setLocalDescription(
  7696. modifiedAnswer,
  7697. function () {
  7698. // noop
  7699. },
  7700. function (error) {
  7701. logger.log('triggerKeyframe setLocalDescription failed', error);
  7702. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7703. }
  7704. );
  7705. },
  7706. function (error) {
  7707. logger.log('triggerKeyframe createAnswer failed', error);
  7708. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7709. }
  7710. );
  7711. },
  7712. function (error) {
  7713. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7714. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7715. }
  7716. );
  7717. }
  7718. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7719. var self = this;
  7720. var thessrc;
  7721. var streamId = RTC.getStreamID(data.stream);
  7722. // look up an associated JID for a stream id
  7723. if (!streamId) {
  7724. logger.error("No stream ID for", data.stream);
  7725. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7726. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7727. var ssrclines = this.peerconnection.remoteDescription?
  7728. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7729. ssrclines = ssrclines.filter(function (line) {
  7730. // NOTE(gp) previously we filtered on the mslabel, but that property
  7731. // is not always present.
  7732. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7733. if (RTCBrowserType.isTemasysPluginUsed()) {
  7734. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7735. } else {
  7736. return ((line.indexOf('msid:' + streamId) !== -1));
  7737. }
  7738. });
  7739. if (ssrclines.length) {
  7740. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7741. if (!self.ssrcOwners[thessrc]) {
  7742. logger.error("No SSRC owner known for: " + thessrc);
  7743. return;
  7744. }
  7745. data.peerjid = self.ssrcOwners[thessrc];
  7746. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7747. } else {
  7748. logger.error("No SSRC lines for ", streamId);
  7749. }
  7750. }
  7751. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7752. var isVideo = data.stream.getVideoTracks().length > 0;
  7753. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7754. if (isVideo &&
  7755. data.peerjid && this.peerjid === data.peerjid &&
  7756. data.stream.getVideoTracks().length === 0 &&
  7757. RTC.localVideo.getTracks().length > 0) {
  7758. window.setTimeout(function () {
  7759. self.sendKeyframe();
  7760. }, 3000);
  7761. }
  7762. }
  7763. /**
  7764. * Returns the ice connection state for the peer connection.
  7765. * @returns the ice connection state for the peer connection.
  7766. */
  7767. JingleSessionPC.prototype.getIceConnectionState = function () {
  7768. return this.peerconnection.iceConnectionState;
  7769. }
  7770. module.exports = JingleSessionPC;
  7771. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7772. },{"../../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){
  7773. (function (__filename){
  7774. /* global $ */
  7775. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7776. /*
  7777. Here we do modifications of local video SSRCs. There are 2 situations we have
  7778. to handle:
  7779. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7780. have no local camera and it is not generated automatically, but SSRC=1 is
  7781. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7782. and we won't be able to request video key frames correctly.
  7783. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7784. in future. It turned out that Chrome may keep on using the SSRC of removed
  7785. video stream in RTCP even though a new one has been created. So we just
  7786. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7787. notifications are blocked once first video SSRC is advertised to the focus.
  7788. What this hack does:
  7789. 1. Stores the SSRC of the first video stream created by
  7790. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7791. b) watching for 'source-add' for new video stream if it has not been
  7792. created in step a)
  7793. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7794. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7795. returned to the other parts of the application.
  7796. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7797. blocks those notifications. This makes Jicofo and all participants think
  7798. that it exists all the time even if the video stream has been removed or
  7799. replaced locally. Thanks to that there is no additional signaling activity
  7800. on video mute or when switching to the desktop stream.
  7801. */
  7802. var SDP = require('./SDP');
  7803. var RandomUtil = require('../util/RandomUtil');
  7804. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7805. /**
  7806. * The hack is enabled on all browsers except FF by default
  7807. * FIXME finish the hack once removeStream method is implemented in FF
  7808. * @type {boolean}
  7809. */
  7810. var isEnabled = !RTCBrowserType.isFirefox();
  7811. /**
  7812. * Stored SSRC of local video stream.
  7813. */
  7814. var localVideoSSRC;
  7815. /**
  7816. * SSRC used for recvonly video stream when we have no local camera.
  7817. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7818. * instead of 1.
  7819. */
  7820. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  7821. /**
  7822. * cname for <tt>localRecvOnlySSRC</tt>
  7823. */
  7824. var localRecvOnlyCName;
  7825. /**
  7826. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7827. * from given Jingle IQ.
  7828. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7829. * @param actionName display name of the action which will be printed in log
  7830. * messages.
  7831. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7832. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7833. * other SSRCs left to be signaled after removing it.
  7834. */
  7835. var filterOutSource = function (modifyIq, actionName) {
  7836. var modifyIqTree = $(modifyIq.tree());
  7837. if (!localVideoSSRC)
  7838. return modifyIqTree[0];
  7839. var videoSSRC = modifyIqTree.find(
  7840. '>jingle>content[name="video"]' +
  7841. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7842. if (!videoSSRC.length) {
  7843. return modifyIqTree[0];
  7844. }
  7845. logger.info(
  7846. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7847. videoSSRC.remove();
  7848. // Check if any sources still left to be added/removed
  7849. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7850. return modifyIqTree[0];
  7851. } else {
  7852. return null;
  7853. }
  7854. };
  7855. /**
  7856. * Scans given Jingle IQ for video SSRC and stores it.
  7857. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7858. */
  7859. var storeLocalVideoSSRC = function (jingleIq) {
  7860. var videoSSRCs =
  7861. $(jingleIq.tree())
  7862. .find('>jingle>content[name="video"]>description>source');
  7863. videoSSRCs.each(function (idx, ssrcElem) {
  7864. if (localVideoSSRC)
  7865. return;
  7866. // We consider SSRC real only if it has msid attribute
  7867. // recvonly streams in FF do not have it as well as local SSRCs
  7868. // we generate for recvonly streams in Chrome
  7869. var ssrSel = $(ssrcElem);
  7870. var msid = ssrSel.find('>parameter[name="msid"]');
  7871. if (msid.length) {
  7872. var ssrcVal = ssrSel.attr('ssrc');
  7873. if (ssrcVal) {
  7874. localVideoSSRC = ssrcVal;
  7875. logger.info('Stored local video SSRC' +
  7876. ' for future re-use: ' + localVideoSSRC);
  7877. }
  7878. }
  7879. });
  7880. };
  7881. /**
  7882. * Generates new label/mslabel attribute
  7883. * @returns {string} label/mslabel attribute
  7884. */
  7885. function generateLabel() {
  7886. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  7887. "-" + RandomUtil.randomHexString(4) + "-" +
  7888. RandomUtil.randomHexString(4) + "-" + RandomUtil.randomHexString(12);
  7889. }
  7890. /**
  7891. * Generates new SSRC for local video recvonly stream.
  7892. * FIXME what about eventual SSRC collision ?
  7893. */
  7894. function generateRecvonlySSRC() {
  7895. localVideoSSRC = localRecvOnlySSRC =
  7896. localVideoSSRC ?
  7897. localVideoSSRC : Math.random().toString(10).substring(2, 11);
  7898. localRecvOnlyCName =
  7899. Math.random().toString(36).substring(2);
  7900. localRecvOnlyMSLabel = generateLabel();
  7901. localRecvOnlyLabel = generateLabel();
  7902. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  7903. logger.info(
  7904. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7905. ", cname: " + localRecvOnlyCName);
  7906. }
  7907. var LocalSSRCReplacement = {
  7908. /**
  7909. * Method must be called before 'session-initiate' or 'session-invite' is
  7910. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7911. *
  7912. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7913. * which will be scanned for local video SSRC.
  7914. */
  7915. processSessionInit: function (sessionInit) {
  7916. if (!isEnabled)
  7917. return;
  7918. if (localVideoSSRC) {
  7919. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7920. return;
  7921. }
  7922. storeLocalVideoSSRC(sessionInit);
  7923. },
  7924. /**
  7925. * If we have local video SSRC stored searched given
  7926. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7927. * with the stored one.
  7928. * @param localDescription local description object that will have local
  7929. * video SSRC replaced with the stored one
  7930. * @returns modified <tt>localDescription</tt> object.
  7931. */
  7932. mungeLocalVideoSSRC: function (localDescription) {
  7933. if (!isEnabled)
  7934. return localDescription;
  7935. if (!localDescription) {
  7936. logger.warn("localDescription is null or undefined");
  7937. return localDescription;
  7938. }
  7939. // IF we have local video SSRC stored make sure it is replaced
  7940. // with old SSRC
  7941. var sdp = new SDP(localDescription.sdp);
  7942. if (sdp.media.length < 2)
  7943. return;
  7944. if (localVideoSSRC && sdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7945. !sdp.containsSSRC(localVideoSSRC)) {
  7946. // Get new video SSRC
  7947. var map = sdp.getMediaSsrcMap();
  7948. var videoPart = map[1];
  7949. var videoSSRCs = videoPart.ssrcs;
  7950. var newSSRC = Object.keys(videoSSRCs)[0];
  7951. logger.info(
  7952. "Replacing new video SSRC: " + newSSRC +
  7953. " with " + localVideoSSRC);
  7954. localDescription.sdp =
  7955. sdp.raw.replace(
  7956. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7957. 'a=ssrc:' + localVideoSSRC);
  7958. }
  7959. else if (sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7960. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7961. // Make sure we have any SSRC for recvonly video stream
  7962. if (!localRecvOnlySSRC) {
  7963. generateRecvonlySSRC();
  7964. }
  7965. logger.info('No SSRC in video recvonly stream' +
  7966. ' - adding SSRC: ' + localRecvOnlySSRC);
  7967. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7968. ' cname:' + localRecvOnlyCName + '\r\n' +
  7969. 'a=ssrc:' + localRecvOnlySSRC +
  7970. ' msid:' + localRecvOnlyMSID + '\r\n' +
  7971. 'a=ssrc:' + localRecvOnlySSRC +
  7972. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  7973. 'a=ssrc:' + localRecvOnlySSRC +
  7974. ' label:' + localRecvOnlyLabel + '\r\n';
  7975. localDescription.sdp = sdp.session + sdp.media.join('');
  7976. }
  7977. return localDescription;
  7978. },
  7979. /**
  7980. * Method must be called before 'source-add' notification is sent. In case
  7981. * we have local video SSRC advertised already it will be removed from the
  7982. * notification. If no other SSRCs are described by given IQ null will be
  7983. * returned which means that there is no point in sending the notification.
  7984. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7985. * @returns modified 'source-add' IQ which can be sent to the focus or
  7986. * <tt>null</tt> if no notification shall be sent. It is no longer
  7987. * a Strophe IQ Builder instance, but DOM element tree.
  7988. */
  7989. processSourceAdd: function (sourceAdd) {
  7990. if (!isEnabled)
  7991. return sourceAdd;
  7992. if (!localVideoSSRC) {
  7993. // Store local SSRC if available
  7994. storeLocalVideoSSRC(sourceAdd);
  7995. return sourceAdd;
  7996. } else {
  7997. return filterOutSource(sourceAdd, 'source-add');
  7998. }
  7999. },
  8000. /**
  8001. * Method must be called before 'source-remove' notification is sent.
  8002. * Removes local video SSRC from the notification. If there are no other
  8003. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  8004. * means that there is no point in sending the notification.
  8005. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  8006. * @returns modified 'source-remove' IQ which can be sent to the focus or
  8007. * <tt>null</tt> if no notification shall be sent. It is no longer
  8008. * a Strophe IQ Builder instance, but DOM element tree.
  8009. */
  8010. processSourceRemove: function (sourceRemove) {
  8011. if (!isEnabled)
  8012. return sourceRemove;
  8013. return filterOutSource(sourceRemove, 'source-remove');
  8014. },
  8015. /**
  8016. * Turns the hack on or off
  8017. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  8018. * to disable it
  8019. */
  8020. setEnabled: function (enabled) {
  8021. isEnabled = enabled;
  8022. }
  8023. };
  8024. module.exports = LocalSSRCReplacement;
  8025. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  8026. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":48}],30:[function(require,module,exports){
  8027. (function (__filename){
  8028. /* jshint -W117 */
  8029. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8030. var SDPUtil = require("./SDPUtil");
  8031. // SDP STUFF
  8032. function SDP(sdp) {
  8033. /**
  8034. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  8035. * @type {boolean}
  8036. */
  8037. this.removeTcpCandidates = false;
  8038. /**
  8039. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  8040. * @type {boolean}
  8041. */
  8042. this.removeUdpCandidates = false;
  8043. this.media = sdp.split('\r\nm=');
  8044. for (var i = 1; i < this.media.length; i++) {
  8045. this.media[i] = 'm=' + this.media[i];
  8046. if (i != this.media.length - 1) {
  8047. this.media[i] += '\r\n';
  8048. }
  8049. }
  8050. this.session = this.media.shift() + '\r\n';
  8051. this.raw = this.session + this.media.join('');
  8052. }
  8053. /**
  8054. * Returns map of MediaChannel mapped per channel idx.
  8055. */
  8056. SDP.prototype.getMediaSsrcMap = function() {
  8057. var self = this;
  8058. var media_ssrcs = {};
  8059. var tmp;
  8060. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  8061. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  8062. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  8063. var media = {
  8064. mediaindex: mediaindex,
  8065. mid: mid,
  8066. ssrcs: {},
  8067. ssrcGroups: []
  8068. };
  8069. media_ssrcs[mediaindex] = media;
  8070. tmp.forEach(function (line) {
  8071. var linessrc = line.substring(7).split(' ')[0];
  8072. // allocate new ChannelSsrc
  8073. if(!media.ssrcs[linessrc]) {
  8074. media.ssrcs[linessrc] = {
  8075. ssrc: linessrc,
  8076. lines: []
  8077. };
  8078. }
  8079. media.ssrcs[linessrc].lines.push(line);
  8080. });
  8081. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  8082. tmp.forEach(function(line){
  8083. var idx = line.indexOf(' ');
  8084. var semantics = line.substr(0, idx).substr(13);
  8085. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8086. if (ssrcs.length) {
  8087. media.ssrcGroups.push({
  8088. semantics: semantics,
  8089. ssrcs: ssrcs
  8090. });
  8091. }
  8092. });
  8093. }
  8094. return media_ssrcs;
  8095. };
  8096. /**
  8097. * Returns <tt>true</tt> if this SDP contains given SSRC.
  8098. * @param ssrc the ssrc to check.
  8099. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  8100. */
  8101. SDP.prototype.containsSSRC = function (ssrc) {
  8102. // FIXME this code is really strange - improve it if you can
  8103. var medias = this.getMediaSsrcMap();
  8104. var result = false;
  8105. Object.keys(medias).forEach(function (mediaindex) {
  8106. if (result)
  8107. return;
  8108. if (medias[mediaindex].ssrcs[ssrc]) {
  8109. result = true;
  8110. }
  8111. });
  8112. return result;
  8113. };
  8114. // remove iSAC and CN from SDP
  8115. SDP.prototype.mangle = function () {
  8116. var i, j, mline, lines, rtpmap, newdesc;
  8117. for (i = 0; i < this.media.length; i++) {
  8118. lines = this.media[i].split('\r\n');
  8119. lines.pop(); // remove empty last element
  8120. mline = SDPUtil.parse_mline(lines.shift());
  8121. if (mline.media != 'audio')
  8122. continue;
  8123. newdesc = '';
  8124. mline.fmt.length = 0;
  8125. for (j = 0; j < lines.length; j++) {
  8126. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  8127. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  8128. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  8129. continue;
  8130. mline.fmt.push(rtpmap.id);
  8131. newdesc += lines[j] + '\r\n';
  8132. } else {
  8133. newdesc += lines[j] + '\r\n';
  8134. }
  8135. }
  8136. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  8137. this.media[i] += newdesc;
  8138. }
  8139. this.raw = this.session + this.media.join('');
  8140. };
  8141. // remove lines matching prefix from session section
  8142. SDP.prototype.removeSessionLines = function(prefix) {
  8143. var self = this;
  8144. var lines = SDPUtil.find_lines(this.session, prefix);
  8145. lines.forEach(function(line) {
  8146. self.session = self.session.replace(line + '\r\n', '');
  8147. });
  8148. this.raw = this.session + this.media.join('');
  8149. return lines;
  8150. }
  8151. // remove lines matching prefix from a media section specified by mediaindex
  8152. // TODO: non-numeric mediaindex could match mid
  8153. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  8154. var self = this;
  8155. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  8156. lines.forEach(function(line) {
  8157. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  8158. });
  8159. this.raw = this.session + this.media.join('');
  8160. return lines;
  8161. }
  8162. // add content's to a jingle element
  8163. SDP.prototype.toJingle = function (elem, thecreator) {
  8164. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  8165. var self = this;
  8166. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  8167. // new bundle plan
  8168. if (SDPUtil.find_line(this.session, 'a=group:')) {
  8169. lines = SDPUtil.find_lines(this.session, 'a=group:');
  8170. for (i = 0; i < lines.length; i++) {
  8171. tmp = lines[i].split(' ');
  8172. var semantics = tmp.shift().substr(8);
  8173. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  8174. for (j = 0; j < tmp.length; j++) {
  8175. elem.c('content', {name: tmp[j]}).up();
  8176. }
  8177. elem.up();
  8178. }
  8179. }
  8180. for (i = 0; i < this.media.length; i++) {
  8181. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  8182. if (!(mline.media === 'audio' ||
  8183. mline.media === 'video' ||
  8184. mline.media === 'application'))
  8185. {
  8186. continue;
  8187. }
  8188. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  8189. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  8190. } else {
  8191. ssrc = false;
  8192. }
  8193. elem.c('content', {creator: thecreator, name: mline.media});
  8194. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  8195. // prefer identifier from a=mid if present
  8196. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  8197. elem.attrs({ name: mid });
  8198. }
  8199. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  8200. elem.c('description',
  8201. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  8202. media: mline.media });
  8203. if (ssrc) {
  8204. elem.attrs({ssrc: ssrc});
  8205. }
  8206. for (j = 0; j < mline.fmt.length; j++) {
  8207. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  8208. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  8209. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  8210. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  8211. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  8212. for (k = 0; k < tmp.length; k++) {
  8213. elem.c('parameter', tmp[k]).up();
  8214. }
  8215. }
  8216. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  8217. elem.up();
  8218. }
  8219. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  8220. elem.c('encryption', {required: 1});
  8221. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  8222. crypto.forEach(function(line) {
  8223. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  8224. });
  8225. elem.up(); // end of encryption
  8226. }
  8227. if (ssrc) {
  8228. // new style mapping
  8229. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8230. // FIXME: group by ssrc and support multiple different ssrcs
  8231. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  8232. if(ssrclines.length > 0) {
  8233. ssrclines.forEach(function (line) {
  8234. var idx = line.indexOf(' ');
  8235. var linessrc = line.substr(0, idx).substr(7);
  8236. if (linessrc != ssrc) {
  8237. elem.up();
  8238. ssrc = linessrc;
  8239. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8240. }
  8241. var kv = line.substr(idx + 1);
  8242. elem.c('parameter');
  8243. if (kv.indexOf(':') == -1) {
  8244. elem.attrs({ name: kv });
  8245. } else {
  8246. var k = kv.split(':', 2)[0];
  8247. elem.attrs({ name: k });
  8248. var v = kv.split(':', 2)[1];
  8249. v = SDPUtil.filter_special_chars(v);
  8250. elem.attrs({ value: v });
  8251. }
  8252. elem.up();
  8253. });
  8254. } else {
  8255. elem.up();
  8256. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8257. elem.c('parameter');
  8258. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  8259. elem.up();
  8260. var msid = null;
  8261. if(mline.media == "audio")
  8262. {
  8263. msid = APP.RTC.localAudio._getId();
  8264. }
  8265. else
  8266. {
  8267. msid = APP.RTC.localVideo._getId();
  8268. }
  8269. if(msid != null)
  8270. {
  8271. msid = SDPUtil.filter_special_chars(msid);
  8272. elem.c('parameter');
  8273. elem.attrs({name: "msid", value:msid});
  8274. elem.up();
  8275. elem.c('parameter');
  8276. elem.attrs({name: "mslabel", value:msid});
  8277. elem.up();
  8278. elem.c('parameter');
  8279. elem.attrs({name: "label", value:msid});
  8280. elem.up();
  8281. }
  8282. }
  8283. elem.up();
  8284. // XEP-0339 handle ssrc-group attributes
  8285. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  8286. ssrc_group_lines.forEach(function(line) {
  8287. var idx = line.indexOf(' ');
  8288. var semantics = line.substr(0, idx).substr(13);
  8289. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8290. if (ssrcs.length) {
  8291. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8292. ssrcs.forEach(function(ssrc) {
  8293. elem.c('source', { ssrc: ssrc })
  8294. .up();
  8295. });
  8296. elem.up();
  8297. }
  8298. });
  8299. }
  8300. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  8301. elem.c('rtcp-mux').up();
  8302. }
  8303. // XEP-0293 -- map a=rtcp-fb:*
  8304. this.rtcpFbToJingle(i, elem, '*');
  8305. // XEP-0294
  8306. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  8307. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  8308. for (j = 0; j < lines.length; j++) {
  8309. tmp = SDPUtil.parse_extmap(lines[j]);
  8310. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  8311. uri: tmp.uri,
  8312. id: tmp.value });
  8313. if (tmp.hasOwnProperty('direction')) {
  8314. switch (tmp.direction) {
  8315. case 'sendonly':
  8316. elem.attrs({senders: 'responder'});
  8317. break;
  8318. case 'recvonly':
  8319. elem.attrs({senders: 'initiator'});
  8320. break;
  8321. case 'sendrecv':
  8322. elem.attrs({senders: 'both'});
  8323. break;
  8324. case 'inactive':
  8325. elem.attrs({senders: 'none'});
  8326. break;
  8327. }
  8328. }
  8329. // TODO: handle params
  8330. elem.up();
  8331. }
  8332. }
  8333. elem.up(); // end of description
  8334. }
  8335. // map ice-ufrag/pwd, dtls fingerprint, candidates
  8336. this.transportToJingle(i, elem);
  8337. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  8338. elem.attrs({senders: 'both'});
  8339. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  8340. elem.attrs({senders: 'initiator'});
  8341. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  8342. elem.attrs({senders: 'responder'});
  8343. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  8344. elem.attrs({senders: 'none'});
  8345. }
  8346. if (mline.port == '0') {
  8347. // estos hack to reject an m-line
  8348. elem.attrs({senders: 'rejected'});
  8349. }
  8350. elem.up(); // end of content
  8351. }
  8352. elem.up();
  8353. return elem;
  8354. };
  8355. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  8356. var tmp, sctpmap, sctpAttrs, fingerprints;
  8357. var self = this;
  8358. elem.c('transport');
  8359. // XEP-0343 DTLS/SCTP
  8360. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  8361. {
  8362. sctpmap = SDPUtil.find_line(
  8363. this.media[mediaindex], 'a=sctpmap:', self.session);
  8364. if (sctpmap)
  8365. {
  8366. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  8367. elem.c('sctpmap',
  8368. {
  8369. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  8370. number: sctpAttrs[0], /* SCTP port */
  8371. protocol: sctpAttrs[1] /* protocol */
  8372. });
  8373. // Optional stream count attribute
  8374. if (sctpAttrs.length > 2)
  8375. elem.attrs({ streams: sctpAttrs[2]});
  8376. elem.up();
  8377. }
  8378. }
  8379. // XEP-0320
  8380. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  8381. fingerprints.forEach(function(line) {
  8382. tmp = SDPUtil.parse_fingerprint(line);
  8383. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  8384. elem.c('fingerprint').t(tmp.fingerprint);
  8385. delete tmp.fingerprint;
  8386. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  8387. if (line) {
  8388. tmp.setup = line.substr(8);
  8389. }
  8390. elem.attrs(tmp);
  8391. elem.up(); // end of fingerprint
  8392. });
  8393. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  8394. if (tmp) {
  8395. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  8396. elem.attrs(tmp);
  8397. // XEP-0176
  8398. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  8399. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  8400. lines.forEach(function (line) {
  8401. var candidate = SDPUtil.candidateToJingle(line);
  8402. var protocol = (candidate &&
  8403. typeof candidate.protocol === 'string')
  8404. ? candidate.protocol.toLowerCase() : '';
  8405. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8406. (self.removeUdpCandidates && protocol === 'udp')) {
  8407. return;
  8408. }
  8409. elem.c('candidate', candidate).up();
  8410. });
  8411. }
  8412. }
  8413. elem.up(); // end of transport
  8414. }
  8415. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  8416. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  8417. lines.forEach(function (line) {
  8418. var tmp = SDPUtil.parse_rtcpfb(line);
  8419. if (tmp.type == 'trr-int') {
  8420. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  8421. elem.up();
  8422. } else {
  8423. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  8424. if (tmp.params.length > 0) {
  8425. elem.attrs({'subtype': tmp.params[0]});
  8426. }
  8427. elem.up();
  8428. }
  8429. });
  8430. };
  8431. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  8432. var media = '';
  8433. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8434. if (tmp.length) {
  8435. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  8436. if (tmp.attr('value')) {
  8437. media += tmp.attr('value');
  8438. } else {
  8439. media += '0';
  8440. }
  8441. media += '\r\n';
  8442. }
  8443. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  8444. tmp.each(function () {
  8445. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  8446. if ($(this).attr('subtype')) {
  8447. media += ' ' + $(this).attr('subtype');
  8448. }
  8449. media += '\r\n';
  8450. });
  8451. return media;
  8452. };
  8453. // construct an SDP from a jingle stanza
  8454. SDP.prototype.fromJingle = function (jingle) {
  8455. var self = this;
  8456. this.raw = 'v=0\r\n' +
  8457. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8458. 's=-\r\n' +
  8459. 't=0 0\r\n';
  8460. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  8461. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  8462. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  8463. var contents = $(group).find('>content').map(function (idx, content) {
  8464. return content.getAttribute('name');
  8465. }).get();
  8466. if (contents.length > 0) {
  8467. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  8468. }
  8469. });
  8470. }
  8471. this.session = this.raw;
  8472. jingle.find('>content').each(function () {
  8473. var m = self.jingle2media($(this));
  8474. self.media.push(m);
  8475. });
  8476. // reconstruct msid-semantic -- apparently not necessary
  8477. /*
  8478. var msid = SDPUtil.parse_ssrc(this.raw);
  8479. if (msid.hasOwnProperty('mslabel')) {
  8480. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  8481. }
  8482. */
  8483. this.raw = this.session + this.media.join('');
  8484. };
  8485. // translate a jingle content element into an an SDP media part
  8486. SDP.prototype.jingle2media = function (content) {
  8487. var media = '',
  8488. desc = content.find('description'),
  8489. ssrc = desc.attr('ssrc'),
  8490. self = this,
  8491. tmp;
  8492. var sctp = content.find(
  8493. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  8494. tmp = { media: desc.attr('media') };
  8495. tmp.port = '1';
  8496. if (content.attr('senders') == 'rejected') {
  8497. // estos hack to reject an m-line.
  8498. tmp.port = '0';
  8499. }
  8500. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  8501. if (sctp.length)
  8502. tmp.proto = 'DTLS/SCTP';
  8503. else
  8504. tmp.proto = 'RTP/SAVPF';
  8505. } else {
  8506. tmp.proto = 'RTP/AVPF';
  8507. }
  8508. if (!sctp.length) {
  8509. tmp.fmt = desc.find('payload-type').map(
  8510. function () { return this.getAttribute('id'); }).get();
  8511. media += SDPUtil.build_mline(tmp) + '\r\n';
  8512. } else {
  8513. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  8514. media += 'a=sctpmap:' + sctp.attr('number') +
  8515. ' ' + sctp.attr('protocol');
  8516. var streamCount = sctp.attr('streams');
  8517. if (streamCount)
  8518. media += ' ' + streamCount + '\r\n';
  8519. else
  8520. media += '\r\n';
  8521. }
  8522. media += 'c=IN IP4 0.0.0.0\r\n';
  8523. if (!sctp.length)
  8524. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  8525. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  8526. if (tmp.length) {
  8527. if (tmp.attr('ufrag')) {
  8528. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  8529. }
  8530. if (tmp.attr('pwd')) {
  8531. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  8532. }
  8533. tmp.find('>fingerprint').each(function () {
  8534. // FIXME: check namespace at some point
  8535. media += 'a=fingerprint:' + this.getAttribute('hash');
  8536. media += ' ' + $(this).text();
  8537. media += '\r\n';
  8538. if (this.getAttribute('setup')) {
  8539. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8540. }
  8541. });
  8542. }
  8543. switch (content.attr('senders')) {
  8544. case 'initiator':
  8545. media += 'a=sendonly\r\n';
  8546. break;
  8547. case 'responder':
  8548. media += 'a=recvonly\r\n';
  8549. break;
  8550. case 'none':
  8551. media += 'a=inactive\r\n';
  8552. break;
  8553. case 'both':
  8554. media += 'a=sendrecv\r\n';
  8555. break;
  8556. }
  8557. media += 'a=mid:' + content.attr('name') + '\r\n';
  8558. // <description><rtcp-mux/></description>
  8559. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8560. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8561. if (desc.find('rtcp-mux').length) {
  8562. media += 'a=rtcp-mux\r\n';
  8563. }
  8564. if (desc.find('encryption').length) {
  8565. desc.find('encryption>crypto').each(function () {
  8566. media += 'a=crypto:' + this.getAttribute('tag');
  8567. media += ' ' + this.getAttribute('crypto-suite');
  8568. media += ' ' + this.getAttribute('key-params');
  8569. if (this.getAttribute('session-params')) {
  8570. media += ' ' + this.getAttribute('session-params');
  8571. }
  8572. media += '\r\n';
  8573. });
  8574. }
  8575. desc.find('payload-type').each(function () {
  8576. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8577. if ($(this).find('>parameter').length) {
  8578. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8579. media += $(this).find('parameter').map(function () {
  8580. return (this.getAttribute('name')
  8581. ? (this.getAttribute('name') + '=') : '') +
  8582. this.getAttribute('value');
  8583. }).get().join('; ');
  8584. media += '\r\n';
  8585. }
  8586. // xep-0293
  8587. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8588. });
  8589. // xep-0293
  8590. media += self.rtcpFbFromJingle(desc, '*');
  8591. // xep-0294
  8592. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8593. tmp.each(function () {
  8594. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8595. });
  8596. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8597. var protocol = this.getAttribute('protocol');
  8598. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8599. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8600. (self.removeUdpCandidates && protocol === 'udp')) {
  8601. return;
  8602. }
  8603. media += SDPUtil.candidateFromJingle(this);
  8604. });
  8605. // XEP-0339 handle ssrc-group attributes
  8606. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8607. var semantics = this.getAttribute('semantics');
  8608. var ssrcs = $(this).find('>source').map(function() {
  8609. return this.getAttribute('ssrc');
  8610. }).get();
  8611. if (ssrcs.length) {
  8612. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8613. }
  8614. });
  8615. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8616. tmp.each(function () {
  8617. var ssrc = this.getAttribute('ssrc');
  8618. $(this).find('>parameter').each(function () {
  8619. var name = this.getAttribute('name');
  8620. var value = this.getAttribute('value');
  8621. value = SDPUtil.filter_special_chars(value);
  8622. media += 'a=ssrc:' + ssrc + ' ' + name;
  8623. if (value && value.length)
  8624. media += ':' + value;
  8625. media += '\r\n';
  8626. });
  8627. });
  8628. return media;
  8629. };
  8630. module.exports = SDP;
  8631. }).call(this,"/modules/xmpp/SDP.js")
  8632. },{"./SDPUtil":32,"jitsi-meet-logger":48}],31:[function(require,module,exports){
  8633. var SDPUtil = require("./SDPUtil");
  8634. function SDPDiffer(mySDP, otherSDP)
  8635. {
  8636. this.mySDP = mySDP;
  8637. this.otherSDP = otherSDP;
  8638. }
  8639. /**
  8640. * Returns map of MediaChannel that contains media contained in
  8641. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8642. */
  8643. SDPDiffer.prototype.getNewMedia = function() {
  8644. // this could be useful in Array.prototype.
  8645. function arrayEquals(array) {
  8646. // if the other array is a falsy value, return
  8647. if (!array)
  8648. return false;
  8649. // compare lengths - can save a lot of time
  8650. if (this.length != array.length)
  8651. return false;
  8652. for (var i = 0, l=this.length; i < l; i++) {
  8653. // Check if we have nested arrays
  8654. if (this[i] instanceof Array && array[i] instanceof Array) {
  8655. // recurse into the nested arrays
  8656. if (!this[i].equals(array[i]))
  8657. return false;
  8658. }
  8659. else if (this[i] != array[i]) {
  8660. // Warning - two different object instances will never be
  8661. // equal: {x:20} != {x:20}
  8662. return false;
  8663. }
  8664. }
  8665. return true;
  8666. }
  8667. var myMedias = this.mySDP.getMediaSsrcMap();
  8668. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8669. var newMedia = {};
  8670. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8671. var myMedia = myMedias[othersMediaIdx];
  8672. var othersMedia = othersMedias[othersMediaIdx];
  8673. if(!myMedia && othersMedia) {
  8674. // Add whole channel
  8675. newMedia[othersMediaIdx] = othersMedia;
  8676. return;
  8677. }
  8678. // Look for new ssrcs across the channel
  8679. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8680. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8681. // Allocate channel if we've found ssrc that doesn't exist in
  8682. // our channel
  8683. if(!newMedia[othersMediaIdx]){
  8684. newMedia[othersMediaIdx] = {
  8685. mediaindex: othersMedia.mediaindex,
  8686. mid: othersMedia.mid,
  8687. ssrcs: {},
  8688. ssrcGroups: []
  8689. };
  8690. }
  8691. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8692. }
  8693. });
  8694. // Look for new ssrc groups across the channels
  8695. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8696. // try to match the other ssrc-group with an ssrc-group of ours
  8697. var matched = false;
  8698. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8699. var mySsrcGroup = myMedia.ssrcGroups[i];
  8700. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8701. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8702. [mySsrcGroup.ssrcs])) {
  8703. matched = true;
  8704. break;
  8705. }
  8706. }
  8707. if (!matched) {
  8708. // Allocate channel if we've found an ssrc-group that doesn't
  8709. // exist in our channel
  8710. if(!newMedia[othersMediaIdx]){
  8711. newMedia[othersMediaIdx] = {
  8712. mediaindex: othersMedia.mediaindex,
  8713. mid: othersMedia.mid,
  8714. ssrcs: {},
  8715. ssrcGroups: []
  8716. };
  8717. }
  8718. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8719. }
  8720. });
  8721. });
  8722. return newMedia;
  8723. };
  8724. /**
  8725. * TODO: document!
  8726. */
  8727. SDPDiffer.prototype.toJingle = function(modify) {
  8728. var sdpMediaSsrcs = this.getNewMedia();
  8729. var modified = false;
  8730. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8731. modified = true;
  8732. var media = sdpMediaSsrcs[mediaindex];
  8733. modify.c('content', {name: media.mid});
  8734. modify.c('description',
  8735. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8736. // FIXME: not completely sure this operates on blocks and / or handles
  8737. // different ssrcs correctly
  8738. // generate sources from lines
  8739. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8740. var mediaSsrc = media.ssrcs[ssrcNum];
  8741. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8742. modify.attrs({ssrc: mediaSsrc.ssrc});
  8743. // iterate over ssrc lines
  8744. mediaSsrc.lines.forEach(function (line) {
  8745. var idx = line.indexOf(' ');
  8746. var kv = line.substr(idx + 1);
  8747. modify.c('parameter');
  8748. if (kv.indexOf(':') == -1) {
  8749. modify.attrs({ name: kv });
  8750. } else {
  8751. var nv = kv.split(':', 2);
  8752. var name = nv[0];
  8753. var value = SDPUtil.filter_special_chars(nv[1]);
  8754. modify.attrs({ name: name });
  8755. modify.attrs({ value: value });
  8756. }
  8757. modify.up(); // end of parameter
  8758. });
  8759. modify.up(); // end of source
  8760. });
  8761. // generate source groups from lines
  8762. media.ssrcGroups.forEach(function(ssrcGroup) {
  8763. if (ssrcGroup.ssrcs.length) {
  8764. modify.c('ssrc-group', {
  8765. semantics: ssrcGroup.semantics,
  8766. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8767. });
  8768. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8769. modify.c('source', { ssrc: ssrc })
  8770. .up(); // end of source
  8771. });
  8772. modify.up(); // end of ssrc-group
  8773. }
  8774. });
  8775. modify.up(); // end of description
  8776. modify.up(); // end of content
  8777. });
  8778. return modified;
  8779. };
  8780. module.exports = SDPDiffer;
  8781. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8782. (function (__filename){
  8783. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8784. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8785. SDPUtil = {
  8786. filter_special_chars: function (text) {
  8787. return text.replace(/[\\\/\{,\}\+]/g, "");
  8788. },
  8789. iceparams: function (mediadesc, sessiondesc) {
  8790. var data = null;
  8791. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8792. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8793. data = {
  8794. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8795. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8796. };
  8797. }
  8798. return data;
  8799. },
  8800. parse_iceufrag: function (line) {
  8801. return line.substring(12);
  8802. },
  8803. build_iceufrag: function (frag) {
  8804. return 'a=ice-ufrag:' + frag;
  8805. },
  8806. parse_icepwd: function (line) {
  8807. return line.substring(10);
  8808. },
  8809. build_icepwd: function (pwd) {
  8810. return 'a=ice-pwd:' + pwd;
  8811. },
  8812. parse_mid: function (line) {
  8813. return line.substring(6);
  8814. },
  8815. parse_mline: function (line) {
  8816. var parts = line.substring(2).split(' '),
  8817. data = {};
  8818. data.media = parts.shift();
  8819. data.port = parts.shift();
  8820. data.proto = parts.shift();
  8821. if (parts[parts.length - 1] === '') { // trailing whitespace
  8822. parts.pop();
  8823. }
  8824. data.fmt = parts;
  8825. return data;
  8826. },
  8827. build_mline: function (mline) {
  8828. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8829. },
  8830. parse_rtpmap: function (line) {
  8831. var parts = line.substring(9).split(' '),
  8832. data = {};
  8833. data.id = parts.shift();
  8834. parts = parts[0].split('/');
  8835. data.name = parts.shift();
  8836. data.clockrate = parts.shift();
  8837. data.channels = parts.length ? parts.shift() : '1';
  8838. return data;
  8839. },
  8840. /**
  8841. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8842. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8843. * @returns [SCTP port number, protocol, streams]
  8844. */
  8845. parse_sctpmap: function (line)
  8846. {
  8847. var parts = line.substring(10).split(' ');
  8848. var sctpPort = parts[0];
  8849. var protocol = parts[1];
  8850. // Stream count is optional
  8851. var streamCount = parts.length > 2 ? parts[2] : null;
  8852. return [sctpPort, protocol, streamCount];// SCTP port
  8853. },
  8854. build_rtpmap: function (el) {
  8855. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8856. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8857. line += '/' + el.getAttribute('channels');
  8858. }
  8859. return line;
  8860. },
  8861. parse_crypto: function (line) {
  8862. var parts = line.substring(9).split(' '),
  8863. data = {};
  8864. data.tag = parts.shift();
  8865. data['crypto-suite'] = parts.shift();
  8866. data['key-params'] = parts.shift();
  8867. if (parts.length) {
  8868. data['session-params'] = parts.join(' ');
  8869. }
  8870. return data;
  8871. },
  8872. parse_fingerprint: function (line) { // RFC 4572
  8873. var parts = line.substring(14).split(' '),
  8874. data = {};
  8875. data.hash = parts.shift();
  8876. data.fingerprint = parts.shift();
  8877. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8878. return data;
  8879. },
  8880. parse_fmtp: function (line) {
  8881. var parts = line.split(' '),
  8882. i, key, value,
  8883. data = [];
  8884. parts.shift();
  8885. parts = parts.join(' ').split(';');
  8886. for (i = 0; i < parts.length; i++) {
  8887. key = parts[i].split('=')[0];
  8888. while (key.length && key[0] == ' ') {
  8889. key = key.substring(1);
  8890. }
  8891. value = parts[i].split('=')[1];
  8892. if (key && value) {
  8893. data.push({name: key, value: value});
  8894. } else if (key) {
  8895. // rfc 4733 (DTMF) style stuff
  8896. data.push({name: '', value: key});
  8897. }
  8898. }
  8899. return data;
  8900. },
  8901. parse_icecandidate: function (line) {
  8902. var candidate = {},
  8903. elems = line.split(' ');
  8904. candidate.foundation = elems[0].substring(12);
  8905. candidate.component = elems[1];
  8906. candidate.protocol = elems[2].toLowerCase();
  8907. candidate.priority = elems[3];
  8908. candidate.ip = elems[4];
  8909. candidate.port = elems[5];
  8910. // elems[6] => "typ"
  8911. candidate.type = elems[7];
  8912. candidate.generation = 0; // default value, may be overwritten below
  8913. for (var i = 8; i < elems.length; i += 2) {
  8914. switch (elems[i]) {
  8915. case 'raddr':
  8916. candidate['rel-addr'] = elems[i + 1];
  8917. break;
  8918. case 'rport':
  8919. candidate['rel-port'] = elems[i + 1];
  8920. break;
  8921. case 'generation':
  8922. candidate.generation = elems[i + 1];
  8923. break;
  8924. case 'tcptype':
  8925. candidate.tcptype = elems[i + 1];
  8926. break;
  8927. default: // TODO
  8928. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8929. }
  8930. }
  8931. candidate.network = '1';
  8932. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8933. return candidate;
  8934. },
  8935. build_icecandidate: function (cand) {
  8936. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8937. line += ' ';
  8938. switch (cand.type) {
  8939. case 'srflx':
  8940. case 'prflx':
  8941. case 'relay':
  8942. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8943. line += 'raddr';
  8944. line += ' ';
  8945. line += cand['rel-addr'];
  8946. line += ' ';
  8947. line += 'rport';
  8948. line += ' ';
  8949. line += cand['rel-port'];
  8950. line += ' ';
  8951. }
  8952. break;
  8953. }
  8954. if (cand.hasOwnAttribute('tcptype')) {
  8955. line += 'tcptype';
  8956. line += ' ';
  8957. line += cand.tcptype;
  8958. line += ' ';
  8959. }
  8960. line += 'generation';
  8961. line += ' ';
  8962. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8963. return line;
  8964. },
  8965. parse_ssrc: function (desc) {
  8966. // proprietary mapping of a=ssrc lines
  8967. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8968. // and parse according to that
  8969. var lines = desc.split('\r\n'),
  8970. data = {};
  8971. for (var i = 0; i < lines.length; i++) {
  8972. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8973. var idx = lines[i].indexOf(' ');
  8974. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8975. }
  8976. }
  8977. return data;
  8978. },
  8979. parse_rtcpfb: function (line) {
  8980. var parts = line.substr(10).split(' ');
  8981. var data = {};
  8982. data.pt = parts.shift();
  8983. data.type = parts.shift();
  8984. data.params = parts;
  8985. return data;
  8986. },
  8987. parse_extmap: function (line) {
  8988. var parts = line.substr(9).split(' ');
  8989. var data = {};
  8990. data.value = parts.shift();
  8991. if (data.value.indexOf('/') != -1) {
  8992. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8993. data.value = data.value.substr(0, data.value.indexOf('/'));
  8994. } else {
  8995. data.direction = 'both';
  8996. }
  8997. data.uri = parts.shift();
  8998. data.params = parts;
  8999. return data;
  9000. },
  9001. find_line: function (haystack, needle, sessionpart) {
  9002. var lines = haystack.split('\r\n');
  9003. for (var i = 0; i < lines.length; i++) {
  9004. if (lines[i].substring(0, needle.length) == needle) {
  9005. return lines[i];
  9006. }
  9007. }
  9008. if (!sessionpart) {
  9009. return false;
  9010. }
  9011. // search session part
  9012. lines = sessionpart.split('\r\n');
  9013. for (var j = 0; j < lines.length; j++) {
  9014. if (lines[j].substring(0, needle.length) == needle) {
  9015. return lines[j];
  9016. }
  9017. }
  9018. return false;
  9019. },
  9020. find_lines: function (haystack, needle, sessionpart) {
  9021. var lines = haystack.split('\r\n'),
  9022. needles = [];
  9023. for (var i = 0; i < lines.length; i++) {
  9024. if (lines[i].substring(0, needle.length) == needle)
  9025. needles.push(lines[i]);
  9026. }
  9027. if (needles.length || !sessionpart) {
  9028. return needles;
  9029. }
  9030. // search session part
  9031. lines = sessionpart.split('\r\n');
  9032. for (var j = 0; j < lines.length; j++) {
  9033. if (lines[j].substring(0, needle.length) == needle) {
  9034. needles.push(lines[j]);
  9035. }
  9036. }
  9037. return needles;
  9038. },
  9039. candidateToJingle: function (line) {
  9040. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  9041. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  9042. if (line.indexOf('candidate:') === 0) {
  9043. line = 'a=' + line;
  9044. } else if (line.substring(0, 12) != 'a=candidate:') {
  9045. logger.log('parseCandidate called with a line that is not a candidate line');
  9046. logger.log(line);
  9047. return null;
  9048. }
  9049. if (line.substring(line.length - 2) == '\r\n') // chomp it
  9050. line = line.substring(0, line.length - 2);
  9051. var candidate = {},
  9052. elems = line.split(' '),
  9053. i;
  9054. if (elems[6] != 'typ') {
  9055. logger.log('did not find typ in the right place');
  9056. logger.log(line);
  9057. return null;
  9058. }
  9059. candidate.foundation = elems[0].substring(12);
  9060. candidate.component = elems[1];
  9061. candidate.protocol = elems[2].toLowerCase();
  9062. candidate.priority = elems[3];
  9063. candidate.ip = elems[4];
  9064. candidate.port = elems[5];
  9065. // elems[6] => "typ"
  9066. candidate.type = elems[7];
  9067. candidate.generation = '0'; // default, may be overwritten below
  9068. for (i = 8; i < elems.length; i += 2) {
  9069. switch (elems[i]) {
  9070. case 'raddr':
  9071. candidate['rel-addr'] = elems[i + 1];
  9072. break;
  9073. case 'rport':
  9074. candidate['rel-port'] = elems[i + 1];
  9075. break;
  9076. case 'generation':
  9077. candidate.generation = elems[i + 1];
  9078. break;
  9079. case 'tcptype':
  9080. candidate.tcptype = elems[i + 1];
  9081. break;
  9082. default: // TODO
  9083. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9084. }
  9085. }
  9086. candidate.network = '1';
  9087. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9088. return candidate;
  9089. },
  9090. candidateFromJingle: function (cand) {
  9091. var line = 'a=candidate:';
  9092. line += cand.getAttribute('foundation');
  9093. line += ' ';
  9094. line += cand.getAttribute('component');
  9095. line += ' ';
  9096. var protocol = cand.getAttribute('protocol');
  9097. // use tcp candidates for FF
  9098. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  9099. protocol = 'tcp';
  9100. }
  9101. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  9102. line += ' ';
  9103. line += cand.getAttribute('priority');
  9104. line += ' ';
  9105. line += cand.getAttribute('ip');
  9106. line += ' ';
  9107. line += cand.getAttribute('port');
  9108. line += ' ';
  9109. line += 'typ';
  9110. line += ' ' + cand.getAttribute('type');
  9111. line += ' ';
  9112. switch (cand.getAttribute('type')) {
  9113. case 'srflx':
  9114. case 'prflx':
  9115. case 'relay':
  9116. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  9117. line += 'raddr';
  9118. line += ' ';
  9119. line += cand.getAttribute('rel-addr');
  9120. line += ' ';
  9121. line += 'rport';
  9122. line += ' ';
  9123. line += cand.getAttribute('rel-port');
  9124. line += ' ';
  9125. }
  9126. break;
  9127. }
  9128. if (protocol.toLowerCase() == 'tcp') {
  9129. line += 'tcptype';
  9130. line += ' ';
  9131. line += cand.getAttribute('tcptype');
  9132. line += ' ';
  9133. }
  9134. line += 'generation';
  9135. line += ' ';
  9136. line += cand.getAttribute('generation') || '0';
  9137. return line + '\r\n';
  9138. }
  9139. };
  9140. module.exports = SDPUtil;
  9141. }).call(this,"/modules/xmpp/SDPUtil.js")
  9142. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":48}],33:[function(require,module,exports){
  9143. (function (__filename){
  9144. /* global $ */
  9145. var RTC = require('../RTC/RTC');
  9146. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9147. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  9148. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9149. var SSRCReplacement = require("./LocalSSRCReplacement");
  9150. function TraceablePeerConnection(ice_config, constraints, session) {
  9151. var self = this;
  9152. this.session = session;
  9153. var RTCPeerConnectionType = null;
  9154. if (RTCBrowserType.isFirefox()) {
  9155. RTCPeerConnectionType = mozRTCPeerConnection;
  9156. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  9157. RTCPeerConnectionType = RTCPeerConnection;
  9158. } else {
  9159. RTCPeerConnectionType = webkitRTCPeerConnection;
  9160. }
  9161. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  9162. this.updateLog = [];
  9163. this.stats = {};
  9164. this.statsinterval = null;
  9165. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  9166. var Interop = require('sdp-interop').Interop;
  9167. this.interop = new Interop();
  9168. var Simulcast = require('sdp-simulcast');
  9169. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  9170. // override as desired
  9171. this.trace = function (what, info) {
  9172. /*logger.warn('WTRACE', what, info);
  9173. if (info && RTCBrowserType.isIExplorer()) {
  9174. if (info.length > 1024) {
  9175. logger.warn('WTRACE', what, info.substr(1024));
  9176. }
  9177. if (info.length > 2048) {
  9178. logger.warn('WTRACE', what, info.substr(2048));
  9179. }
  9180. }*/
  9181. self.updateLog.push({
  9182. time: new Date(),
  9183. type: what,
  9184. value: info || ""
  9185. });
  9186. };
  9187. this.onicecandidate = null;
  9188. this.peerconnection.onicecandidate = function (event) {
  9189. // FIXME: this causes stack overflow with Temasys Plugin
  9190. if (!RTCBrowserType.isTemasysPluginUsed())
  9191. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  9192. if (self.onicecandidate !== null) {
  9193. self.onicecandidate(event);
  9194. }
  9195. };
  9196. this.onaddstream = null;
  9197. this.peerconnection.onaddstream = function (event) {
  9198. self.trace('onaddstream', event.stream.id);
  9199. if (self.onaddstream !== null) {
  9200. self.onaddstream(event);
  9201. }
  9202. };
  9203. this.onremovestream = null;
  9204. this.peerconnection.onremovestream = function (event) {
  9205. self.trace('onremovestream', event.stream.id);
  9206. if (self.onremovestream !== null) {
  9207. self.onremovestream(event);
  9208. }
  9209. };
  9210. this.onsignalingstatechange = null;
  9211. this.peerconnection.onsignalingstatechange = function (event) {
  9212. self.trace('onsignalingstatechange', self.signalingState);
  9213. if (self.onsignalingstatechange !== null) {
  9214. self.onsignalingstatechange(event);
  9215. }
  9216. };
  9217. this.oniceconnectionstatechange = null;
  9218. this.peerconnection.oniceconnectionstatechange = function (event) {
  9219. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  9220. if (self.oniceconnectionstatechange !== null) {
  9221. self.oniceconnectionstatechange(event);
  9222. }
  9223. };
  9224. this.onnegotiationneeded = null;
  9225. this.peerconnection.onnegotiationneeded = function (event) {
  9226. self.trace('onnegotiationneeded');
  9227. if (self.onnegotiationneeded !== null) {
  9228. self.onnegotiationneeded(event);
  9229. }
  9230. };
  9231. self.ondatachannel = null;
  9232. this.peerconnection.ondatachannel = function (event) {
  9233. self.trace('ondatachannel', event);
  9234. if (self.ondatachannel !== null) {
  9235. self.ondatachannel(event);
  9236. }
  9237. };
  9238. // XXX: do all non-firefox browsers which we support also support this?
  9239. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  9240. this.statsinterval = window.setInterval(function() {
  9241. self.peerconnection.getStats(function(stats) {
  9242. var results = stats.result();
  9243. var now = new Date();
  9244. for (var i = 0; i < results.length; ++i) {
  9245. results[i].names().forEach(function (name) {
  9246. var id = results[i].id + '-' + name;
  9247. if (!self.stats[id]) {
  9248. self.stats[id] = {
  9249. startTime: now,
  9250. endTime: now,
  9251. values: [],
  9252. times: []
  9253. };
  9254. }
  9255. self.stats[id].values.push(results[i].stat(name));
  9256. self.stats[id].times.push(now.getTime());
  9257. if (self.stats[id].values.length > self.maxstats) {
  9258. self.stats[id].values.shift();
  9259. self.stats[id].times.shift();
  9260. }
  9261. self.stats[id].endTime = now;
  9262. });
  9263. }
  9264. });
  9265. }, 1000);
  9266. }
  9267. }
  9268. /**
  9269. * Returns a string representation of a SessionDescription object.
  9270. */
  9271. var dumpSDP = function(description) {
  9272. if (typeof description === 'undefined' || description == null) {
  9273. return '';
  9274. }
  9275. return 'type: ' + description.type + '\r\n' + description.sdp;
  9276. };
  9277. /**
  9278. * Takes a SessionDescription object and returns a "normalized" version.
  9279. * Currently it only takes care of ordering the a=ssrc lines.
  9280. */
  9281. var normalizePlanB = function(desc) {
  9282. if (typeof desc !== 'object' || desc === null ||
  9283. typeof desc.sdp !== 'string') {
  9284. logger.warn('An empty description was passed as an argument.');
  9285. return desc;
  9286. }
  9287. var transform = require('sdp-transform');
  9288. var session = transform.parse(desc.sdp);
  9289. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  9290. Array.isArray(session.media)) {
  9291. session.media.forEach(function (mLine) {
  9292. // Chrome appears to be picky about the order in which a=ssrc lines
  9293. // are listed in an m-line when rtx is enabled (and thus there are
  9294. // a=ssrc-group lines with FID semantics). Specifically if we have
  9295. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  9296. // the "a=ssrc:S1" lines, SRD fails.
  9297. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  9298. // first.
  9299. var firstSsrcs = [];
  9300. var newSsrcLines = [];
  9301. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  9302. mLine.ssrcGroups.forEach(function (group) {
  9303. if (typeof group.semantics !== 'undefined' &&
  9304. group.semantics === 'FID') {
  9305. if (typeof group.ssrcs !== 'undefined') {
  9306. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  9307. }
  9308. }
  9309. });
  9310. }
  9311. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  9312. var i;
  9313. for (i = 0; i<mLine.ssrcs.length; i++){
  9314. if (typeof mLine.ssrcs[i] === 'object'
  9315. && typeof mLine.ssrcs[i].id !== 'undefined'
  9316. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  9317. newSsrcLines.push(mLine.ssrcs[i]);
  9318. delete mLine.ssrcs[i];
  9319. }
  9320. }
  9321. for (i = 0; i<mLine.ssrcs.length; i++){
  9322. if (typeof mLine.ssrcs[i] !== 'undefined') {
  9323. newSsrcLines.push(mLine.ssrcs[i]);
  9324. }
  9325. }
  9326. mLine.ssrcs = newSsrcLines;
  9327. }
  9328. });
  9329. }
  9330. var resStr = transform.write(session);
  9331. return new RTCSessionDescription({
  9332. type: desc.type,
  9333. sdp: resStr
  9334. });
  9335. };
  9336. var getters = {
  9337. signalingState: function () {
  9338. return this.peerconnection.signalingState;
  9339. },
  9340. iceConnectionState: function () {
  9341. return this.peerconnection.iceConnectionState;
  9342. },
  9343. localDescription: function() {
  9344. var desc = this.peerconnection.localDescription;
  9345. // FIXME this should probably be after the Unified Plan -> Plan B
  9346. // transformation.
  9347. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  9348. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  9349. // if we're running on FF, transform to Plan B first.
  9350. if (RTCBrowserType.usesUnifiedPlan()) {
  9351. desc = this.interop.toPlanB(desc);
  9352. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  9353. }
  9354. return desc;
  9355. },
  9356. remoteDescription: function() {
  9357. var desc = this.peerconnection.remoteDescription;
  9358. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  9359. // if we're running on FF, transform to Plan B first.
  9360. if (RTCBrowserType.usesUnifiedPlan()) {
  9361. desc = this.interop.toPlanB(desc);
  9362. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  9363. }
  9364. return desc;
  9365. }
  9366. };
  9367. Object.keys(getters).forEach(function (prop) {
  9368. Object.defineProperty(
  9369. TraceablePeerConnection.prototype,
  9370. prop, {
  9371. get: getters[prop]
  9372. }
  9373. );
  9374. });
  9375. TraceablePeerConnection.prototype.addStream = function (stream) {
  9376. this.trace('addStream', stream.id);
  9377. try
  9378. {
  9379. this.peerconnection.addStream(stream);
  9380. }
  9381. catch (e)
  9382. {
  9383. logger.error(e);
  9384. }
  9385. };
  9386. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  9387. this.trace('removeStream', stream.id);
  9388. if(stopStreams) {
  9389. RTC.stopMediaStream(stream);
  9390. }
  9391. try {
  9392. // FF doesn't support this yet.
  9393. if (this.peerconnection.removeStream)
  9394. this.peerconnection.removeStream(stream);
  9395. } catch (e) {
  9396. logger.error(e);
  9397. }
  9398. };
  9399. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  9400. this.trace('createDataChannel', label, opts);
  9401. return this.peerconnection.createDataChannel(label, opts);
  9402. };
  9403. TraceablePeerConnection.prototype.setLocalDescription
  9404. = function (description, successCallback, failureCallback) {
  9405. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  9406. // if we're running on FF, transform to Plan A first.
  9407. if (RTCBrowserType.usesUnifiedPlan()) {
  9408. description = this.interop.toUnifiedPlan(description);
  9409. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  9410. }
  9411. var self = this;
  9412. this.peerconnection.setLocalDescription(description,
  9413. function () {
  9414. self.trace('setLocalDescriptionOnSuccess');
  9415. successCallback();
  9416. },
  9417. function (err) {
  9418. self.trace('setLocalDescriptionOnFailure', err);
  9419. failureCallback(err);
  9420. }
  9421. );
  9422. /*
  9423. if (this.statsinterval === null && this.maxstats > 0) {
  9424. // start gathering stats
  9425. }
  9426. */
  9427. };
  9428. TraceablePeerConnection.prototype.setRemoteDescription
  9429. = function (description, successCallback, failureCallback) {
  9430. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  9431. // TODO the focus should squeze or explode the remote simulcast
  9432. description = this.simulcast.mungeRemoteDescription(description);
  9433. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  9434. // if we're running on FF, transform to Plan A first.
  9435. if (RTCBrowserType.usesUnifiedPlan()) {
  9436. description = this.interop.toUnifiedPlan(description);
  9437. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  9438. }
  9439. if (RTCBrowserType.usesPlanB()) {
  9440. description = normalizePlanB(description);
  9441. }
  9442. var self = this;
  9443. this.peerconnection.setRemoteDescription(description,
  9444. function () {
  9445. self.trace('setRemoteDescriptionOnSuccess');
  9446. successCallback();
  9447. },
  9448. function (err) {
  9449. self.trace('setRemoteDescriptionOnFailure', err);
  9450. failureCallback(err);
  9451. }
  9452. );
  9453. /*
  9454. if (this.statsinterval === null && this.maxstats > 0) {
  9455. // start gathering stats
  9456. }
  9457. */
  9458. };
  9459. TraceablePeerConnection.prototype.close = function () {
  9460. this.trace('stop');
  9461. if (this.statsinterval !== null) {
  9462. window.clearInterval(this.statsinterval);
  9463. this.statsinterval = null;
  9464. }
  9465. this.peerconnection.close();
  9466. };
  9467. TraceablePeerConnection.prototype.createOffer
  9468. = function (successCallback, failureCallback, constraints) {
  9469. var self = this;
  9470. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  9471. this.peerconnection.createOffer(
  9472. function (offer) {
  9473. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  9474. // NOTE this is not tested because in meet the focus generates the
  9475. // offer.
  9476. // if we're running on FF, transform to Plan B first.
  9477. if (RTCBrowserType.usesUnifiedPlan()) {
  9478. offer = self.interop.toPlanB(offer);
  9479. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  9480. }
  9481. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  9482. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9483. offer = self.simulcast.mungeLocalDescription(offer);
  9484. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  9485. }
  9486. successCallback(offer);
  9487. },
  9488. function(err) {
  9489. self.trace('createOfferOnFailure', err);
  9490. failureCallback(err);
  9491. },
  9492. constraints
  9493. );
  9494. };
  9495. TraceablePeerConnection.prototype.createAnswer
  9496. = function (successCallback, failureCallback, constraints) {
  9497. var self = this;
  9498. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  9499. this.peerconnection.createAnswer(
  9500. function (answer) {
  9501. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  9502. // if we're running on FF, transform to Plan A first.
  9503. if (RTCBrowserType.usesUnifiedPlan()) {
  9504. answer = self.interop.toPlanB(answer);
  9505. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  9506. }
  9507. // munge local video SSRC
  9508. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  9509. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  9510. answer = self.simulcast.mungeLocalDescription(answer);
  9511. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  9512. }
  9513. successCallback(answer);
  9514. },
  9515. function(err) {
  9516. self.trace('createAnswerOnFailure', err);
  9517. failureCallback(err);
  9518. },
  9519. constraints
  9520. );
  9521. };
  9522. TraceablePeerConnection.prototype.addIceCandidate
  9523. = function (candidate, successCallback, failureCallback) {
  9524. //var self = this;
  9525. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  9526. this.peerconnection.addIceCandidate(candidate);
  9527. /* maybe later
  9528. this.peerconnection.addIceCandidate(candidate,
  9529. function () {
  9530. self.trace('addIceCandidateOnSuccess');
  9531. successCallback();
  9532. },
  9533. function (err) {
  9534. self.trace('addIceCandidateOnFailure', err);
  9535. failureCallback(err);
  9536. }
  9537. );
  9538. */
  9539. };
  9540. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9541. // TODO: Is this the correct way to handle Opera, Temasys?
  9542. if (RTCBrowserType.isFirefox()) {
  9543. // ignore for now...
  9544. if(!errback)
  9545. errback = function () {};
  9546. this.peerconnection.getStats(null, callback, errback);
  9547. } else {
  9548. this.peerconnection.getStats(callback);
  9549. }
  9550. };
  9551. module.exports = TraceablePeerConnection;
  9552. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9553. },{"../../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){
  9554. (function (__filename){
  9555. /* global $, $iq, Promise, Strophe */
  9556. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9557. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9558. var Settings = require("../settings/Settings");
  9559. var AuthenticationEvents
  9560. = require("../../service/authentication/AuthenticationEvents");
  9561. function createExpBackoffTimer(step) {
  9562. var count = 1;
  9563. return function (reset) {
  9564. // Reset call
  9565. if (reset) {
  9566. count = 1;
  9567. return;
  9568. }
  9569. // Calculate next timeout
  9570. var timeout = Math.pow(2, count - 1);
  9571. count += 1;
  9572. return timeout * step;
  9573. };
  9574. }
  9575. function Moderator(roomName, xmpp, emitter) {
  9576. this.roomName = roomName;
  9577. this.xmppService = xmpp;
  9578. this.getNextTimeout = createExpBackoffTimer(1000);
  9579. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9580. // External authentication stuff
  9581. this.externalAuthEnabled = false;
  9582. this.settings = new Settings(roomName);
  9583. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9584. // it will be enabled automatically if focus detects the component through
  9585. // service discovery.
  9586. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  9587. this.xmppService.options.hosts.call_control !== undefined;
  9588. this.eventEmitter = emitter;
  9589. this.connection = this.xmppService.connection;
  9590. this.focusUserJid;
  9591. //FIXME:
  9592. // Message listener that talks to POPUP window
  9593. function listener(event) {
  9594. if (event.data && event.data.sessionId) {
  9595. if (event.origin !== window.location.origin) {
  9596. logger.warn("Ignoring sessionId from different origin: " +
  9597. event.origin);
  9598. return;
  9599. }
  9600. localStorage.setItem('sessionId', event.data.sessionId);
  9601. // After popup is closed we will authenticate
  9602. }
  9603. }
  9604. // Register
  9605. if (window.addEventListener) {
  9606. window.addEventListener("message", listener, false);
  9607. } else {
  9608. window.attachEvent("onmessage", listener);
  9609. }
  9610. }
  9611. Moderator.prototype.isExternalAuthEnabled = function () {
  9612. return this.externalAuthEnabled;
  9613. };
  9614. Moderator.prototype.isSipGatewayEnabled = function () {
  9615. return this.sipGatewayEnabled;
  9616. };
  9617. Moderator.prototype.onMucMemberLeft = function (jid) {
  9618. logger.info("Someone left is it focus ? " + jid);
  9619. var resource = Strophe.getResourceFromJid(jid);
  9620. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9621. logger.info(
  9622. "Focus has left the room - leaving conference");
  9623. //hangUp();
  9624. // We'd rather reload to have everything re-initialized
  9625. //FIXME: show some message before reload
  9626. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9627. }
  9628. };
  9629. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9630. if (!this.focusUserJid) {
  9631. this.focusUserJid = focusJid;
  9632. logger.info("Focus jid set to: " + this.focusUserJid);
  9633. }
  9634. };
  9635. Moderator.prototype.getFocusUserJid = function () {
  9636. return this.focusUserJid;
  9637. };
  9638. Moderator.prototype.getFocusComponent = function () {
  9639. // Get focus component address
  9640. var focusComponent = this.xmppService.options.hosts.focus;
  9641. // If not specified use default: 'focus.domain'
  9642. if (!focusComponent) {
  9643. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9644. }
  9645. return focusComponent;
  9646. };
  9647. Moderator.prototype.createConferenceIq = function () {
  9648. // Generate create conference IQ
  9649. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9650. // Session Id used for authentication
  9651. var sessionId = localStorage.getItem('sessionId');
  9652. var machineUID = this.settings.getSettings().uid;
  9653. logger.info(
  9654. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9655. elem.c('conference', {
  9656. xmlns: 'http://jitsi.org/protocol/focus',
  9657. room: this.roomName,
  9658. 'machine-uid': machineUID
  9659. });
  9660. if (sessionId) {
  9661. elem.attrs({ 'session-id': sessionId});
  9662. }
  9663. if (this.xmppService.options.hosts.bridge !== undefined) {
  9664. elem.c(
  9665. 'property', {
  9666. name: 'bridge',
  9667. value: this.xmppService.options.hosts.bridge
  9668. }).up();
  9669. }
  9670. if (this.xmppService.options.enforcedBridge !== undefined) {
  9671. elem.c(
  9672. 'property', {
  9673. name: 'enforcedBridge',
  9674. value: this.xmppService.options.enforcedBridge
  9675. }).up();
  9676. }
  9677. // Tell the focus we have Jigasi configured
  9678. if (this.xmppService.options.hosts.call_control !== undefined) {
  9679. elem.c(
  9680. 'property', {
  9681. name: 'call_control',
  9682. value: this.xmppService.options.hosts.call_control
  9683. }).up();
  9684. }
  9685. if (this.xmppService.options.channelLastN !== undefined) {
  9686. elem.c(
  9687. 'property', {
  9688. name: 'channelLastN',
  9689. value: this.xmppService.options.channelLastN
  9690. }).up();
  9691. }
  9692. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9693. elem.c(
  9694. 'property', {
  9695. name: 'adaptiveLastN',
  9696. value: this.xmppService.options.adaptiveLastN
  9697. }).up();
  9698. }
  9699. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9700. elem.c(
  9701. 'property', {
  9702. name: 'adaptiveSimulcast',
  9703. value: this.xmppService.options.adaptiveSimulcast
  9704. }).up();
  9705. }
  9706. if (this.xmppService.options.openSctp !== undefined) {
  9707. elem.c(
  9708. 'property', {
  9709. name: 'openSctp',
  9710. value: this.xmppService.options.openSctp
  9711. }).up();
  9712. }
  9713. if (this.xmppService.options.startAudioMuted !== undefined)
  9714. {
  9715. elem.c(
  9716. 'property', {
  9717. name: 'startAudioMuted',
  9718. value: this.xmppService.options.startAudioMuted
  9719. }).up();
  9720. }
  9721. if (this.xmppService.options.startVideoMuted !== undefined)
  9722. {
  9723. elem.c(
  9724. 'property', {
  9725. name: 'startVideoMuted',
  9726. value: this.xmppService.options.startVideoMuted
  9727. }).up();
  9728. }
  9729. elem.c(
  9730. 'property', {
  9731. name: 'simulcastMode',
  9732. value: 'rewriting'
  9733. }).up();
  9734. elem.up();
  9735. return elem;
  9736. };
  9737. Moderator.prototype.parseSessionId = function (resultIq) {
  9738. var sessionId = $(resultIq).find('conference').attr('session-id');
  9739. if (sessionId) {
  9740. logger.info('Received sessionId: ' + sessionId);
  9741. localStorage.setItem('sessionId', sessionId);
  9742. }
  9743. };
  9744. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9745. this.setFocusUserJid(
  9746. $(resultIq).find('conference').attr('focusjid'));
  9747. var authenticationEnabled
  9748. = $(resultIq).find(
  9749. '>conference>property' +
  9750. '[name=\'authentication\'][value=\'true\']').length > 0;
  9751. logger.info("Authentication enabled: " + authenticationEnabled);
  9752. this.externalAuthEnabled = $(resultIq).find(
  9753. '>conference>property' +
  9754. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9755. console.info(
  9756. 'External authentication enabled: ' + this.externalAuthEnabled);
  9757. if (!this.externalAuthEnabled) {
  9758. // We expect to receive sessionId in 'internal' authentication mode
  9759. this.parseSessionId(resultIq);
  9760. }
  9761. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9762. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9763. authenticationEnabled, authIdentity);
  9764. // Check if focus has auto-detected Jigasi component(this will be also
  9765. // included if we have passed our host from the config)
  9766. if ($(resultIq).find(
  9767. '>conference>property' +
  9768. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9769. this.sipGatewayEnabled = true;
  9770. }
  9771. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9772. };
  9773. // FIXME = we need to show the fact that we're waiting for the focus
  9774. // to the user(or that focus is not available)
  9775. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9776. // Try to use focus user JID from the config
  9777. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9778. // Send create conference IQ
  9779. var iq = this.createConferenceIq();
  9780. var self = this;
  9781. this.connection.sendIQ(
  9782. iq,
  9783. function (result) {
  9784. // Setup config options
  9785. self.parseConfigOptions(result);
  9786. if ('true' === $(result).find('conference').attr('ready')) {
  9787. // Reset both timers
  9788. self.getNextTimeout(true);
  9789. self.getNextErrorTimeout(true);
  9790. // Exec callback
  9791. callback();
  9792. } else {
  9793. var waitMs = self.getNextTimeout();
  9794. logger.info("Waiting for the focus... " + waitMs);
  9795. // Reset error timeout
  9796. self.getNextErrorTimeout(true);
  9797. window.setTimeout(
  9798. function () {
  9799. self.allocateConferenceFocus(callback);
  9800. }, waitMs);
  9801. }
  9802. },
  9803. function (error) {
  9804. // Invalid session ? remove and try again
  9805. // without session ID to get a new one
  9806. var invalidSession
  9807. = $(error).find('>error>session-invalid').length;
  9808. if (invalidSession) {
  9809. logger.info("Session expired! - removing");
  9810. localStorage.removeItem("sessionId");
  9811. }
  9812. if ($(error).find('>error>graceful-shutdown').length) {
  9813. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9814. return;
  9815. }
  9816. // Check for error returned by the reservation system
  9817. var reservationErr = $(error).find('>error>reservation-error');
  9818. if (reservationErr.length) {
  9819. // Trigger error event
  9820. var errorCode = reservationErr.attr('error-code');
  9821. var errorMsg;
  9822. if ($(error).find('>error>text')) {
  9823. errorMsg = $(error).find('>error>text').text();
  9824. }
  9825. self.eventEmitter.emit(
  9826. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9827. return;
  9828. }
  9829. // Not authorized to create new room
  9830. if ($(error).find('>error>not-authorized').length) {
  9831. logger.warn("Unauthorized to start the conference", error);
  9832. var toDomain
  9833. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9834. if (toDomain !==
  9835. this.xmppService.options.hosts.anonymousdomain) {
  9836. //FIXME: "is external" should come either from
  9837. // the focus or config.js
  9838. self.externalAuthEnabled = true;
  9839. }
  9840. self.eventEmitter.emit(
  9841. XMPPEvents.AUTHENTICATION_REQUIRED,
  9842. function () {
  9843. self.allocateConferenceFocus(
  9844. callback);
  9845. });
  9846. return;
  9847. }
  9848. var waitMs = self.getNextErrorTimeout();
  9849. logger.error("Focus error, retry after " + waitMs, error);
  9850. // Show message
  9851. var focusComponent = self.getFocusComponent();
  9852. var retrySec = waitMs / 1000;
  9853. //FIXME: message is duplicated ?
  9854. // Do not show in case of session invalid
  9855. // which means just a retry
  9856. if (!invalidSession) {
  9857. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9858. focusComponent, retrySec);
  9859. }
  9860. // Reset response timeout
  9861. self.getNextTimeout(true);
  9862. window.setTimeout(
  9863. function () {
  9864. self.allocateConferenceFocus(callback);
  9865. }, waitMs);
  9866. }
  9867. );
  9868. };
  9869. Moderator.prototype.authenticate = function () {
  9870. var self = this;
  9871. return new Promise(function (resolve, reject) {
  9872. self.connection.sendIQ(
  9873. self.createConferenceIq(),
  9874. function (result) {
  9875. self.parseSessionId(result);
  9876. resolve();
  9877. }, function (error) {
  9878. var code = $(error).find('>error').attr('code');
  9879. reject(error, code);
  9880. }
  9881. );
  9882. });
  9883. };
  9884. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  9885. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9886. iq.c('login-url', {
  9887. xmlns: 'http://jitsi.org/protocol/focus',
  9888. room: this.roomName,
  9889. 'machine-uid': this.settings.getSettings().uid
  9890. });
  9891. this.connection.sendIQ(
  9892. iq,
  9893. function (result) {
  9894. var url = $(result).find('login-url').attr('url');
  9895. url = url = decodeURIComponent(url);
  9896. if (url) {
  9897. logger.info("Got auth url: " + url);
  9898. urlCallback(url);
  9899. } else {
  9900. logger.error(
  9901. "Failed to get auth url from the focus", result);
  9902. failureCallback(result);
  9903. }
  9904. },
  9905. function (error) {
  9906. logger.error("Get auth url error", error);
  9907. failureCallback(error);
  9908. }
  9909. );
  9910. };
  9911. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  9912. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9913. iq.c('login-url', {
  9914. xmlns: 'http://jitsi.org/protocol/focus',
  9915. room: this.roomName,
  9916. 'machine-uid': this.settings.getSettings().uid,
  9917. popup: true
  9918. });
  9919. this.connection.sendIQ(
  9920. iq,
  9921. function (result) {
  9922. var url = $(result).find('login-url').attr('url');
  9923. url = url = decodeURIComponent(url);
  9924. if (url) {
  9925. logger.info("Got POPUP auth url: " + url);
  9926. urlCallback(url);
  9927. } else {
  9928. logger.error(
  9929. "Failed to get POPUP auth url from the focus", result);
  9930. failureCallback(result);
  9931. }
  9932. },
  9933. function (error) {
  9934. logger.error('Get POPUP auth url error', error);
  9935. failureCallback(error);
  9936. }
  9937. );
  9938. };
  9939. Moderator.prototype.logout = function (callback) {
  9940. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9941. var sessionId = localStorage.getItem('sessionId');
  9942. if (!sessionId) {
  9943. callback();
  9944. return;
  9945. }
  9946. iq.c('logout', {
  9947. xmlns: 'http://jitsi.org/protocol/focus',
  9948. 'session-id': sessionId
  9949. });
  9950. this.connection.sendIQ(
  9951. iq,
  9952. function (result) {
  9953. var logoutUrl = $(result).find('logout').attr('logout-url');
  9954. if (logoutUrl) {
  9955. logoutUrl = decodeURIComponent(logoutUrl);
  9956. }
  9957. logger.info("Log out OK, url: " + logoutUrl, result);
  9958. localStorage.removeItem('sessionId');
  9959. callback(logoutUrl);
  9960. },
  9961. function (error) {
  9962. logger.error("Logout error", error);
  9963. }
  9964. );
  9965. };
  9966. module.exports = Moderator;
  9967. }).call(this,"/modules/xmpp/moderator.js")
  9968. },{"../../service/authentication/AuthenticationEvents":83,"../../service/xmpp/XMPPEvents":87,"../settings/Settings":21,"jitsi-meet-logger":48}],35:[function(require,module,exports){
  9969. (function (__filename){
  9970. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  9971. Toolbar, Util, Promise */
  9972. var XMPPEvents = require("../../service/XMPP/XMPPEvents");
  9973. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9974. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  9975. roomjid) {
  9976. this.eventEmitter = eventEmitter;
  9977. this.connection = connection;
  9978. this.state = "off";
  9979. this.focusMucJid = focusMucJid;
  9980. this.jirecon = jirecon;
  9981. this.url = null;
  9982. this.type = type;
  9983. this._isSupported = ((type === Recording.types.JIBRI)
  9984. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  9985. /**
  9986. * The ID of the jirecon recording session. Jirecon generates it when we
  9987. * initially start recording, and it needs to be used in subsequent requests
  9988. * to jirecon.
  9989. */
  9990. this.jireconRid = null;
  9991. this.roomjid = roomjid;
  9992. }
  9993. Recording.types = {
  9994. COLIBRI: "colibri",
  9995. JIRECON: "jirecon",
  9996. JIBRI: "jibri"
  9997. };
  9998. Recording.prototype.handleJibriPresence = function (jibri) {
  9999. var attributes = jibri.attributes;
  10000. if(!attributes)
  10001. return;
  10002. this._isSupported =
  10003. (attributes.status && attributes.status !== "undefined");
  10004. if(this._isSupported) {
  10005. this.url = attributes.url || null;
  10006. this.state = attributes.status || "off";
  10007. }
  10008. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  10009. };
  10010. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  10011. options) {
  10012. if (state == this.state){
  10013. errCallback(new Error("Invalid state!"));
  10014. }
  10015. options = options || {};
  10016. // FIXME jibri does not accept IQ without 'url' attribute set ?
  10017. var iq = $iq({to: this.focusMucJid, type: 'set'})
  10018. .c('jibri', {
  10019. "xmlns": 'http://jitsi.org/protocol/jibri',
  10020. "action": (state === 'on') ? 'start' : 'stop',
  10021. "streamid": options.streamId,
  10022. "follow-entity": options.followEntity
  10023. }).up();
  10024. logger.log('Set jibri recording: '+state, iq.nodeTree);
  10025. console.log(iq.nodeTree);
  10026. this.connection.sendIQ(
  10027. iq,
  10028. function (result) {
  10029. callback($(result).find('jibri').attr('state'),
  10030. $(result).find('jibri').attr('url'));
  10031. },
  10032. function (error) {
  10033. logger.log('Failed to start recording, error: ', error);
  10034. errCallback(error);
  10035. });
  10036. };
  10037. Recording.prototype.setRecordingJirecon =
  10038. function (state, callback, errCallback, options) {
  10039. if (state == this.state){
  10040. errCallback(new Error("Invalid state!"));
  10041. }
  10042. var iq = $iq({to: this.jirecon, type: 'set'})
  10043. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  10044. action: (state === 'on') ? 'start' : 'stop',
  10045. mucjid: this.roomjid});
  10046. if (state === 'off'){
  10047. iq.attrs({rid: this.jireconRid});
  10048. }
  10049. console.log('Start recording');
  10050. var self = this;
  10051. this.connection.sendIQ(
  10052. iq,
  10053. function (result) {
  10054. // TODO wait for an IQ with the real status, since this is
  10055. // provisional?
  10056. self.jireconRid = $(result).find('recording').attr('rid');
  10057. console.log('Recording ' +
  10058. ((state === 'on') ? 'started' : 'stopped') +
  10059. '(jirecon)' + result);
  10060. self.state = state;
  10061. if (state === 'off'){
  10062. self.jireconRid = null;
  10063. }
  10064. callback(state);
  10065. },
  10066. function (error) {
  10067. console.log('Failed to start recording, error: ', error);
  10068. errCallback(error);
  10069. });
  10070. };
  10071. // Sends a COLIBRI message which enables or disables (according to 'state')
  10072. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  10073. // with the new recording state, according to the IQ.
  10074. Recording.prototype.setRecordingColibri =
  10075. function (state, callback, errCallback, options) {
  10076. var elem = $iq({to: this.focusMucJid, type: 'set'});
  10077. elem.c('conference', {
  10078. xmlns: 'http://jitsi.org/protocol/colibri'
  10079. });
  10080. elem.c('recording', {state: state, token: options.token});
  10081. var self = this;
  10082. this.connection.sendIQ(elem,
  10083. function (result) {
  10084. console.log('Set recording "', state, '". Result:', result);
  10085. var recordingElem = $(result).find('>conference>recording');
  10086. var newState = recordingElem.attr('state');
  10087. self.state = newState;
  10088. callback(newState);
  10089. if (newState === 'pending') {
  10090. self.connection.addHandler(function(iq){
  10091. var state = $(iq).find('recording').attr('state');
  10092. if (state) {
  10093. self.state = newState;
  10094. callback(state);
  10095. }
  10096. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  10097. }
  10098. },
  10099. function (error) {
  10100. console.warn(error);
  10101. errCallback(error);
  10102. }
  10103. );
  10104. };
  10105. Recording.prototype.setRecording =
  10106. function (state, callback, errCallback, options) {
  10107. switch(this.type){
  10108. case Recording.types.JIRECON:
  10109. this.setRecordingJirecon(state, callback, errCallback, options);
  10110. break;
  10111. case Recording.types.COLIBRI:
  10112. this.setRecordingColibri(state, callback, errCallback, options);
  10113. break;
  10114. case Recording.types.JIBRI:
  10115. this.setRecordingJibri(state, callback, errCallback, options);
  10116. break;
  10117. default:
  10118. console.error("Unknown recording type!");
  10119. return;
  10120. }
  10121. };
  10122. /**
  10123. *Starts/stops the recording
  10124. * @param token token for authentication
  10125. * @param statusChangeHandler {function} receives the new status as argument.
  10126. */
  10127. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  10128. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  10129. (!options.streamId && this.type === Recording.types.JIBRI)){
  10130. statusChangeHandler("error", new Error("No token passed!"));
  10131. logger.error("No token passed!");
  10132. return;
  10133. }
  10134. var oldState = this.state;
  10135. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  10136. var self = this;
  10137. this.setRecording(newState,
  10138. function (state, url) {
  10139. logger.log("New recording state: ", state);
  10140. if (state && state !== oldState) {
  10141. self.state = state;
  10142. self.url = url;
  10143. statusChangeHandler(state);
  10144. } else {
  10145. statusChangeHandler("error", new Error("Status not changed!"));
  10146. }
  10147. }, function (error) {
  10148. statusChangeHandler("error", error);
  10149. }, options);
  10150. };
  10151. /**
  10152. * Returns true if the recording is supproted and false if not.
  10153. */
  10154. Recording.prototype.isSupported = function () {
  10155. return this._isSupported;
  10156. };
  10157. /**
  10158. * Returns null if the recording is not supported, "on" if the recording started
  10159. * and "off" if the recording is not started.
  10160. */
  10161. Recording.prototype.getState = function () {
  10162. return this.state;
  10163. };
  10164. /**
  10165. * Returns the url of the recorded video.
  10166. */
  10167. Recording.prototype.getURL = function () {
  10168. return this.url;
  10169. };
  10170. module.exports = Recording;
  10171. }).call(this,"/modules/xmpp/recording.js")
  10172. },{"../../service/XMPP/XMPPEvents":82,"jitsi-meet-logger":48}],36:[function(require,module,exports){
  10173. (function (__filename){
  10174. /* jshint -W117 */
  10175. /* a simple MUC connection plugin
  10176. * can only handle a single MUC room
  10177. */
  10178. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10179. var ChatRoom = require("./ChatRoom");
  10180. module.exports = function(XMPP) {
  10181. Strophe.addConnectionPlugin('emuc', {
  10182. connection: null,
  10183. rooms: {},//map with the rooms
  10184. init: function (conn) {
  10185. this.connection = conn;
  10186. // add handlers (just once)
  10187. this.connection.addHandler(this.onPresence.bind(this), null,
  10188. 'presence', null, null, null, null);
  10189. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  10190. null, 'presence', 'unavailable', null);
  10191. this.connection.addHandler(this.onPresenceError.bind(this), null,
  10192. 'presence', 'error', null);
  10193. this.connection.addHandler(this.onMessage.bind(this), null,
  10194. 'message', null, null);
  10195. this.connection.addHandler(this.onMute.bind(this),
  10196. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  10197. },
  10198. createRoom: function (jid, password, options) {
  10199. var roomJid = Strophe.getBareJidFromJid(jid);
  10200. if (this.rooms[roomJid]) {
  10201. logger.error("You are already in the room!");
  10202. return;
  10203. }
  10204. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  10205. return this.rooms[roomJid];
  10206. },
  10207. doLeave: function (jid) {
  10208. this.rooms[jid].doLeave();
  10209. delete this.rooms[jid];
  10210. },
  10211. onPresence: function (pres) {
  10212. var from = pres.getAttribute('from');
  10213. // What is this for? A workaround for something?
  10214. if (pres.getAttribute('type')) {
  10215. return true;
  10216. }
  10217. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10218. if(!room)
  10219. return;
  10220. // Parse status.
  10221. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  10222. room.createNonAnonymousRoom();
  10223. }
  10224. room.onPresence(pres);
  10225. return true;
  10226. },
  10227. onPresenceUnavailable: function (pres) {
  10228. var from = pres.getAttribute('from');
  10229. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10230. if(!room)
  10231. return;
  10232. room.onPresenceUnavailable(pres, from);
  10233. return true;
  10234. },
  10235. onPresenceError: function (pres) {
  10236. var from = pres.getAttribute('from');
  10237. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10238. if(!room)
  10239. return;
  10240. room.onPresenceError(pres, from);
  10241. return true;
  10242. },
  10243. onMessage: function (msg) {
  10244. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  10245. var from = msg.getAttribute('from');
  10246. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10247. if(!room)
  10248. return;
  10249. room.onMessage(msg, from);
  10250. return true;
  10251. },
  10252. setJingleSession: function (from, session) {
  10253. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10254. if(!room)
  10255. return;
  10256. room.setJingleSession(session);
  10257. },
  10258. onMute: function(iq) {
  10259. var from = iq.getAttribute('from');
  10260. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  10261. if(!room)
  10262. return;
  10263. room.onMute(iq);
  10264. return true;
  10265. }
  10266. });
  10267. };
  10268. }).call(this,"/modules/xmpp/strophe.emuc.js")
  10269. },{"./ChatRoom":26,"jitsi-meet-logger":48}],37:[function(require,module,exports){
  10270. (function (__filename){
  10271. /* jshint -W117 */
  10272. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10273. var JingleSession = require("./JingleSessionPC");
  10274. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10275. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10276. module.exports = function(XMPP, eventEmitter) {
  10277. Strophe.addConnectionPlugin('jingle', {
  10278. connection: null,
  10279. sessions: {},
  10280. jid2session: {},
  10281. ice_config: {iceServers: []},
  10282. media_constraints: {
  10283. mandatory: {
  10284. 'OfferToReceiveAudio': true,
  10285. 'OfferToReceiveVideo': true
  10286. }
  10287. // MozDontOfferDataChannel: true when this is firefox
  10288. },
  10289. init: function (conn) {
  10290. this.connection = conn;
  10291. if (this.connection.disco) {
  10292. // http://xmpp.org/extensions/xep-0167.html#support
  10293. // http://xmpp.org/extensions/xep-0176.html#support
  10294. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  10295. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  10296. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  10297. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  10298. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  10299. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  10300. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  10301. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  10302. || RTCBrowserType.isTemasysPluginUsed()) {
  10303. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  10304. }
  10305. // this is dealt with by SDP O/A so we don't need to announce this
  10306. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  10307. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  10308. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  10309. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  10310. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  10311. }
  10312. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  10313. },
  10314. onJingle: function (iq) {
  10315. var sid = $(iq).find('jingle').attr('sid');
  10316. var action = $(iq).find('jingle').attr('action');
  10317. var fromJid = iq.getAttribute('from');
  10318. // send ack first
  10319. var ack = $iq({type: 'result',
  10320. to: fromJid,
  10321. id: iq.getAttribute('id')
  10322. });
  10323. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  10324. var sess = this.sessions[sid];
  10325. if ('session-initiate' != action) {
  10326. if (sess === null) {
  10327. ack.type = 'error';
  10328. ack.c('error', {type: 'cancel'})
  10329. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10330. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10331. this.connection.send(ack);
  10332. return true;
  10333. }
  10334. // local jid is not checked
  10335. if (fromJid != sess.peerjid) {
  10336. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  10337. ack.type = 'error';
  10338. ack.c('error', {type: 'cancel'})
  10339. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  10340. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  10341. this.connection.send(ack);
  10342. return true;
  10343. }
  10344. } else if (sess !== undefined) {
  10345. // existing session with same session id
  10346. // this might be out-of-order if the sess.peerjid is the same as from
  10347. ack.type = 'error';
  10348. ack.c('error', {type: 'cancel'})
  10349. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  10350. logger.warn('duplicate session id', sid);
  10351. this.connection.send(ack);
  10352. return true;
  10353. }
  10354. // FIXME: check for a defined action
  10355. this.connection.send(ack);
  10356. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  10357. switch (action) {
  10358. case 'session-initiate':
  10359. console.log("(TIME) received session-initiate:\t",
  10360. window.performance.now());
  10361. var startMuted = $(iq).find('jingle>startmuted');
  10362. if (startMuted && startMuted.length > 0) {
  10363. var audioMuted = startMuted.attr("audio");
  10364. var videoMuted = startMuted.attr("video");
  10365. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  10366. audioMuted === "true", videoMuted === "true");
  10367. }
  10368. sess = new JingleSession(
  10369. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  10370. this.connection, XMPP);
  10371. // configure session
  10372. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  10373. this.connection.emuc.setJingleSession(fromBareJid, sess);
  10374. sess.media_constraints = this.media_constraints;
  10375. sess.ice_config = this.ice_config;
  10376. sess.initialize(fromJid, false);
  10377. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  10378. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  10379. sess.setOffer($(iq).find('>jingle'));
  10380. this.sessions[sess.sid] = sess;
  10381. this.jid2session[sess.peerjid] = sess;
  10382. // the callback should either
  10383. // .sendAnswer and .accept
  10384. // or .sendTerminate -- not necessarily synchronous
  10385. sess.sendAnswer();
  10386. sess.accept();
  10387. break;
  10388. case 'session-accept':
  10389. sess.setAnswer($(iq).find('>jingle'));
  10390. sess.accept();
  10391. break;
  10392. case 'session-terminate':
  10393. // If this is not the focus sending the terminate, we have
  10394. // nothing more to do here.
  10395. if (Object.keys(this.sessions).length < 1
  10396. || !(this.sessions[Object.keys(this.sessions)[0]]
  10397. instanceof JingleSession))
  10398. {
  10399. break;
  10400. }
  10401. logger.log('terminating...', sess.sid);
  10402. sess.terminate();
  10403. this.terminate(sess.sid);
  10404. if ($(iq).find('>jingle>reason').length) {
  10405. $(document).trigger('callterminated.jingle', [
  10406. sess.sid,
  10407. sess.peerjid,
  10408. $(iq).find('>jingle>reason>:first')[0].tagName,
  10409. $(iq).find('>jingle>reason>text').text()
  10410. ]);
  10411. } else {
  10412. $(document).trigger('callterminated.jingle',
  10413. [sess.sid, sess.peerjid]);
  10414. }
  10415. break;
  10416. case 'transport-info':
  10417. sess.addIceCandidate($(iq).find('>jingle>content'));
  10418. break;
  10419. case 'session-info':
  10420. var affected;
  10421. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10422. $(document).trigger('ringing.jingle', [sess.sid]);
  10423. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10424. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10425. $(document).trigger('mute.jingle', [sess.sid, affected]);
  10426. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  10427. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  10428. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  10429. }
  10430. break;
  10431. case 'addsource': // FIXME: proprietary, un-jingleish
  10432. case 'source-add': // FIXME: proprietary
  10433. sess.addSource($(iq).find('>jingle>content'));
  10434. break;
  10435. case 'removesource': // FIXME: proprietary, un-jingleish
  10436. case 'source-remove': // FIXME: proprietary
  10437. sess.removeSource($(iq).find('>jingle>content'));
  10438. break;
  10439. default:
  10440. logger.warn('jingle action not implemented', action);
  10441. break;
  10442. }
  10443. return true;
  10444. },
  10445. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  10446. if (sid === null || sid === undefined) {
  10447. for (sid in this.sessions) {
  10448. if (this.sessions[sid].state != 'ended') {
  10449. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10450. this.sessions[sid].terminate();
  10451. }
  10452. delete this.jid2session[this.sessions[sid].peerjid];
  10453. delete this.sessions[sid];
  10454. }
  10455. } else if (this.sessions.hasOwnProperty(sid)) {
  10456. if (this.sessions[sid].state != 'ended') {
  10457. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  10458. this.sessions[sid].terminate();
  10459. }
  10460. delete this.jid2session[this.sessions[sid].peerjid];
  10461. delete this.sessions[sid];
  10462. }
  10463. },
  10464. getStunAndTurnCredentials: function () {
  10465. // get stun and turn configuration from server via xep-0215
  10466. // uses time-limited credentials as described in
  10467. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  10468. //
  10469. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  10470. // for a prosody module which implements this
  10471. //
  10472. // currently, this doesn't work with updateIce and therefore credentials with a long
  10473. // validity have to be fetched before creating the peerconnection
  10474. // TODO: implement refresh via updateIce as described in
  10475. // https://code.google.com/p/webrtc/issues/detail?id=1650
  10476. var self = this;
  10477. this.connection.sendIQ(
  10478. $iq({type: 'get', to: this.connection.domain})
  10479. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  10480. function (res) {
  10481. var iceservers = [];
  10482. $(res).find('>services>service').each(function (idx, el) {
  10483. el = $(el);
  10484. var dict = {};
  10485. var type = el.attr('type');
  10486. switch (type) {
  10487. case 'stun':
  10488. dict.url = 'stun:' + el.attr('host');
  10489. if (el.attr('port')) {
  10490. dict.url += ':' + el.attr('port');
  10491. }
  10492. iceservers.push(dict);
  10493. break;
  10494. case 'turn':
  10495. case 'turns':
  10496. dict.url = type + ':';
  10497. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  10498. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  10499. dict.url += el.attr('username') + '@';
  10500. } else {
  10501. dict.username = el.attr('username'); // only works in M28
  10502. }
  10503. }
  10504. dict.url += el.attr('host');
  10505. if (el.attr('port') && el.attr('port') != '3478') {
  10506. dict.url += ':' + el.attr('port');
  10507. }
  10508. if (el.attr('transport') && el.attr('transport') != 'udp') {
  10509. dict.url += '?transport=' + el.attr('transport');
  10510. }
  10511. if (el.attr('password')) {
  10512. dict.credential = el.attr('password');
  10513. }
  10514. iceservers.push(dict);
  10515. break;
  10516. }
  10517. });
  10518. self.ice_config.iceServers = iceservers;
  10519. },
  10520. function (err) {
  10521. logger.warn('getting turn credentials failed', err);
  10522. logger.warn('is mod_turncredentials or similar installed?');
  10523. }
  10524. );
  10525. // implement push?
  10526. },
  10527. /**
  10528. * Returns the data saved in 'updateLog' in a format to be logged.
  10529. */
  10530. getLog: function () {
  10531. var data = {};
  10532. var self = this;
  10533. Object.keys(this.sessions).forEach(function (sid) {
  10534. var session = self.sessions[sid];
  10535. if (session.peerconnection && session.peerconnection.updateLog) {
  10536. // FIXME: should probably be a .dump call
  10537. data["jingle_" + session.sid] = {
  10538. updateLog: session.peerconnection.updateLog,
  10539. stats: session.peerconnection.stats,
  10540. url: window.location.href
  10541. };
  10542. }
  10543. });
  10544. return data;
  10545. }
  10546. });
  10547. };
  10548. }).call(this,"/modules/xmpp/strophe.jingle.js")
  10549. },{"../../service/xmpp/XMPPEvents":87,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":48}],38:[function(require,module,exports){
  10550. /* global Strophe */
  10551. module.exports = function () {
  10552. Strophe.addConnectionPlugin('logger', {
  10553. // logs raw stanzas and makes them available for download as JSON
  10554. connection: null,
  10555. log: [],
  10556. init: function (conn) {
  10557. this.connection = conn;
  10558. this.connection.rawInput = this.log_incoming.bind(this);
  10559. this.connection.rawOutput = this.log_outgoing.bind(this);
  10560. },
  10561. log_incoming: function (stanza) {
  10562. this.log.push([new Date().getTime(), 'incoming', stanza]);
  10563. },
  10564. log_outgoing: function (stanza) {
  10565. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  10566. }
  10567. });
  10568. };
  10569. },{}],39:[function(require,module,exports){
  10570. (function (__filename){
  10571. /* global $, $iq, Strophe */
  10572. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10573. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10574. /**
  10575. * Ping every 20 sec
  10576. */
  10577. var PING_INTERVAL = 20000;
  10578. /**
  10579. * Ping timeout error after 15 sec of waiting.
  10580. */
  10581. var PING_TIMEOUT = 15000;
  10582. /**
  10583. * Will close the connection after 3 consecutive ping errors.
  10584. */
  10585. var PING_THRESHOLD = 3;
  10586. /**
  10587. * XEP-0199 ping plugin.
  10588. *
  10589. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  10590. */
  10591. module.exports = function (XMPP, eventEmitter) {
  10592. Strophe.addConnectionPlugin('ping', {
  10593. connection: null,
  10594. failedPings: 0,
  10595. /**
  10596. * Initializes the plugin. Method called by Strophe.
  10597. * @param connection Strophe connection instance.
  10598. */
  10599. init: function (connection) {
  10600. this.connection = connection;
  10601. Strophe.addNamespace('PING', "urn:xmpp:ping");
  10602. },
  10603. /**
  10604. * Sends "ping" to given <tt>jid</tt>
  10605. * @param jid the JID to which ping request will be sent.
  10606. * @param success callback called on success.
  10607. * @param error callback called on error.
  10608. * @param timeout ms how long are we going to wait for the response. On
  10609. * timeout <tt>error<//t> callback is called with undefined error
  10610. * argument.
  10611. */
  10612. ping: function (jid, success, error, timeout) {
  10613. var iq = $iq({type: 'get', to: jid});
  10614. iq.c('ping', {xmlns: Strophe.NS.PING});
  10615. this.connection.sendIQ(iq, success, error, timeout);
  10616. },
  10617. /**
  10618. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  10619. * @param jid the JID to be checked for ping support.
  10620. * @param callback function with boolean argument which will be
  10621. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  10622. */
  10623. hasPingSupport: function (jid, callback) {
  10624. this.connection.disco.info(
  10625. jid, null,
  10626. function (result) {
  10627. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  10628. callback(ping.length > 0);
  10629. },
  10630. function (error) {
  10631. logger.error("Ping feature discovery error", error);
  10632. callback(false);
  10633. }
  10634. );
  10635. },
  10636. /**
  10637. * Starts to send ping in given interval to specified remote JID.
  10638. * This plugin supports only one such task and <tt>stopInterval</tt>
  10639. * must be called before starting a new one.
  10640. * @param remoteJid remote JID to which ping requests will be sent to.
  10641. * @param interval task interval in ms.
  10642. */
  10643. startInterval: function (remoteJid, interval) {
  10644. if (this.intervalId) {
  10645. logger.error("Ping task scheduled already");
  10646. return;
  10647. }
  10648. if (!interval)
  10649. interval = PING_INTERVAL;
  10650. var self = this;
  10651. this.intervalId = window.setInterval(function () {
  10652. self.ping(remoteJid,
  10653. function (result) {
  10654. // Ping OK
  10655. self.failedPings = 0;
  10656. },
  10657. function (error) {
  10658. self.failedPings += 1;
  10659. logger.error(
  10660. "Ping " + (error ? "error" : "timeout"), error);
  10661. if (self.failedPings >= PING_THRESHOLD) {
  10662. self.connection.disconnect();
  10663. }
  10664. }, PING_TIMEOUT);
  10665. }, interval);
  10666. logger.info("XMPP pings will be sent every " + interval + " ms");
  10667. },
  10668. /**
  10669. * Stops current "ping" interval task.
  10670. */
  10671. stopInterval: function () {
  10672. if (this.intervalId) {
  10673. window.clearInterval(this.intervalId);
  10674. this.intervalId = null;
  10675. this.failedPings = 0;
  10676. logger.info("Ping interval cleared");
  10677. }
  10678. }
  10679. });
  10680. };
  10681. }).call(this,"/modules/xmpp/strophe.ping.js")
  10682. },{"../../service/xmpp/XMPPEvents":87,"jitsi-meet-logger":48}],40:[function(require,module,exports){
  10683. (function (__filename){
  10684. /* jshint -W117 */
  10685. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10686. module.exports = function() {
  10687. Strophe.addConnectionPlugin('rayo',
  10688. {
  10689. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  10690. connection: null,
  10691. init: function (conn) {
  10692. this.connection = conn;
  10693. if (this.connection.disco) {
  10694. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  10695. }
  10696. this.connection.addHandler(
  10697. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  10698. null, null);
  10699. },
  10700. onRayo: function (iq) {
  10701. logger.info("Rayo IQ", iq);
  10702. },
  10703. dial: function (to, from, roomName, roomPass, focusMucJid) {
  10704. var self = this;
  10705. return new Promise(function (resolve, reject) {
  10706. if(!focusMucJid) {
  10707. reject(new Error("Internal error!"));
  10708. return;
  10709. }
  10710. var req = $iq(
  10711. {
  10712. type: 'set',
  10713. to: focusMucJid
  10714. }
  10715. );
  10716. req.c('dial',
  10717. {
  10718. xmlns: self.RAYO_XMLNS,
  10719. to: to,
  10720. from: from
  10721. });
  10722. req.c('header',
  10723. {
  10724. name: 'JvbRoomName',
  10725. value: roomName
  10726. }).up();
  10727. if (roomPass !== null && roomPass.length) {
  10728. req.c('header',
  10729. {
  10730. name: 'JvbRoomPassword',
  10731. value: roomPass
  10732. }).up();
  10733. }
  10734. self.connection.sendIQ(
  10735. req,
  10736. function (result) {
  10737. logger.info('Dial result ', result);
  10738. var resource = $(result).find('ref').attr('uri');
  10739. self.call_resource =
  10740. resource.substr('xmpp:'.length);
  10741. logger.info(
  10742. "Received call resource: " +
  10743. self.call_resource);
  10744. resolve();
  10745. },
  10746. function (error) {
  10747. logger.info('Dial error ', error);
  10748. reject(error);
  10749. }
  10750. );
  10751. });
  10752. },
  10753. hangup: function () {
  10754. var self = this;
  10755. return new Promise(function (resolve, reject) {
  10756. if (!self.call_resource) {
  10757. reject(new Error("No call in progress"));
  10758. logger.warn("No call in progress");
  10759. return;
  10760. }
  10761. var req = $iq(
  10762. {
  10763. type: 'set',
  10764. to: self.call_resource
  10765. }
  10766. );
  10767. req.c('hangup',
  10768. {
  10769. xmlns: self.RAYO_XMLNS
  10770. });
  10771. self.connection.sendIQ(
  10772. req,
  10773. function (result) {
  10774. logger.info('Hangup result ', result);
  10775. self.call_resource = null;
  10776. resolve();
  10777. },
  10778. function (error) {
  10779. logger.info('Hangup error ', error);
  10780. self.call_resource = null;
  10781. reject(new Error('Hangup error '));
  10782. }
  10783. );
  10784. });
  10785. }
  10786. }
  10787. );
  10788. };
  10789. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10790. },{"jitsi-meet-logger":48}],41:[function(require,module,exports){
  10791. (function (__filename){
  10792. /* global Strophe */
  10793. /**
  10794. * Strophe logger implementation. Logs from level WARN and above.
  10795. */
  10796. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10797. module.exports = function () {
  10798. Strophe.log = function (level, msg) {
  10799. switch (level) {
  10800. case Strophe.LogLevel.WARN:
  10801. logger.warn("Strophe: " + msg);
  10802. break;
  10803. case Strophe.LogLevel.ERROR:
  10804. case Strophe.LogLevel.FATAL:
  10805. logger.error("Strophe: " + msg);
  10806. break;
  10807. }
  10808. };
  10809. Strophe.getStatusString = function (status) {
  10810. switch (status) {
  10811. case Strophe.Status.ERROR:
  10812. return "ERROR";
  10813. case Strophe.Status.CONNECTING:
  10814. return "CONNECTING";
  10815. case Strophe.Status.CONNFAIL:
  10816. return "CONNFAIL";
  10817. case Strophe.Status.AUTHENTICATING:
  10818. return "AUTHENTICATING";
  10819. case Strophe.Status.AUTHFAIL:
  10820. return "AUTHFAIL";
  10821. case Strophe.Status.CONNECTED:
  10822. return "CONNECTED";
  10823. case Strophe.Status.DISCONNECTED:
  10824. return "DISCONNECTED";
  10825. case Strophe.Status.DISCONNECTING:
  10826. return "DISCONNECTING";
  10827. case Strophe.Status.ATTACHED:
  10828. return "ATTACHED";
  10829. default:
  10830. return "unknown";
  10831. }
  10832. };
  10833. };
  10834. }).call(this,"/modules/xmpp/strophe.util.js")
  10835. },{"jitsi-meet-logger":48}],42:[function(require,module,exports){
  10836. (function (__filename){
  10837. /* global $, APP, config, Strophe*/
  10838. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10839. var EventEmitter = require("events");
  10840. var Pako = require("pako");
  10841. var RTCEvents = require("../../service/RTC/RTCEvents");
  10842. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10843. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  10844. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10845. var RTC = require("../RTC/RTC");
  10846. var authenticatedUser = false;
  10847. function createConnection(bosh) {
  10848. bosh = bosh || '/http-bind';
  10849. // Append token as URL param
  10850. if (this.token) {
  10851. bosh += bosh.indexOf('?') == -1 ?
  10852. '?token=' + this.token : '&token=' + this.token;
  10853. }
  10854. return new Strophe.Connection(bosh);
  10855. };
  10856. //!!!!!!!!!! FIXME: ...
  10857. function initStrophePlugins(XMPP)
  10858. {
  10859. require("./strophe.emuc")(XMPP);
  10860. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  10861. // require("./strophe.moderate")(XMPP, eventEmitter);
  10862. require("./strophe.util")();
  10863. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  10864. require("./strophe.rayo")();
  10865. require("./strophe.logger")();
  10866. }
  10867. //!!!!!!!!!! FIXME: ...
  10868. ///**
  10869. // * If given <tt>localStream</tt> is video one this method will advertise it's
  10870. // * video type in MUC presence.
  10871. // * @param localStream new or modified <tt>LocalStream</tt>.
  10872. // */
  10873. //function broadcastLocalVideoType(localStream) {
  10874. // if (localStream.videoType)
  10875. // XMPP.addToPresence('videoType', localStream.videoType);
  10876. //}
  10877. //
  10878. //function registerListeners() {
  10879. // RTC.addStreamListener(
  10880. // broadcastLocalVideoType,
  10881. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  10882. // );
  10883. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  10884. // XMPP.addToPresence("devices", devices);
  10885. // });
  10886. //}
  10887. function XMPP(options) {
  10888. this.eventEmitter = new EventEmitter();
  10889. this.connection = null;
  10890. this.disconnectInProgress = false;
  10891. this.forceMuted = false;
  10892. this.options = options;
  10893. initStrophePlugins(this);
  10894. // registerListeners();
  10895. this.connection = createConnection(options.bosh);
  10896. }
  10897. XMPP.prototype.getConnection = function(){ return connection; };
  10898. XMPP.prototype._connect = function (jid, password) {
  10899. var self = this;
  10900. // connection.connect() starts the connection process.
  10901. //
  10902. // As the connection process proceeds, the user supplied callback will
  10903. // be triggered multiple times with status updates. The callback should
  10904. // take two arguments - the status code and the error condition.
  10905. //
  10906. // The status code will be one of the values in the Strophe.Status
  10907. // constants. The error condition will be one of the conditions defined
  10908. // in RFC 3920 or the condition ‘strophe-parsererror’.
  10909. //
  10910. // The Parameters wait, hold and route are optional and only relevant
  10911. // for BOSH connections. Please see XEP 124 for a more detailed
  10912. // explanation of the optional parameters.
  10913. //
  10914. // Connection status constants for use by the connection handler
  10915. // callback.
  10916. //
  10917. // Status.ERROR - An error has occurred (websockets specific)
  10918. // Status.CONNECTING - The connection is currently being made
  10919. // Status.CONNFAIL - The connection attempt failed
  10920. // Status.AUTHENTICATING - The connection is authenticating
  10921. // Status.AUTHFAIL - The authentication attempt failed
  10922. // Status.CONNECTED - The connection has succeeded
  10923. // Status.DISCONNECTED - The connection has been terminated
  10924. // Status.DISCONNECTING - The connection is currently being terminated
  10925. // Status.ATTACHED - The connection has been attached
  10926. var anonymousConnectionFailed = false;
  10927. var connectionFailed = false;
  10928. var lastErrorMsg;
  10929. this.connection.connect(jid, password, function (status, msg) {
  10930. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  10931. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  10932. if (status === Strophe.Status.CONNECTED) {
  10933. if (self.options.useStunTurn) {
  10934. self.connection.jingle.getStunAndTurnCredentials();
  10935. }
  10936. logger.info("My Jabber ID: " + self.connection.jid);
  10937. // Schedule ping ?
  10938. var pingJid = self.connection.domain;
  10939. self.connection.ping.hasPingSupport(
  10940. pingJid,
  10941. function (hasPing) {
  10942. if (hasPing)
  10943. self.connection.ping.startInterval(pingJid);
  10944. else
  10945. logger.warn("Ping NOT supported by " + pingJid);
  10946. }
  10947. );
  10948. if (password)
  10949. authenticatedUser = true;
  10950. if (self.connection && self.connection.connected &&
  10951. Strophe.getResourceFromJid(self.connection.jid)) {
  10952. // .connected is true while connecting?
  10953. // self.connection.send($pres());
  10954. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  10955. Strophe.getResourceFromJid(self.connection.jid));
  10956. }
  10957. } else if (status === Strophe.Status.CONNFAIL) {
  10958. if (msg === 'x-strophe-bad-non-anon-jid') {
  10959. anonymousConnectionFailed = true;
  10960. }
  10961. else
  10962. {
  10963. connectionFailed = true;
  10964. }
  10965. lastErrorMsg = msg;
  10966. } else if (status === Strophe.Status.DISCONNECTED) {
  10967. // Stop ping interval
  10968. self.connection.ping.stopInterval();
  10969. self.disconnectInProgress = false;
  10970. if (anonymousConnectionFailed) {
  10971. // prompt user for username and password
  10972. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10973. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10974. } else if(connectionFailed) {
  10975. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10976. JitsiConnectionErrors.OTHER_ERROR,
  10977. msg ? msg : lastErrorMsg);
  10978. } else {
  10979. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  10980. msg ? msg : lastErrorMsg);
  10981. }
  10982. } else if (status === Strophe.Status.AUTHFAIL) {
  10983. // wrong password or username, prompt user
  10984. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10985. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10986. }
  10987. });
  10988. }
  10989. XMPP.prototype.connect = function (jid, password) {
  10990. if(!jid) {
  10991. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10992. // Force authenticated domain if room is appended with '?login=true'
  10993. if (this.options.hosts.anonymousdomain &&
  10994. window.location.search.indexOf("login=true") !== -1) {
  10995. configDomain = this.options.hosts.domain;
  10996. }
  10997. jid = configDomain || window.location.hostname;
  10998. }
  10999. return this._connect(jid, password);
  11000. };
  11001. XMPP.prototype.createRoom = function (roomName, options) {
  11002. var roomjid = roomName + '@' + this.options.hosts.muc;
  11003. if (options.useNicks) {
  11004. if (options.nick) {
  11005. roomjid += '/' + options.nick;
  11006. } else {
  11007. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  11008. }
  11009. } else {
  11010. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  11011. if(!authenticatedUser)
  11012. tmpJid = tmpJid.substr(0, 8);
  11013. roomjid += '/' + tmpJid;
  11014. }
  11015. return this.connection.emuc.createRoom(roomjid, null, options);
  11016. }
  11017. XMPP.prototype.addListener = function(type, listener) {
  11018. this.eventEmitter.on(type, listener);
  11019. };
  11020. XMPP.prototype.removeListener = function (type, listener) {
  11021. this.eventEmitter.removeListener(type, listener);
  11022. };
  11023. //FIXME: this should work with the room
  11024. XMPP.prototype.leaveRoom = function (jid) {
  11025. var handler = this.connection.jingle.jid2session[jid];
  11026. if (handler && handler.peerconnection) {
  11027. // FIXME: probably removing streams is not required and close() should
  11028. // be enough
  11029. if (RTC.localAudio) {
  11030. handler.peerconnection.removeStream(
  11031. RTC.localAudio.getOriginalStream(), true);
  11032. }
  11033. if (RTC.localVideo) {
  11034. handler.peerconnection.removeStream(
  11035. RTC.localVideo.getOriginalStream(), true);
  11036. }
  11037. handler.peerconnection.close();
  11038. }
  11039. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  11040. this.connection.emuc.doLeave(jid);
  11041. };
  11042. /**
  11043. * Sends 'data' as a log message to the focus. Returns true iff a message
  11044. * was sent.
  11045. * @param data
  11046. * @returns {boolean} true iff a message was sent.
  11047. */
  11048. XMPP.prototype.sendLogs = function (data) {
  11049. if(!this.connection.emuc.focusMucJid)
  11050. return false;
  11051. var deflate = true;
  11052. var content = JSON.stringify(data);
  11053. if (deflate) {
  11054. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  11055. }
  11056. content = Base64.encode(content);
  11057. // XEP-0337-ish
  11058. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  11059. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  11060. id: 'PeerConnectionStats'});
  11061. message.c('message').t(content).up();
  11062. if (deflate) {
  11063. message.c('tag', {name: "deflated", value: "true"}).up();
  11064. }
  11065. message.up();
  11066. this.connection.send(message);
  11067. return true;
  11068. };
  11069. // Gets the logs from strophe.jingle.
  11070. XMPP.prototype.getJingleLog = function () {
  11071. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  11072. };
  11073. // Gets the logs from strophe.
  11074. XMPP.prototype.getXmppLog = function () {
  11075. return this.connection.logger ? this.connection.logger.log : null;
  11076. };
  11077. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  11078. this.connection.rayo.dial(to, from, roomName,roomPass);
  11079. };
  11080. XMPP.prototype.setMute = function (jid, mute) {
  11081. this.connection.moderate.setMute(jid, mute);
  11082. };
  11083. XMPP.prototype.eject = function (jid) {
  11084. this.connection.moderate.eject(jid);
  11085. };
  11086. XMPP.prototype.getSessions = function () {
  11087. return this.connection.jingle.sessions;
  11088. };
  11089. XMPP.prototype.disconnect = function () {
  11090. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  11091. {
  11092. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  11093. return;
  11094. }
  11095. this.disconnectInProgress = true;
  11096. this.connection.disconnect();
  11097. };
  11098. /**
  11099. * Gets the SSRC of local media stream.
  11100. * @param mediaType the media type that tells whether we want to get
  11101. * the SSRC of local audio or video stream.
  11102. * @returns {*} the SSRC number for local media stream or <tt>null</tt> if
  11103. * not available.
  11104. */
  11105. XMPP.prototype.getLocalSSRC = function (mediaType) {
  11106. if (this.connection.jingle.activecall &&
  11107. this.connection.jingle.activecall.peerconnection) {
  11108. return this.connection.jingle.activecall.getLocalSSRC(mediaType);
  11109. } else {
  11110. return null;
  11111. }
  11112. };
  11113. module.exports = XMPP;
  11114. }).call(this,"/modules/xmpp/xmpp.js")
  11115. },{"../../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){
  11116. (function (process){
  11117. /*!
  11118. * async
  11119. * https://github.com/caolan/async
  11120. *
  11121. * Copyright 2010-2014 Caolan McMahon
  11122. * Released under the MIT license
  11123. */
  11124. /*jshint onevar: false, indent:4 */
  11125. /*global setImmediate: false, setTimeout: false, console: false */
  11126. (function () {
  11127. var async = {};
  11128. // global on the server, window in the browser
  11129. var root, previous_async;
  11130. root = this;
  11131. if (root != null) {
  11132. previous_async = root.async;
  11133. }
  11134. async.noConflict = function () {
  11135. root.async = previous_async;
  11136. return async;
  11137. };
  11138. function only_once(fn) {
  11139. var called = false;
  11140. return function() {
  11141. if (called) throw new Error("Callback was already called.");
  11142. called = true;
  11143. fn.apply(root, arguments);
  11144. }
  11145. }
  11146. //// cross-browser compatiblity functions ////
  11147. var _toString = Object.prototype.toString;
  11148. var _isArray = Array.isArray || function (obj) {
  11149. return _toString.call(obj) === '[object Array]';
  11150. };
  11151. var _each = function (arr, iterator) {
  11152. if (arr.forEach) {
  11153. return arr.forEach(iterator);
  11154. }
  11155. for (var i = 0; i < arr.length; i += 1) {
  11156. iterator(arr[i], i, arr);
  11157. }
  11158. };
  11159. var _map = function (arr, iterator) {
  11160. if (arr.map) {
  11161. return arr.map(iterator);
  11162. }
  11163. var results = [];
  11164. _each(arr, function (x, i, a) {
  11165. results.push(iterator(x, i, a));
  11166. });
  11167. return results;
  11168. };
  11169. var _reduce = function (arr, iterator, memo) {
  11170. if (arr.reduce) {
  11171. return arr.reduce(iterator, memo);
  11172. }
  11173. _each(arr, function (x, i, a) {
  11174. memo = iterator(memo, x, i, a);
  11175. });
  11176. return memo;
  11177. };
  11178. var _keys = function (obj) {
  11179. if (Object.keys) {
  11180. return Object.keys(obj);
  11181. }
  11182. var keys = [];
  11183. for (var k in obj) {
  11184. if (obj.hasOwnProperty(k)) {
  11185. keys.push(k);
  11186. }
  11187. }
  11188. return keys;
  11189. };
  11190. //// exported async module functions ////
  11191. //// nextTick implementation with browser-compatible fallback ////
  11192. if (typeof process === 'undefined' || !(process.nextTick)) {
  11193. if (typeof setImmediate === 'function') {
  11194. async.nextTick = function (fn) {
  11195. // not a direct alias for IE10 compatibility
  11196. setImmediate(fn);
  11197. };
  11198. async.setImmediate = async.nextTick;
  11199. }
  11200. else {
  11201. async.nextTick = function (fn) {
  11202. setTimeout(fn, 0);
  11203. };
  11204. async.setImmediate = async.nextTick;
  11205. }
  11206. }
  11207. else {
  11208. async.nextTick = process.nextTick;
  11209. if (typeof setImmediate !== 'undefined') {
  11210. async.setImmediate = function (fn) {
  11211. // not a direct alias for IE10 compatibility
  11212. setImmediate(fn);
  11213. };
  11214. }
  11215. else {
  11216. async.setImmediate = async.nextTick;
  11217. }
  11218. }
  11219. async.each = function (arr, iterator, callback) {
  11220. callback = callback || function () {};
  11221. if (!arr.length) {
  11222. return callback();
  11223. }
  11224. var completed = 0;
  11225. _each(arr, function (x) {
  11226. iterator(x, only_once(done) );
  11227. });
  11228. function done(err) {
  11229. if (err) {
  11230. callback(err);
  11231. callback = function () {};
  11232. }
  11233. else {
  11234. completed += 1;
  11235. if (completed >= arr.length) {
  11236. callback();
  11237. }
  11238. }
  11239. }
  11240. };
  11241. async.forEach = async.each;
  11242. async.eachSeries = function (arr, iterator, callback) {
  11243. callback = callback || function () {};
  11244. if (!arr.length) {
  11245. return callback();
  11246. }
  11247. var completed = 0;
  11248. var iterate = function () {
  11249. iterator(arr[completed], function (err) {
  11250. if (err) {
  11251. callback(err);
  11252. callback = function () {};
  11253. }
  11254. else {
  11255. completed += 1;
  11256. if (completed >= arr.length) {
  11257. callback();
  11258. }
  11259. else {
  11260. iterate();
  11261. }
  11262. }
  11263. });
  11264. };
  11265. iterate();
  11266. };
  11267. async.forEachSeries = async.eachSeries;
  11268. async.eachLimit = function (arr, limit, iterator, callback) {
  11269. var fn = _eachLimit(limit);
  11270. fn.apply(null, [arr, iterator, callback]);
  11271. };
  11272. async.forEachLimit = async.eachLimit;
  11273. var _eachLimit = function (limit) {
  11274. return function (arr, iterator, callback) {
  11275. callback = callback || function () {};
  11276. if (!arr.length || limit <= 0) {
  11277. return callback();
  11278. }
  11279. var completed = 0;
  11280. var started = 0;
  11281. var running = 0;
  11282. (function replenish () {
  11283. if (completed >= arr.length) {
  11284. return callback();
  11285. }
  11286. while (running < limit && started < arr.length) {
  11287. started += 1;
  11288. running += 1;
  11289. iterator(arr[started - 1], function (err) {
  11290. if (err) {
  11291. callback(err);
  11292. callback = function () {};
  11293. }
  11294. else {
  11295. completed += 1;
  11296. running -= 1;
  11297. if (completed >= arr.length) {
  11298. callback();
  11299. }
  11300. else {
  11301. replenish();
  11302. }
  11303. }
  11304. });
  11305. }
  11306. })();
  11307. };
  11308. };
  11309. var doParallel = function (fn) {
  11310. return function () {
  11311. var args = Array.prototype.slice.call(arguments);
  11312. return fn.apply(null, [async.each].concat(args));
  11313. };
  11314. };
  11315. var doParallelLimit = function(limit, fn) {
  11316. return function () {
  11317. var args = Array.prototype.slice.call(arguments);
  11318. return fn.apply(null, [_eachLimit(limit)].concat(args));
  11319. };
  11320. };
  11321. var doSeries = function (fn) {
  11322. return function () {
  11323. var args = Array.prototype.slice.call(arguments);
  11324. return fn.apply(null, [async.eachSeries].concat(args));
  11325. };
  11326. };
  11327. var _asyncMap = function (eachfn, arr, iterator, callback) {
  11328. arr = _map(arr, function (x, i) {
  11329. return {index: i, value: x};
  11330. });
  11331. if (!callback) {
  11332. eachfn(arr, function (x, callback) {
  11333. iterator(x.value, function (err) {
  11334. callback(err);
  11335. });
  11336. });
  11337. } else {
  11338. var results = [];
  11339. eachfn(arr, function (x, callback) {
  11340. iterator(x.value, function (err, v) {
  11341. results[x.index] = v;
  11342. callback(err);
  11343. });
  11344. }, function (err) {
  11345. callback(err, results);
  11346. });
  11347. }
  11348. };
  11349. async.map = doParallel(_asyncMap);
  11350. async.mapSeries = doSeries(_asyncMap);
  11351. async.mapLimit = function (arr, limit, iterator, callback) {
  11352. return _mapLimit(limit)(arr, iterator, callback);
  11353. };
  11354. var _mapLimit = function(limit) {
  11355. return doParallelLimit(limit, _asyncMap);
  11356. };
  11357. // reduce only has a series version, as doing reduce in parallel won't
  11358. // work in many situations.
  11359. async.reduce = function (arr, memo, iterator, callback) {
  11360. async.eachSeries(arr, function (x, callback) {
  11361. iterator(memo, x, function (err, v) {
  11362. memo = v;
  11363. callback(err);
  11364. });
  11365. }, function (err) {
  11366. callback(err, memo);
  11367. });
  11368. };
  11369. // inject alias
  11370. async.inject = async.reduce;
  11371. // foldl alias
  11372. async.foldl = async.reduce;
  11373. async.reduceRight = function (arr, memo, iterator, callback) {
  11374. var reversed = _map(arr, function (x) {
  11375. return x;
  11376. }).reverse();
  11377. async.reduce(reversed, memo, iterator, callback);
  11378. };
  11379. // foldr alias
  11380. async.foldr = async.reduceRight;
  11381. var _filter = function (eachfn, arr, iterator, callback) {
  11382. var results = [];
  11383. arr = _map(arr, function (x, i) {
  11384. return {index: i, value: x};
  11385. });
  11386. eachfn(arr, function (x, callback) {
  11387. iterator(x.value, function (v) {
  11388. if (v) {
  11389. results.push(x);
  11390. }
  11391. callback();
  11392. });
  11393. }, function (err) {
  11394. callback(_map(results.sort(function (a, b) {
  11395. return a.index - b.index;
  11396. }), function (x) {
  11397. return x.value;
  11398. }));
  11399. });
  11400. };
  11401. async.filter = doParallel(_filter);
  11402. async.filterSeries = doSeries(_filter);
  11403. // select alias
  11404. async.select = async.filter;
  11405. async.selectSeries = async.filterSeries;
  11406. var _reject = function (eachfn, arr, iterator, callback) {
  11407. var results = [];
  11408. arr = _map(arr, function (x, i) {
  11409. return {index: i, value: x};
  11410. });
  11411. eachfn(arr, function (x, callback) {
  11412. iterator(x.value, function (v) {
  11413. if (!v) {
  11414. results.push(x);
  11415. }
  11416. callback();
  11417. });
  11418. }, function (err) {
  11419. callback(_map(results.sort(function (a, b) {
  11420. return a.index - b.index;
  11421. }), function (x) {
  11422. return x.value;
  11423. }));
  11424. });
  11425. };
  11426. async.reject = doParallel(_reject);
  11427. async.rejectSeries = doSeries(_reject);
  11428. var _detect = function (eachfn, arr, iterator, main_callback) {
  11429. eachfn(arr, function (x, callback) {
  11430. iterator(x, function (result) {
  11431. if (result) {
  11432. main_callback(x);
  11433. main_callback = function () {};
  11434. }
  11435. else {
  11436. callback();
  11437. }
  11438. });
  11439. }, function (err) {
  11440. main_callback();
  11441. });
  11442. };
  11443. async.detect = doParallel(_detect);
  11444. async.detectSeries = doSeries(_detect);
  11445. async.some = function (arr, iterator, main_callback) {
  11446. async.each(arr, function (x, callback) {
  11447. iterator(x, function (v) {
  11448. if (v) {
  11449. main_callback(true);
  11450. main_callback = function () {};
  11451. }
  11452. callback();
  11453. });
  11454. }, function (err) {
  11455. main_callback(false);
  11456. });
  11457. };
  11458. // any alias
  11459. async.any = async.some;
  11460. async.every = function (arr, iterator, main_callback) {
  11461. async.each(arr, function (x, callback) {
  11462. iterator(x, function (v) {
  11463. if (!v) {
  11464. main_callback(false);
  11465. main_callback = function () {};
  11466. }
  11467. callback();
  11468. });
  11469. }, function (err) {
  11470. main_callback(true);
  11471. });
  11472. };
  11473. // all alias
  11474. async.all = async.every;
  11475. async.sortBy = function (arr, iterator, callback) {
  11476. async.map(arr, function (x, callback) {
  11477. iterator(x, function (err, criteria) {
  11478. if (err) {
  11479. callback(err);
  11480. }
  11481. else {
  11482. callback(null, {value: x, criteria: criteria});
  11483. }
  11484. });
  11485. }, function (err, results) {
  11486. if (err) {
  11487. return callback(err);
  11488. }
  11489. else {
  11490. var fn = function (left, right) {
  11491. var a = left.criteria, b = right.criteria;
  11492. return a < b ? -1 : a > b ? 1 : 0;
  11493. };
  11494. callback(null, _map(results.sort(fn), function (x) {
  11495. return x.value;
  11496. }));
  11497. }
  11498. });
  11499. };
  11500. async.auto = function (tasks, callback) {
  11501. callback = callback || function () {};
  11502. var keys = _keys(tasks);
  11503. var remainingTasks = keys.length
  11504. if (!remainingTasks) {
  11505. return callback();
  11506. }
  11507. var results = {};
  11508. var listeners = [];
  11509. var addListener = function (fn) {
  11510. listeners.unshift(fn);
  11511. };
  11512. var removeListener = function (fn) {
  11513. for (var i = 0; i < listeners.length; i += 1) {
  11514. if (listeners[i] === fn) {
  11515. listeners.splice(i, 1);
  11516. return;
  11517. }
  11518. }
  11519. };
  11520. var taskComplete = function () {
  11521. remainingTasks--
  11522. _each(listeners.slice(0), function (fn) {
  11523. fn();
  11524. });
  11525. };
  11526. addListener(function () {
  11527. if (!remainingTasks) {
  11528. var theCallback = callback;
  11529. // prevent final callback from calling itself if it errors
  11530. callback = function () {};
  11531. theCallback(null, results);
  11532. }
  11533. });
  11534. _each(keys, function (k) {
  11535. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  11536. var taskCallback = function (err) {
  11537. var args = Array.prototype.slice.call(arguments, 1);
  11538. if (args.length <= 1) {
  11539. args = args[0];
  11540. }
  11541. if (err) {
  11542. var safeResults = {};
  11543. _each(_keys(results), function(rkey) {
  11544. safeResults[rkey] = results[rkey];
  11545. });
  11546. safeResults[k] = args;
  11547. callback(err, safeResults);
  11548. // stop subsequent errors hitting callback multiple times
  11549. callback = function () {};
  11550. }
  11551. else {
  11552. results[k] = args;
  11553. async.setImmediate(taskComplete);
  11554. }
  11555. };
  11556. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  11557. var ready = function () {
  11558. return _reduce(requires, function (a, x) {
  11559. return (a && results.hasOwnProperty(x));
  11560. }, true) && !results.hasOwnProperty(k);
  11561. };
  11562. if (ready()) {
  11563. task[task.length - 1](taskCallback, results);
  11564. }
  11565. else {
  11566. var listener = function () {
  11567. if (ready()) {
  11568. removeListener(listener);
  11569. task[task.length - 1](taskCallback, results);
  11570. }
  11571. };
  11572. addListener(listener);
  11573. }
  11574. });
  11575. };
  11576. async.retry = function(times, task, callback) {
  11577. var DEFAULT_TIMES = 5;
  11578. var attempts = [];
  11579. // Use defaults if times not passed
  11580. if (typeof times === 'function') {
  11581. callback = task;
  11582. task = times;
  11583. times = DEFAULT_TIMES;
  11584. }
  11585. // Make sure times is a number
  11586. times = parseInt(times, 10) || DEFAULT_TIMES;
  11587. var wrappedTask = function(wrappedCallback, wrappedResults) {
  11588. var retryAttempt = function(task, finalAttempt) {
  11589. return function(seriesCallback) {
  11590. task(function(err, result){
  11591. seriesCallback(!err || finalAttempt, {err: err, result: result});
  11592. }, wrappedResults);
  11593. };
  11594. };
  11595. while (times) {
  11596. attempts.push(retryAttempt(task, !(times-=1)));
  11597. }
  11598. async.series(attempts, function(done, data){
  11599. data = data[data.length - 1];
  11600. (wrappedCallback || callback)(data.err, data.result);
  11601. });
  11602. }
  11603. // If a callback is passed, run this as a controll flow
  11604. return callback ? wrappedTask() : wrappedTask
  11605. };
  11606. async.waterfall = function (tasks, callback) {
  11607. callback = callback || function () {};
  11608. if (!_isArray(tasks)) {
  11609. var err = new Error('First argument to waterfall must be an array of functions');
  11610. return callback(err);
  11611. }
  11612. if (!tasks.length) {
  11613. return callback();
  11614. }
  11615. var wrapIterator = function (iterator) {
  11616. return function (err) {
  11617. if (err) {
  11618. callback.apply(null, arguments);
  11619. callback = function () {};
  11620. }
  11621. else {
  11622. var args = Array.prototype.slice.call(arguments, 1);
  11623. var next = iterator.next();
  11624. if (next) {
  11625. args.push(wrapIterator(next));
  11626. }
  11627. else {
  11628. args.push(callback);
  11629. }
  11630. async.setImmediate(function () {
  11631. iterator.apply(null, args);
  11632. });
  11633. }
  11634. };
  11635. };
  11636. wrapIterator(async.iterator(tasks))();
  11637. };
  11638. var _parallel = function(eachfn, tasks, callback) {
  11639. callback = callback || function () {};
  11640. if (_isArray(tasks)) {
  11641. eachfn.map(tasks, function (fn, callback) {
  11642. if (fn) {
  11643. fn(function (err) {
  11644. var args = Array.prototype.slice.call(arguments, 1);
  11645. if (args.length <= 1) {
  11646. args = args[0];
  11647. }
  11648. callback.call(null, err, args);
  11649. });
  11650. }
  11651. }, callback);
  11652. }
  11653. else {
  11654. var results = {};
  11655. eachfn.each(_keys(tasks), function (k, callback) {
  11656. tasks[k](function (err) {
  11657. var args = Array.prototype.slice.call(arguments, 1);
  11658. if (args.length <= 1) {
  11659. args = args[0];
  11660. }
  11661. results[k] = args;
  11662. callback(err);
  11663. });
  11664. }, function (err) {
  11665. callback(err, results);
  11666. });
  11667. }
  11668. };
  11669. async.parallel = function (tasks, callback) {
  11670. _parallel({ map: async.map, each: async.each }, tasks, callback);
  11671. };
  11672. async.parallelLimit = function(tasks, limit, callback) {
  11673. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  11674. };
  11675. async.series = function (tasks, callback) {
  11676. callback = callback || function () {};
  11677. if (_isArray(tasks)) {
  11678. async.mapSeries(tasks, function (fn, callback) {
  11679. if (fn) {
  11680. fn(function (err) {
  11681. var args = Array.prototype.slice.call(arguments, 1);
  11682. if (args.length <= 1) {
  11683. args = args[0];
  11684. }
  11685. callback.call(null, err, args);
  11686. });
  11687. }
  11688. }, callback);
  11689. }
  11690. else {
  11691. var results = {};
  11692. async.eachSeries(_keys(tasks), function (k, callback) {
  11693. tasks[k](function (err) {
  11694. var args = Array.prototype.slice.call(arguments, 1);
  11695. if (args.length <= 1) {
  11696. args = args[0];
  11697. }
  11698. results[k] = args;
  11699. callback(err);
  11700. });
  11701. }, function (err) {
  11702. callback(err, results);
  11703. });
  11704. }
  11705. };
  11706. async.iterator = function (tasks) {
  11707. var makeCallback = function (index) {
  11708. var fn = function () {
  11709. if (tasks.length) {
  11710. tasks[index].apply(null, arguments);
  11711. }
  11712. return fn.next();
  11713. };
  11714. fn.next = function () {
  11715. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  11716. };
  11717. return fn;
  11718. };
  11719. return makeCallback(0);
  11720. };
  11721. async.apply = function (fn) {
  11722. var args = Array.prototype.slice.call(arguments, 1);
  11723. return function () {
  11724. return fn.apply(
  11725. null, args.concat(Array.prototype.slice.call(arguments))
  11726. );
  11727. };
  11728. };
  11729. var _concat = function (eachfn, arr, fn, callback) {
  11730. var r = [];
  11731. eachfn(arr, function (x, cb) {
  11732. fn(x, function (err, y) {
  11733. r = r.concat(y || []);
  11734. cb(err);
  11735. });
  11736. }, function (err) {
  11737. callback(err, r);
  11738. });
  11739. };
  11740. async.concat = doParallel(_concat);
  11741. async.concatSeries = doSeries(_concat);
  11742. async.whilst = function (test, iterator, callback) {
  11743. if (test()) {
  11744. iterator(function (err) {
  11745. if (err) {
  11746. return callback(err);
  11747. }
  11748. async.whilst(test, iterator, callback);
  11749. });
  11750. }
  11751. else {
  11752. callback();
  11753. }
  11754. };
  11755. async.doWhilst = function (iterator, test, callback) {
  11756. iterator(function (err) {
  11757. if (err) {
  11758. return callback(err);
  11759. }
  11760. var args = Array.prototype.slice.call(arguments, 1);
  11761. if (test.apply(null, args)) {
  11762. async.doWhilst(iterator, test, callback);
  11763. }
  11764. else {
  11765. callback();
  11766. }
  11767. });
  11768. };
  11769. async.until = function (test, iterator, callback) {
  11770. if (!test()) {
  11771. iterator(function (err) {
  11772. if (err) {
  11773. return callback(err);
  11774. }
  11775. async.until(test, iterator, callback);
  11776. });
  11777. }
  11778. else {
  11779. callback();
  11780. }
  11781. };
  11782. async.doUntil = function (iterator, test, callback) {
  11783. iterator(function (err) {
  11784. if (err) {
  11785. return callback(err);
  11786. }
  11787. var args = Array.prototype.slice.call(arguments, 1);
  11788. if (!test.apply(null, args)) {
  11789. async.doUntil(iterator, test, callback);
  11790. }
  11791. else {
  11792. callback();
  11793. }
  11794. });
  11795. };
  11796. async.queue = function (worker, concurrency) {
  11797. if (concurrency === undefined) {
  11798. concurrency = 1;
  11799. }
  11800. function _insert(q, data, pos, callback) {
  11801. if (!q.started){
  11802. q.started = true;
  11803. }
  11804. if (!_isArray(data)) {
  11805. data = [data];
  11806. }
  11807. if(data.length == 0) {
  11808. // call drain immediately if there are no tasks
  11809. return async.setImmediate(function() {
  11810. if (q.drain) {
  11811. q.drain();
  11812. }
  11813. });
  11814. }
  11815. _each(data, function(task) {
  11816. var item = {
  11817. data: task,
  11818. callback: typeof callback === 'function' ? callback : null
  11819. };
  11820. if (pos) {
  11821. q.tasks.unshift(item);
  11822. } else {
  11823. q.tasks.push(item);
  11824. }
  11825. if (q.saturated && q.tasks.length === q.concurrency) {
  11826. q.saturated();
  11827. }
  11828. async.setImmediate(q.process);
  11829. });
  11830. }
  11831. var workers = 0;
  11832. var q = {
  11833. tasks: [],
  11834. concurrency: concurrency,
  11835. saturated: null,
  11836. empty: null,
  11837. drain: null,
  11838. started: false,
  11839. paused: false,
  11840. push: function (data, callback) {
  11841. _insert(q, data, false, callback);
  11842. },
  11843. kill: function () {
  11844. q.drain = null;
  11845. q.tasks = [];
  11846. },
  11847. unshift: function (data, callback) {
  11848. _insert(q, data, true, callback);
  11849. },
  11850. process: function () {
  11851. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  11852. var task = q.tasks.shift();
  11853. if (q.empty && q.tasks.length === 0) {
  11854. q.empty();
  11855. }
  11856. workers += 1;
  11857. var next = function () {
  11858. workers -= 1;
  11859. if (task.callback) {
  11860. task.callback.apply(task, arguments);
  11861. }
  11862. if (q.drain && q.tasks.length + workers === 0) {
  11863. q.drain();
  11864. }
  11865. q.process();
  11866. };
  11867. var cb = only_once(next);
  11868. worker(task.data, cb);
  11869. }
  11870. },
  11871. length: function () {
  11872. return q.tasks.length;
  11873. },
  11874. running: function () {
  11875. return workers;
  11876. },
  11877. idle: function() {
  11878. return q.tasks.length + workers === 0;
  11879. },
  11880. pause: function () {
  11881. if (q.paused === true) { return; }
  11882. q.paused = true;
  11883. q.process();
  11884. },
  11885. resume: function () {
  11886. if (q.paused === false) { return; }
  11887. q.paused = false;
  11888. q.process();
  11889. }
  11890. };
  11891. return q;
  11892. };
  11893. async.priorityQueue = function (worker, concurrency) {
  11894. function _compareTasks(a, b){
  11895. return a.priority - b.priority;
  11896. };
  11897. function _binarySearch(sequence, item, compare) {
  11898. var beg = -1,
  11899. end = sequence.length - 1;
  11900. while (beg < end) {
  11901. var mid = beg + ((end - beg + 1) >>> 1);
  11902. if (compare(item, sequence[mid]) >= 0) {
  11903. beg = mid;
  11904. } else {
  11905. end = mid - 1;
  11906. }
  11907. }
  11908. return beg;
  11909. }
  11910. function _insert(q, data, priority, callback) {
  11911. if (!q.started){
  11912. q.started = true;
  11913. }
  11914. if (!_isArray(data)) {
  11915. data = [data];
  11916. }
  11917. if(data.length == 0) {
  11918. // call drain immediately if there are no tasks
  11919. return async.setImmediate(function() {
  11920. if (q.drain) {
  11921. q.drain();
  11922. }
  11923. });
  11924. }
  11925. _each(data, function(task) {
  11926. var item = {
  11927. data: task,
  11928. priority: priority,
  11929. callback: typeof callback === 'function' ? callback : null
  11930. };
  11931. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  11932. if (q.saturated && q.tasks.length === q.concurrency) {
  11933. q.saturated();
  11934. }
  11935. async.setImmediate(q.process);
  11936. });
  11937. }
  11938. // Start with a normal queue
  11939. var q = async.queue(worker, concurrency);
  11940. // Override push to accept second parameter representing priority
  11941. q.push = function (data, priority, callback) {
  11942. _insert(q, data, priority, callback);
  11943. };
  11944. // Remove unshift function
  11945. delete q.unshift;
  11946. return q;
  11947. };
  11948. async.cargo = function (worker, payload) {
  11949. var working = false,
  11950. tasks = [];
  11951. var cargo = {
  11952. tasks: tasks,
  11953. payload: payload,
  11954. saturated: null,
  11955. empty: null,
  11956. drain: null,
  11957. drained: true,
  11958. push: function (data, callback) {
  11959. if (!_isArray(data)) {
  11960. data = [data];
  11961. }
  11962. _each(data, function(task) {
  11963. tasks.push({
  11964. data: task,
  11965. callback: typeof callback === 'function' ? callback : null
  11966. });
  11967. cargo.drained = false;
  11968. if (cargo.saturated && tasks.length === payload) {
  11969. cargo.saturated();
  11970. }
  11971. });
  11972. async.setImmediate(cargo.process);
  11973. },
  11974. process: function process() {
  11975. if (working) return;
  11976. if (tasks.length === 0) {
  11977. if(cargo.drain && !cargo.drained) cargo.drain();
  11978. cargo.drained = true;
  11979. return;
  11980. }
  11981. var ts = typeof payload === 'number'
  11982. ? tasks.splice(0, payload)
  11983. : tasks.splice(0, tasks.length);
  11984. var ds = _map(ts, function (task) {
  11985. return task.data;
  11986. });
  11987. if(cargo.empty) cargo.empty();
  11988. working = true;
  11989. worker(ds, function () {
  11990. working = false;
  11991. var args = arguments;
  11992. _each(ts, function (data) {
  11993. if (data.callback) {
  11994. data.callback.apply(null, args);
  11995. }
  11996. });
  11997. process();
  11998. });
  11999. },
  12000. length: function () {
  12001. return tasks.length;
  12002. },
  12003. running: function () {
  12004. return working;
  12005. }
  12006. };
  12007. return cargo;
  12008. };
  12009. var _console_fn = function (name) {
  12010. return function (fn) {
  12011. var args = Array.prototype.slice.call(arguments, 1);
  12012. fn.apply(null, args.concat([function (err) {
  12013. var args = Array.prototype.slice.call(arguments, 1);
  12014. if (typeof console !== 'undefined') {
  12015. if (err) {
  12016. if (console.error) {
  12017. console.error(err);
  12018. }
  12019. }
  12020. else if (console[name]) {
  12021. _each(args, function (x) {
  12022. console[name](x);
  12023. });
  12024. }
  12025. }
  12026. }]));
  12027. };
  12028. };
  12029. async.log = _console_fn('log');
  12030. async.dir = _console_fn('dir');
  12031. /*async.info = _console_fn('info');
  12032. async.warn = _console_fn('warn');
  12033. async.error = _console_fn('error');*/
  12034. async.memoize = function (fn, hasher) {
  12035. var memo = {};
  12036. var queues = {};
  12037. hasher = hasher || function (x) {
  12038. return x;
  12039. };
  12040. var memoized = function () {
  12041. var args = Array.prototype.slice.call(arguments);
  12042. var callback = args.pop();
  12043. var key = hasher.apply(null, args);
  12044. if (key in memo) {
  12045. async.nextTick(function () {
  12046. callback.apply(null, memo[key]);
  12047. });
  12048. }
  12049. else if (key in queues) {
  12050. queues[key].push(callback);
  12051. }
  12052. else {
  12053. queues[key] = [callback];
  12054. fn.apply(null, args.concat([function () {
  12055. memo[key] = arguments;
  12056. var q = queues[key];
  12057. delete queues[key];
  12058. for (var i = 0, l = q.length; i < l; i++) {
  12059. q[i].apply(null, arguments);
  12060. }
  12061. }]));
  12062. }
  12063. };
  12064. memoized.memo = memo;
  12065. memoized.unmemoized = fn;
  12066. return memoized;
  12067. };
  12068. async.unmemoize = function (fn) {
  12069. return function () {
  12070. return (fn.unmemoized || fn).apply(null, arguments);
  12071. };
  12072. };
  12073. async.times = function (count, iterator, callback) {
  12074. var counter = [];
  12075. for (var i = 0; i < count; i++) {
  12076. counter.push(i);
  12077. }
  12078. return async.map(counter, iterator, callback);
  12079. };
  12080. async.timesSeries = function (count, iterator, callback) {
  12081. var counter = [];
  12082. for (var i = 0; i < count; i++) {
  12083. counter.push(i);
  12084. }
  12085. return async.mapSeries(counter, iterator, callback);
  12086. };
  12087. async.seq = function (/* functions... */) {
  12088. var fns = arguments;
  12089. return function () {
  12090. var that = this;
  12091. var args = Array.prototype.slice.call(arguments);
  12092. var callback = args.pop();
  12093. async.reduce(fns, args, function (newargs, fn, cb) {
  12094. fn.apply(that, newargs.concat([function () {
  12095. var err = arguments[0];
  12096. var nextargs = Array.prototype.slice.call(arguments, 1);
  12097. cb(err, nextargs);
  12098. }]))
  12099. },
  12100. function (err, results) {
  12101. callback.apply(that, [err].concat(results));
  12102. });
  12103. };
  12104. };
  12105. async.compose = function (/* functions... */) {
  12106. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  12107. };
  12108. var _applyEach = function (eachfn, fns /*args...*/) {
  12109. var go = function () {
  12110. var that = this;
  12111. var args = Array.prototype.slice.call(arguments);
  12112. var callback = args.pop();
  12113. return eachfn(fns, function (fn, cb) {
  12114. fn.apply(that, args.concat([cb]));
  12115. },
  12116. callback);
  12117. };
  12118. if (arguments.length > 2) {
  12119. var args = Array.prototype.slice.call(arguments, 2);
  12120. return go.apply(this, args);
  12121. }
  12122. else {
  12123. return go;
  12124. }
  12125. };
  12126. async.applyEach = doParallel(_applyEach);
  12127. async.applyEachSeries = doSeries(_applyEach);
  12128. async.forever = function (fn, callback) {
  12129. function next(err) {
  12130. if (err) {
  12131. if (callback) {
  12132. return callback(err);
  12133. }
  12134. throw err;
  12135. }
  12136. fn(next);
  12137. }
  12138. next();
  12139. };
  12140. // Node.js
  12141. if (typeof module !== 'undefined' && module.exports) {
  12142. module.exports = async;
  12143. }
  12144. // AMD / RequireJS
  12145. else if (typeof define !== 'undefined' && define.amd) {
  12146. define([], function () {
  12147. return async;
  12148. });
  12149. }
  12150. // included directly via <script> tag
  12151. else {
  12152. root.async = async;
  12153. }
  12154. }());
  12155. }).call(this,require('_process'))
  12156. },{"_process":45}],44:[function(require,module,exports){
  12157. // Copyright Joyent, Inc. and other Node contributors.
  12158. //
  12159. // Permission is hereby granted, free of charge, to any person obtaining a
  12160. // copy of this software and associated documentation files (the
  12161. // "Software"), to deal in the Software without restriction, including
  12162. // without limitation the rights to use, copy, modify, merge, publish,
  12163. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12164. // persons to whom the Software is furnished to do so, subject to the
  12165. // following conditions:
  12166. //
  12167. // The above copyright notice and this permission notice shall be included
  12168. // in all copies or substantial portions of the Software.
  12169. //
  12170. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12171. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12172. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12173. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12174. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12175. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12176. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12177. function EventEmitter() {
  12178. this._events = this._events || {};
  12179. this._maxListeners = this._maxListeners || undefined;
  12180. }
  12181. module.exports = EventEmitter;
  12182. // Backwards-compat with node 0.10.x
  12183. EventEmitter.EventEmitter = EventEmitter;
  12184. EventEmitter.prototype._events = undefined;
  12185. EventEmitter.prototype._maxListeners = undefined;
  12186. // By default EventEmitters will print a warning if more than 10 listeners are
  12187. // added to it. This is a useful default which helps finding memory leaks.
  12188. EventEmitter.defaultMaxListeners = 10;
  12189. // Obviously not all Emitters should be limited to 10. This function allows
  12190. // that to be increased. Set to zero for unlimited.
  12191. EventEmitter.prototype.setMaxListeners = function(n) {
  12192. if (!isNumber(n) || n < 0 || isNaN(n))
  12193. throw TypeError('n must be a positive number');
  12194. this._maxListeners = n;
  12195. return this;
  12196. };
  12197. EventEmitter.prototype.emit = function(type) {
  12198. var er, handler, len, args, i, listeners;
  12199. if (!this._events)
  12200. this._events = {};
  12201. // If there is no 'error' event listener then throw.
  12202. if (type === 'error') {
  12203. if (!this._events.error ||
  12204. (isObject(this._events.error) && !this._events.error.length)) {
  12205. er = arguments[1];
  12206. if (er instanceof Error) {
  12207. throw er; // Unhandled 'error' event
  12208. }
  12209. throw TypeError('Uncaught, unspecified "error" event.');
  12210. }
  12211. }
  12212. handler = this._events[type];
  12213. if (isUndefined(handler))
  12214. return false;
  12215. if (isFunction(handler)) {
  12216. switch (arguments.length) {
  12217. // fast cases
  12218. case 1:
  12219. handler.call(this);
  12220. break;
  12221. case 2:
  12222. handler.call(this, arguments[1]);
  12223. break;
  12224. case 3:
  12225. handler.call(this, arguments[1], arguments[2]);
  12226. break;
  12227. // slower
  12228. default:
  12229. len = arguments.length;
  12230. args = new Array(len - 1);
  12231. for (i = 1; i < len; i++)
  12232. args[i - 1] = arguments[i];
  12233. handler.apply(this, args);
  12234. }
  12235. } else if (isObject(handler)) {
  12236. len = arguments.length;
  12237. args = new Array(len - 1);
  12238. for (i = 1; i < len; i++)
  12239. args[i - 1] = arguments[i];
  12240. listeners = handler.slice();
  12241. len = listeners.length;
  12242. for (i = 0; i < len; i++)
  12243. listeners[i].apply(this, args);
  12244. }
  12245. return true;
  12246. };
  12247. EventEmitter.prototype.addListener = function(type, listener) {
  12248. var m;
  12249. if (!isFunction(listener))
  12250. throw TypeError('listener must be a function');
  12251. if (!this._events)
  12252. this._events = {};
  12253. // To avoid recursion in the case that type === "newListener"! Before
  12254. // adding it to the listeners, first emit "newListener".
  12255. if (this._events.newListener)
  12256. this.emit('newListener', type,
  12257. isFunction(listener.listener) ?
  12258. listener.listener : listener);
  12259. if (!this._events[type])
  12260. // Optimize the case of one listener. Don't need the extra array object.
  12261. this._events[type] = listener;
  12262. else if (isObject(this._events[type]))
  12263. // If we've already got an array, just append.
  12264. this._events[type].push(listener);
  12265. else
  12266. // Adding the second element, need to change to array.
  12267. this._events[type] = [this._events[type], listener];
  12268. // Check for listener leak
  12269. if (isObject(this._events[type]) && !this._events[type].warned) {
  12270. var m;
  12271. if (!isUndefined(this._maxListeners)) {
  12272. m = this._maxListeners;
  12273. } else {
  12274. m = EventEmitter.defaultMaxListeners;
  12275. }
  12276. if (m && m > 0 && this._events[type].length > m) {
  12277. this._events[type].warned = true;
  12278. console.error('(node) warning: possible EventEmitter memory ' +
  12279. 'leak detected. %d listeners added. ' +
  12280. 'Use emitter.setMaxListeners() to increase limit.',
  12281. this._events[type].length);
  12282. if (typeof console.trace === 'function') {
  12283. // not supported in IE 10
  12284. console.trace();
  12285. }
  12286. }
  12287. }
  12288. return this;
  12289. };
  12290. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  12291. EventEmitter.prototype.once = function(type, listener) {
  12292. if (!isFunction(listener))
  12293. throw TypeError('listener must be a function');
  12294. var fired = false;
  12295. function g() {
  12296. this.removeListener(type, g);
  12297. if (!fired) {
  12298. fired = true;
  12299. listener.apply(this, arguments);
  12300. }
  12301. }
  12302. g.listener = listener;
  12303. this.on(type, g);
  12304. return this;
  12305. };
  12306. // emits a 'removeListener' event iff the listener was removed
  12307. EventEmitter.prototype.removeListener = function(type, listener) {
  12308. var list, position, length, i;
  12309. if (!isFunction(listener))
  12310. throw TypeError('listener must be a function');
  12311. if (!this._events || !this._events[type])
  12312. return this;
  12313. list = this._events[type];
  12314. length = list.length;
  12315. position = -1;
  12316. if (list === listener ||
  12317. (isFunction(list.listener) && list.listener === listener)) {
  12318. delete this._events[type];
  12319. if (this._events.removeListener)
  12320. this.emit('removeListener', type, listener);
  12321. } else if (isObject(list)) {
  12322. for (i = length; i-- > 0;) {
  12323. if (list[i] === listener ||
  12324. (list[i].listener && list[i].listener === listener)) {
  12325. position = i;
  12326. break;
  12327. }
  12328. }
  12329. if (position < 0)
  12330. return this;
  12331. if (list.length === 1) {
  12332. list.length = 0;
  12333. delete this._events[type];
  12334. } else {
  12335. list.splice(position, 1);
  12336. }
  12337. if (this._events.removeListener)
  12338. this.emit('removeListener', type, listener);
  12339. }
  12340. return this;
  12341. };
  12342. EventEmitter.prototype.removeAllListeners = function(type) {
  12343. var key, listeners;
  12344. if (!this._events)
  12345. return this;
  12346. // not listening for removeListener, no need to emit
  12347. if (!this._events.removeListener) {
  12348. if (arguments.length === 0)
  12349. this._events = {};
  12350. else if (this._events[type])
  12351. delete this._events[type];
  12352. return this;
  12353. }
  12354. // emit removeListener for all listeners on all events
  12355. if (arguments.length === 0) {
  12356. for (key in this._events) {
  12357. if (key === 'removeListener') continue;
  12358. this.removeAllListeners(key);
  12359. }
  12360. this.removeAllListeners('removeListener');
  12361. this._events = {};
  12362. return this;
  12363. }
  12364. listeners = this._events[type];
  12365. if (isFunction(listeners)) {
  12366. this.removeListener(type, listeners);
  12367. } else {
  12368. // LIFO order
  12369. while (listeners.length)
  12370. this.removeListener(type, listeners[listeners.length - 1]);
  12371. }
  12372. delete this._events[type];
  12373. return this;
  12374. };
  12375. EventEmitter.prototype.listeners = function(type) {
  12376. var ret;
  12377. if (!this._events || !this._events[type])
  12378. ret = [];
  12379. else if (isFunction(this._events[type]))
  12380. ret = [this._events[type]];
  12381. else
  12382. ret = this._events[type].slice();
  12383. return ret;
  12384. };
  12385. EventEmitter.listenerCount = function(emitter, type) {
  12386. var ret;
  12387. if (!emitter._events || !emitter._events[type])
  12388. ret = 0;
  12389. else if (isFunction(emitter._events[type]))
  12390. ret = 1;
  12391. else
  12392. ret = emitter._events[type].length;
  12393. return ret;
  12394. };
  12395. function isFunction(arg) {
  12396. return typeof arg === 'function';
  12397. }
  12398. function isNumber(arg) {
  12399. return typeof arg === 'number';
  12400. }
  12401. function isObject(arg) {
  12402. return typeof arg === 'object' && arg !== null;
  12403. }
  12404. function isUndefined(arg) {
  12405. return arg === void 0;
  12406. }
  12407. },{}],45:[function(require,module,exports){
  12408. // shim for using process in browser
  12409. var process = module.exports = {};
  12410. var queue = [];
  12411. var draining = false;
  12412. var currentQueue;
  12413. var queueIndex = -1;
  12414. function cleanUpNextTick() {
  12415. draining = false;
  12416. if (currentQueue.length) {
  12417. queue = currentQueue.concat(queue);
  12418. } else {
  12419. queueIndex = -1;
  12420. }
  12421. if (queue.length) {
  12422. drainQueue();
  12423. }
  12424. }
  12425. function drainQueue() {
  12426. if (draining) {
  12427. return;
  12428. }
  12429. var timeout = setTimeout(cleanUpNextTick);
  12430. draining = true;
  12431. var len = queue.length;
  12432. while(len) {
  12433. currentQueue = queue;
  12434. queue = [];
  12435. while (++queueIndex < len) {
  12436. if (currentQueue) {
  12437. currentQueue[queueIndex].run();
  12438. }
  12439. }
  12440. queueIndex = -1;
  12441. len = queue.length;
  12442. }
  12443. currentQueue = null;
  12444. draining = false;
  12445. clearTimeout(timeout);
  12446. }
  12447. process.nextTick = function (fun) {
  12448. var args = new Array(arguments.length - 1);
  12449. if (arguments.length > 1) {
  12450. for (var i = 1; i < arguments.length; i++) {
  12451. args[i - 1] = arguments[i];
  12452. }
  12453. }
  12454. queue.push(new Item(fun, args));
  12455. if (queue.length === 1 && !draining) {
  12456. setTimeout(drainQueue, 0);
  12457. }
  12458. };
  12459. // v8 likes predictible objects
  12460. function Item(fun, array) {
  12461. this.fun = fun;
  12462. this.array = array;
  12463. }
  12464. Item.prototype.run = function () {
  12465. this.fun.apply(null, this.array);
  12466. };
  12467. process.title = 'browser';
  12468. process.browser = true;
  12469. process.env = {};
  12470. process.argv = [];
  12471. process.version = ''; // empty string to avoid regexp issues
  12472. process.versions = {};
  12473. function noop() {}
  12474. process.on = noop;
  12475. process.addListener = noop;
  12476. process.once = noop;
  12477. process.off = noop;
  12478. process.removeListener = noop;
  12479. process.removeAllListeners = noop;
  12480. process.emit = noop;
  12481. process.binding = function (name) {
  12482. throw new Error('process.binding is not supported');
  12483. };
  12484. process.cwd = function () { return '/' };
  12485. process.chdir = function (dir) {
  12486. throw new Error('process.chdir is not supported');
  12487. };
  12488. process.umask = function() { return 0; };
  12489. },{}],46:[function(require,module,exports){
  12490. (function (process,global){
  12491. /*!
  12492. * @overview es6-promise - a tiny implementation of Promises/A+.
  12493. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  12494. * @license Licensed under MIT license
  12495. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  12496. * @version 3.0.2
  12497. */
  12498. (function() {
  12499. "use strict";
  12500. function lib$es6$promise$utils$$objectOrFunction(x) {
  12501. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  12502. }
  12503. function lib$es6$promise$utils$$isFunction(x) {
  12504. return typeof x === 'function';
  12505. }
  12506. function lib$es6$promise$utils$$isMaybeThenable(x) {
  12507. return typeof x === 'object' && x !== null;
  12508. }
  12509. var lib$es6$promise$utils$$_isArray;
  12510. if (!Array.isArray) {
  12511. lib$es6$promise$utils$$_isArray = function (x) {
  12512. return Object.prototype.toString.call(x) === '[object Array]';
  12513. };
  12514. } else {
  12515. lib$es6$promise$utils$$_isArray = Array.isArray;
  12516. }
  12517. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  12518. var lib$es6$promise$asap$$len = 0;
  12519. var lib$es6$promise$asap$$toString = {}.toString;
  12520. var lib$es6$promise$asap$$vertxNext;
  12521. var lib$es6$promise$asap$$customSchedulerFn;
  12522. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  12523. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  12524. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  12525. lib$es6$promise$asap$$len += 2;
  12526. if (lib$es6$promise$asap$$len === 2) {
  12527. // If len is 2, that means that we need to schedule an async flush.
  12528. // If additional callbacks are queued before the queue is flushed, they
  12529. // will be processed by this flush that we are scheduling.
  12530. if (lib$es6$promise$asap$$customSchedulerFn) {
  12531. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  12532. } else {
  12533. lib$es6$promise$asap$$scheduleFlush();
  12534. }
  12535. }
  12536. }
  12537. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  12538. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  12539. }
  12540. function lib$es6$promise$asap$$setAsap(asapFn) {
  12541. lib$es6$promise$asap$$asap = asapFn;
  12542. }
  12543. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  12544. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  12545. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  12546. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  12547. // test for web worker but not in IE10
  12548. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  12549. typeof importScripts !== 'undefined' &&
  12550. typeof MessageChannel !== 'undefined';
  12551. // node
  12552. function lib$es6$promise$asap$$useNextTick() {
  12553. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  12554. // see https://github.com/cujojs/when/issues/410 for details
  12555. return function() {
  12556. process.nextTick(lib$es6$promise$asap$$flush);
  12557. };
  12558. }
  12559. // vertx
  12560. function lib$es6$promise$asap$$useVertxTimer() {
  12561. return function() {
  12562. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  12563. };
  12564. }
  12565. function lib$es6$promise$asap$$useMutationObserver() {
  12566. var iterations = 0;
  12567. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  12568. var node = document.createTextNode('');
  12569. observer.observe(node, { characterData: true });
  12570. return function() {
  12571. node.data = (iterations = ++iterations % 2);
  12572. };
  12573. }
  12574. // web worker
  12575. function lib$es6$promise$asap$$useMessageChannel() {
  12576. var channel = new MessageChannel();
  12577. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  12578. return function () {
  12579. channel.port2.postMessage(0);
  12580. };
  12581. }
  12582. function lib$es6$promise$asap$$useSetTimeout() {
  12583. return function() {
  12584. setTimeout(lib$es6$promise$asap$$flush, 1);
  12585. };
  12586. }
  12587. var lib$es6$promise$asap$$queue = new Array(1000);
  12588. function lib$es6$promise$asap$$flush() {
  12589. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  12590. var callback = lib$es6$promise$asap$$queue[i];
  12591. var arg = lib$es6$promise$asap$$queue[i+1];
  12592. callback(arg);
  12593. lib$es6$promise$asap$$queue[i] = undefined;
  12594. lib$es6$promise$asap$$queue[i+1] = undefined;
  12595. }
  12596. lib$es6$promise$asap$$len = 0;
  12597. }
  12598. function lib$es6$promise$asap$$attemptVertx() {
  12599. try {
  12600. var r = require;
  12601. var vertx = r('vertx');
  12602. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  12603. return lib$es6$promise$asap$$useVertxTimer();
  12604. } catch(e) {
  12605. return lib$es6$promise$asap$$useSetTimeout();
  12606. }
  12607. }
  12608. var lib$es6$promise$asap$$scheduleFlush;
  12609. // Decide what async method to use to triggering processing of queued callbacks:
  12610. if (lib$es6$promise$asap$$isNode) {
  12611. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  12612. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  12613. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  12614. } else if (lib$es6$promise$asap$$isWorker) {
  12615. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  12616. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  12617. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  12618. } else {
  12619. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  12620. }
  12621. function lib$es6$promise$$internal$$noop() {}
  12622. var lib$es6$promise$$internal$$PENDING = void 0;
  12623. var lib$es6$promise$$internal$$FULFILLED = 1;
  12624. var lib$es6$promise$$internal$$REJECTED = 2;
  12625. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12626. function lib$es6$promise$$internal$$selfFulfillment() {
  12627. return new TypeError("You cannot resolve a promise with itself");
  12628. }
  12629. function lib$es6$promise$$internal$$cannotReturnOwn() {
  12630. return new TypeError('A promises callback cannot return that same promise.');
  12631. }
  12632. function lib$es6$promise$$internal$$getThen(promise) {
  12633. try {
  12634. return promise.then;
  12635. } catch(error) {
  12636. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  12637. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  12638. }
  12639. }
  12640. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  12641. try {
  12642. then.call(value, fulfillmentHandler, rejectionHandler);
  12643. } catch(e) {
  12644. return e;
  12645. }
  12646. }
  12647. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  12648. lib$es6$promise$asap$$asap(function(promise) {
  12649. var sealed = false;
  12650. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  12651. if (sealed) { return; }
  12652. sealed = true;
  12653. if (thenable !== value) {
  12654. lib$es6$promise$$internal$$resolve(promise, value);
  12655. } else {
  12656. lib$es6$promise$$internal$$fulfill(promise, value);
  12657. }
  12658. }, function(reason) {
  12659. if (sealed) { return; }
  12660. sealed = true;
  12661. lib$es6$promise$$internal$$reject(promise, reason);
  12662. }, 'Settle: ' + (promise._label || ' unknown promise'));
  12663. if (!sealed && error) {
  12664. sealed = true;
  12665. lib$es6$promise$$internal$$reject(promise, error);
  12666. }
  12667. }, promise);
  12668. }
  12669. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  12670. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  12671. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  12672. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  12673. lib$es6$promise$$internal$$reject(promise, thenable._result);
  12674. } else {
  12675. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  12676. lib$es6$promise$$internal$$resolve(promise, value);
  12677. }, function(reason) {
  12678. lib$es6$promise$$internal$$reject(promise, reason);
  12679. });
  12680. }
  12681. }
  12682. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  12683. if (maybeThenable.constructor === promise.constructor) {
  12684. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  12685. } else {
  12686. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  12687. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  12688. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  12689. } else if (then === undefined) {
  12690. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12691. } else if (lib$es6$promise$utils$$isFunction(then)) {
  12692. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  12693. } else {
  12694. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  12695. }
  12696. }
  12697. }
  12698. function lib$es6$promise$$internal$$resolve(promise, value) {
  12699. if (promise === value) {
  12700. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  12701. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  12702. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  12703. } else {
  12704. lib$es6$promise$$internal$$fulfill(promise, value);
  12705. }
  12706. }
  12707. function lib$es6$promise$$internal$$publishRejection(promise) {
  12708. if (promise._onerror) {
  12709. promise._onerror(promise._result);
  12710. }
  12711. lib$es6$promise$$internal$$publish(promise);
  12712. }
  12713. function lib$es6$promise$$internal$$fulfill(promise, value) {
  12714. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12715. promise._result = value;
  12716. promise._state = lib$es6$promise$$internal$$FULFILLED;
  12717. if (promise._subscribers.length !== 0) {
  12718. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  12719. }
  12720. }
  12721. function lib$es6$promise$$internal$$reject(promise, reason) {
  12722. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  12723. promise._state = lib$es6$promise$$internal$$REJECTED;
  12724. promise._result = reason;
  12725. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  12726. }
  12727. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  12728. var subscribers = parent._subscribers;
  12729. var length = subscribers.length;
  12730. parent._onerror = null;
  12731. subscribers[length] = child;
  12732. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  12733. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  12734. if (length === 0 && parent._state) {
  12735. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  12736. }
  12737. }
  12738. function lib$es6$promise$$internal$$publish(promise) {
  12739. var subscribers = promise._subscribers;
  12740. var settled = promise._state;
  12741. if (subscribers.length === 0) { return; }
  12742. var child, callback, detail = promise._result;
  12743. for (var i = 0; i < subscribers.length; i += 3) {
  12744. child = subscribers[i];
  12745. callback = subscribers[i + settled];
  12746. if (child) {
  12747. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  12748. } else {
  12749. callback(detail);
  12750. }
  12751. }
  12752. promise._subscribers.length = 0;
  12753. }
  12754. function lib$es6$promise$$internal$$ErrorObject() {
  12755. this.error = null;
  12756. }
  12757. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  12758. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  12759. try {
  12760. return callback(detail);
  12761. } catch(e) {
  12762. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  12763. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  12764. }
  12765. }
  12766. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  12767. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  12768. value, error, succeeded, failed;
  12769. if (hasCallback) {
  12770. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  12771. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  12772. failed = true;
  12773. error = value.error;
  12774. value = null;
  12775. } else {
  12776. succeeded = true;
  12777. }
  12778. if (promise === value) {
  12779. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  12780. return;
  12781. }
  12782. } else {
  12783. value = detail;
  12784. succeeded = true;
  12785. }
  12786. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  12787. // noop
  12788. } else if (hasCallback && succeeded) {
  12789. lib$es6$promise$$internal$$resolve(promise, value);
  12790. } else if (failed) {
  12791. lib$es6$promise$$internal$$reject(promise, error);
  12792. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  12793. lib$es6$promise$$internal$$fulfill(promise, value);
  12794. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12795. lib$es6$promise$$internal$$reject(promise, value);
  12796. }
  12797. }
  12798. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12799. try {
  12800. resolver(function resolvePromise(value){
  12801. lib$es6$promise$$internal$$resolve(promise, value);
  12802. }, function rejectPromise(reason) {
  12803. lib$es6$promise$$internal$$reject(promise, reason);
  12804. });
  12805. } catch(e) {
  12806. lib$es6$promise$$internal$$reject(promise, e);
  12807. }
  12808. }
  12809. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12810. var enumerator = this;
  12811. enumerator._instanceConstructor = Constructor;
  12812. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12813. if (enumerator._validateInput(input)) {
  12814. enumerator._input = input;
  12815. enumerator.length = input.length;
  12816. enumerator._remaining = input.length;
  12817. enumerator._init();
  12818. if (enumerator.length === 0) {
  12819. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12820. } else {
  12821. enumerator.length = enumerator.length || 0;
  12822. enumerator._enumerate();
  12823. if (enumerator._remaining === 0) {
  12824. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12825. }
  12826. }
  12827. } else {
  12828. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12829. }
  12830. }
  12831. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12832. return lib$es6$promise$utils$$isArray(input);
  12833. };
  12834. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12835. return new Error('Array Methods must be provided an Array');
  12836. };
  12837. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  12838. this._result = new Array(this.length);
  12839. };
  12840. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  12841. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  12842. var enumerator = this;
  12843. var length = enumerator.length;
  12844. var promise = enumerator.promise;
  12845. var input = enumerator._input;
  12846. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12847. enumerator._eachEntry(input[i], i);
  12848. }
  12849. };
  12850. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  12851. var enumerator = this;
  12852. var c = enumerator._instanceConstructor;
  12853. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  12854. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  12855. entry._onerror = null;
  12856. enumerator._settledAt(entry._state, i, entry._result);
  12857. } else {
  12858. enumerator._willSettleAt(c.resolve(entry), i);
  12859. }
  12860. } else {
  12861. enumerator._remaining--;
  12862. enumerator._result[i] = entry;
  12863. }
  12864. };
  12865. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  12866. var enumerator = this;
  12867. var promise = enumerator.promise;
  12868. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  12869. enumerator._remaining--;
  12870. if (state === lib$es6$promise$$internal$$REJECTED) {
  12871. lib$es6$promise$$internal$$reject(promise, value);
  12872. } else {
  12873. enumerator._result[i] = value;
  12874. }
  12875. }
  12876. if (enumerator._remaining === 0) {
  12877. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  12878. }
  12879. };
  12880. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  12881. var enumerator = this;
  12882. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  12883. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  12884. }, function(reason) {
  12885. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  12886. });
  12887. };
  12888. function lib$es6$promise$promise$all$$all(entries) {
  12889. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  12890. }
  12891. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  12892. function lib$es6$promise$promise$race$$race(entries) {
  12893. /*jshint validthis:true */
  12894. var Constructor = this;
  12895. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12896. if (!lib$es6$promise$utils$$isArray(entries)) {
  12897. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  12898. return promise;
  12899. }
  12900. var length = entries.length;
  12901. function onFulfillment(value) {
  12902. lib$es6$promise$$internal$$resolve(promise, value);
  12903. }
  12904. function onRejection(reason) {
  12905. lib$es6$promise$$internal$$reject(promise, reason);
  12906. }
  12907. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12908. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  12909. }
  12910. return promise;
  12911. }
  12912. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  12913. function lib$es6$promise$promise$resolve$$resolve(object) {
  12914. /*jshint validthis:true */
  12915. var Constructor = this;
  12916. if (object && typeof object === 'object' && object.constructor === Constructor) {
  12917. return object;
  12918. }
  12919. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12920. lib$es6$promise$$internal$$resolve(promise, object);
  12921. return promise;
  12922. }
  12923. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  12924. function lib$es6$promise$promise$reject$$reject(reason) {
  12925. /*jshint validthis:true */
  12926. var Constructor = this;
  12927. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12928. lib$es6$promise$$internal$$reject(promise, reason);
  12929. return promise;
  12930. }
  12931. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  12932. var lib$es6$promise$promise$$counter = 0;
  12933. function lib$es6$promise$promise$$needsResolver() {
  12934. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  12935. }
  12936. function lib$es6$promise$promise$$needsNew() {
  12937. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  12938. }
  12939. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  12940. /**
  12941. Promise objects represent the eventual result of an asynchronous operation. The
  12942. primary way of interacting with a promise is through its `then` method, which
  12943. registers callbacks to receive either a promise's eventual value or the reason
  12944. why the promise cannot be fulfilled.
  12945. Terminology
  12946. -----------
  12947. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  12948. - `thenable` is an object or function that defines a `then` method.
  12949. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  12950. - `exception` is a value that is thrown using the throw statement.
  12951. - `reason` is a value that indicates why a promise was rejected.
  12952. - `settled` the final resting state of a promise, fulfilled or rejected.
  12953. A promise can be in one of three states: pending, fulfilled, or rejected.
  12954. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  12955. state. Promises that are rejected have a rejection reason and are in the
  12956. rejected state. A fulfillment value is never a thenable.
  12957. Promises can also be said to *resolve* a value. If this value is also a
  12958. promise, then the original promise's settled state will match the value's
  12959. settled state. So a promise that *resolves* a promise that rejects will
  12960. itself reject, and a promise that *resolves* a promise that fulfills will
  12961. itself fulfill.
  12962. Basic Usage:
  12963. ------------
  12964. ```js
  12965. var promise = new Promise(function(resolve, reject) {
  12966. // on success
  12967. resolve(value);
  12968. // on failure
  12969. reject(reason);
  12970. });
  12971. promise.then(function(value) {
  12972. // on fulfillment
  12973. }, function(reason) {
  12974. // on rejection
  12975. });
  12976. ```
  12977. Advanced Usage:
  12978. ---------------
  12979. Promises shine when abstracting away asynchronous interactions such as
  12980. `XMLHttpRequest`s.
  12981. ```js
  12982. function getJSON(url) {
  12983. return new Promise(function(resolve, reject){
  12984. var xhr = new XMLHttpRequest();
  12985. xhr.open('GET', url);
  12986. xhr.onreadystatechange = handler;
  12987. xhr.responseType = 'json';
  12988. xhr.setRequestHeader('Accept', 'application/json');
  12989. xhr.send();
  12990. function handler() {
  12991. if (this.readyState === this.DONE) {
  12992. if (this.status === 200) {
  12993. resolve(this.response);
  12994. } else {
  12995. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  12996. }
  12997. }
  12998. };
  12999. });
  13000. }
  13001. getJSON('/posts.json').then(function(json) {
  13002. // on fulfillment
  13003. }, function(reason) {
  13004. // on rejection
  13005. });
  13006. ```
  13007. Unlike callbacks, promises are great composable primitives.
  13008. ```js
  13009. Promise.all([
  13010. getJSON('/posts'),
  13011. getJSON('/comments')
  13012. ]).then(function(values){
  13013. values[0] // => postsJSON
  13014. values[1] // => commentsJSON
  13015. return values;
  13016. });
  13017. ```
  13018. @class Promise
  13019. @param {function} resolver
  13020. Useful for tooling.
  13021. @constructor
  13022. */
  13023. function lib$es6$promise$promise$$Promise(resolver) {
  13024. this._id = lib$es6$promise$promise$$counter++;
  13025. this._state = undefined;
  13026. this._result = undefined;
  13027. this._subscribers = [];
  13028. if (lib$es6$promise$$internal$$noop !== resolver) {
  13029. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  13030. lib$es6$promise$promise$$needsResolver();
  13031. }
  13032. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  13033. lib$es6$promise$promise$$needsNew();
  13034. }
  13035. lib$es6$promise$$internal$$initializePromise(this, resolver);
  13036. }
  13037. }
  13038. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  13039. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  13040. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  13041. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  13042. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  13043. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  13044. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  13045. lib$es6$promise$promise$$Promise.prototype = {
  13046. constructor: lib$es6$promise$promise$$Promise,
  13047. /**
  13048. The primary way of interacting with a promise is through its `then` method,
  13049. which registers callbacks to receive either a promise's eventual value or the
  13050. reason why the promise cannot be fulfilled.
  13051. ```js
  13052. findUser().then(function(user){
  13053. // user is available
  13054. }, function(reason){
  13055. // user is unavailable, and you are given the reason why
  13056. });
  13057. ```
  13058. Chaining
  13059. --------
  13060. The return value of `then` is itself a promise. This second, 'downstream'
  13061. promise is resolved with the return value of the first promise's fulfillment
  13062. or rejection handler, or rejected if the handler throws an exception.
  13063. ```js
  13064. findUser().then(function (user) {
  13065. return user.name;
  13066. }, function (reason) {
  13067. return 'default name';
  13068. }).then(function (userName) {
  13069. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  13070. // will be `'default name'`
  13071. });
  13072. findUser().then(function (user) {
  13073. throw new Error('Found user, but still unhappy');
  13074. }, function (reason) {
  13075. throw new Error('`findUser` rejected and we're unhappy');
  13076. }).then(function (value) {
  13077. // never reached
  13078. }, function (reason) {
  13079. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  13080. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  13081. });
  13082. ```
  13083. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  13084. ```js
  13085. findUser().then(function (user) {
  13086. throw new PedagogicalException('Upstream error');
  13087. }).then(function (value) {
  13088. // never reached
  13089. }).then(function (value) {
  13090. // never reached
  13091. }, function (reason) {
  13092. // The `PedgagocialException` is propagated all the way down to here
  13093. });
  13094. ```
  13095. Assimilation
  13096. ------------
  13097. Sometimes the value you want to propagate to a downstream promise can only be
  13098. retrieved asynchronously. This can be achieved by returning a promise in the
  13099. fulfillment or rejection handler. The downstream promise will then be pending
  13100. until the returned promise is settled. This is called *assimilation*.
  13101. ```js
  13102. findUser().then(function (user) {
  13103. return findCommentsByAuthor(user);
  13104. }).then(function (comments) {
  13105. // The user's comments are now available
  13106. });
  13107. ```
  13108. If the assimliated promise rejects, then the downstream promise will also reject.
  13109. ```js
  13110. findUser().then(function (user) {
  13111. return findCommentsByAuthor(user);
  13112. }).then(function (comments) {
  13113. // If `findCommentsByAuthor` fulfills, we'll have the value here
  13114. }, function (reason) {
  13115. // If `findCommentsByAuthor` rejects, we'll have the reason here
  13116. });
  13117. ```
  13118. Simple Example
  13119. --------------
  13120. Synchronous Example
  13121. ```javascript
  13122. var result;
  13123. try {
  13124. result = findResult();
  13125. // success
  13126. } catch(reason) {
  13127. // failure
  13128. }
  13129. ```
  13130. Errback Example
  13131. ```js
  13132. findResult(function(result, err){
  13133. if (err) {
  13134. // failure
  13135. } else {
  13136. // success
  13137. }
  13138. });
  13139. ```
  13140. Promise Example;
  13141. ```javascript
  13142. findResult().then(function(result){
  13143. // success
  13144. }, function(reason){
  13145. // failure
  13146. });
  13147. ```
  13148. Advanced Example
  13149. --------------
  13150. Synchronous Example
  13151. ```javascript
  13152. var author, books;
  13153. try {
  13154. author = findAuthor();
  13155. books = findBooksByAuthor(author);
  13156. // success
  13157. } catch(reason) {
  13158. // failure
  13159. }
  13160. ```
  13161. Errback Example
  13162. ```js
  13163. function foundBooks(books) {
  13164. }
  13165. function failure(reason) {
  13166. }
  13167. findAuthor(function(author, err){
  13168. if (err) {
  13169. failure(err);
  13170. // failure
  13171. } else {
  13172. try {
  13173. findBoooksByAuthor(author, function(books, err) {
  13174. if (err) {
  13175. failure(err);
  13176. } else {
  13177. try {
  13178. foundBooks(books);
  13179. } catch(reason) {
  13180. failure(reason);
  13181. }
  13182. }
  13183. });
  13184. } catch(error) {
  13185. failure(err);
  13186. }
  13187. // success
  13188. }
  13189. });
  13190. ```
  13191. Promise Example;
  13192. ```javascript
  13193. findAuthor().
  13194. then(findBooksByAuthor).
  13195. then(function(books){
  13196. // found books
  13197. }).catch(function(reason){
  13198. // something went wrong
  13199. });
  13200. ```
  13201. @method then
  13202. @param {Function} onFulfilled
  13203. @param {Function} onRejected
  13204. Useful for tooling.
  13205. @return {Promise}
  13206. */
  13207. then: function(onFulfillment, onRejection) {
  13208. var parent = this;
  13209. var state = parent._state;
  13210. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  13211. return this;
  13212. }
  13213. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  13214. var result = parent._result;
  13215. if (state) {
  13216. var callback = arguments[state - 1];
  13217. lib$es6$promise$asap$$asap(function(){
  13218. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  13219. });
  13220. } else {
  13221. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  13222. }
  13223. return child;
  13224. },
  13225. /**
  13226. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  13227. as the catch block of a try/catch statement.
  13228. ```js
  13229. function findAuthor(){
  13230. throw new Error('couldn't find that author');
  13231. }
  13232. // synchronous
  13233. try {
  13234. findAuthor();
  13235. } catch(reason) {
  13236. // something went wrong
  13237. }
  13238. // async with promises
  13239. findAuthor().catch(function(reason){
  13240. // something went wrong
  13241. });
  13242. ```
  13243. @method catch
  13244. @param {Function} onRejection
  13245. Useful for tooling.
  13246. @return {Promise}
  13247. */
  13248. 'catch': function(onRejection) {
  13249. return this.then(null, onRejection);
  13250. }
  13251. };
  13252. function lib$es6$promise$polyfill$$polyfill() {
  13253. var local;
  13254. if (typeof global !== 'undefined') {
  13255. local = global;
  13256. } else if (typeof self !== 'undefined') {
  13257. local = self;
  13258. } else {
  13259. try {
  13260. local = Function('return this')();
  13261. } catch (e) {
  13262. throw new Error('polyfill failed because global object is unavailable in this environment');
  13263. }
  13264. }
  13265. var P = local.Promise;
  13266. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  13267. return;
  13268. }
  13269. local.Promise = lib$es6$promise$promise$$default;
  13270. }
  13271. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  13272. var lib$es6$promise$umd$$ES6Promise = {
  13273. 'Promise': lib$es6$promise$promise$$default,
  13274. 'polyfill': lib$es6$promise$polyfill$$default
  13275. };
  13276. /* global define:true module:true window: true */
  13277. if (typeof define === 'function' && define['amd']) {
  13278. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  13279. } else if (typeof module !== 'undefined' && module['exports']) {
  13280. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  13281. } else if (typeof this !== 'undefined') {
  13282. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  13283. }
  13284. lib$es6$promise$polyfill$$default();
  13285. }).call(this);
  13286. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13287. },{"_process":45}],47:[function(require,module,exports){
  13288. /* Copyright @ 2015 Atlassian Pty Ltd
  13289. *
  13290. * Licensed under the Apache License, Version 2.0 (the "License");
  13291. * you may not use this file except in compliance with the License.
  13292. * You may obtain a copy of the License at
  13293. *
  13294. * http://www.apache.org/licenses/LICENSE-2.0
  13295. *
  13296. * Unless required by applicable law or agreed to in writing, software
  13297. * distributed under the License is distributed on an "AS IS" BASIS,
  13298. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13299. * See the License for the specific language governing permissions and
  13300. * limitations under the License.
  13301. */
  13302. /**
  13303. * Ordered log levels.
  13304. */
  13305. var levels = {
  13306. "trace": 0,
  13307. "debug": 1,
  13308. "info": 2,
  13309. "log": 3,
  13310. "warn": 4,
  13311. "error": 5
  13312. };
  13313. /**
  13314. * Parses Error's object stack trace and extracts information about the last
  13315. * caller before the log method was called.
  13316. * @returns JS object with info about the caller - method name, file location,
  13317. * line and column.
  13318. */
  13319. function getCallerInfo() {
  13320. var callerInfo = {
  13321. methodName: "",
  13322. fileLocation: "",
  13323. line: null,
  13324. column: null
  13325. };
  13326. //gets the part of the stack without the logger wrappers
  13327. var error = new Error();
  13328. var stack = error.stack? error.stack.split("\n") : [];
  13329. if(!stack || stack.length < 1) {
  13330. return callerInfo;
  13331. }
  13332. var m = null;
  13333. if(stack[3]) {
  13334. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  13335. }
  13336. if(!m || m.length <= 4) {
  13337. //Firefox && Safari
  13338. if(stack[2].indexOf("log@") === 0){
  13339. //Safari
  13340. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  13341. } else {
  13342. //Firefox
  13343. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  13344. }
  13345. return callerInfo;
  13346. }
  13347. callerInfo.methodName = m[1];
  13348. callerInfo.fileLocation = m[2];
  13349. callerInfo.line = m[3];
  13350. callerInfo.column = m[4];
  13351. return callerInfo;
  13352. }
  13353. /**
  13354. * Logs messages using the transports and level from the logger.
  13355. * @param logger a logger instance.
  13356. * @param level the log level of the message. See the levels variable.
  13357. * @param arguments array with arguments that will be logged.
  13358. */
  13359. function log() {
  13360. var logger = arguments[0], level = arguments[1],
  13361. args = Array.prototype.slice.call(arguments, 2);
  13362. if(levels[level] <= logger.level) {
  13363. return;
  13364. }
  13365. var callerInfo = getCallerInfo();
  13366. for(var i = 0; i < logger.transports.length; i++) {
  13367. var t = logger.transports[i];
  13368. var l = t[level];
  13369. if(l && typeof(l) === "function") {
  13370. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  13371. .apply(t, args);
  13372. }
  13373. }
  13374. }
  13375. /**
  13376. *
  13377. * Constructs new logger object.
  13378. * @param level the logging level for the new logger
  13379. * @param id optional identifier for the logger instance.
  13380. * @param transports optional list of handlers(objects) for the logs.
  13381. * The handlers must support - log, warn, error, debug, info, trace.
  13382. * @param format optional (NOT implemented) string.
  13383. */
  13384. function Logger(level, id, transports, format) {
  13385. this.id = id;
  13386. this.format = format;
  13387. if(!this.transports) {
  13388. this.transports = [];
  13389. this.transports.push(Logger.consoleTransport);
  13390. }
  13391. this.level = levels[level];
  13392. var methods = Object.keys(levels);
  13393. for(var i = 0; i < methods.length; i++){
  13394. this[methods[i]] =
  13395. log.bind(null, this, methods[i]);
  13396. }
  13397. }
  13398. /**
  13399. * Sets the log level for the logger.
  13400. * @param level the new log level.
  13401. */
  13402. Logger.prototype.setLevel = function (level) {
  13403. this.level = levels[level];
  13404. };
  13405. module.exports = Logger;
  13406. /**
  13407. * The default transport - console
  13408. */
  13409. Logger.consoleTransport = console;
  13410. /**
  13411. * Enum for the supported log levels.
  13412. */
  13413. Logger.levels = {
  13414. TRACE: "trace",
  13415. DEBUG: "debug",
  13416. INFO: "info",
  13417. LOG: "log",
  13418. WARN: "warn",
  13419. ERROR: "error"
  13420. };
  13421. },{}],48:[function(require,module,exports){
  13422. /* Copyright @ 2015 Atlassian Pty Ltd
  13423. *
  13424. * Licensed under the Apache License, Version 2.0 (the "License");
  13425. * you may not use this file except in compliance with the License.
  13426. * You may obtain a copy of the License at
  13427. *
  13428. * http://www.apache.org/licenses/LICENSE-2.0
  13429. *
  13430. * Unless required by applicable law or agreed to in writing, software
  13431. * distributed under the License is distributed on an "AS IS" BASIS,
  13432. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13433. * See the License for the specific language governing permissions and
  13434. * limitations under the License.
  13435. */
  13436. var Logger = require("./Logger");
  13437. /**
  13438. * Map with the created loggers with ID.
  13439. */
  13440. var idLoggers = {};
  13441. /**
  13442. * Array with the loggers without id.
  13443. */
  13444. var loggers = [];
  13445. /**
  13446. * Log level for the lbrary.
  13447. */
  13448. var curLevel = Logger.levels.TRACE;
  13449. module.exports = {
  13450. /**
  13451. * Creates new logger.
  13452. * @arguments the same as Logger constructor
  13453. */
  13454. getLogger: function(id, transports, format) {
  13455. var logger = new Logger(curLevel, id, transports, format);
  13456. if(id) {
  13457. idLoggers[id] = idLoggers[id] || [];
  13458. idLoggers[id].push(logger);
  13459. } else {
  13460. loggers.push(logger);
  13461. }
  13462. return logger;
  13463. },
  13464. /**
  13465. * Changes the log level for the existing loggers by id.
  13466. * @param level the new log level.
  13467. * @param id if specified the level will be changed only for loggers with the
  13468. * same id. Otherwise the operation will affect all loggers that don't
  13469. * have id.
  13470. */
  13471. setLogLevelById: function(level, id) {
  13472. var l = id? (idLoggers[id] || []) : loggers;
  13473. for(var i = 0; i < l.length; i++) {
  13474. l[i].setLevel(level);
  13475. }
  13476. },
  13477. /**
  13478. * Changes the log level for all existing loggers.
  13479. * @param level the new log level.
  13480. */
  13481. setLogLevel: function (level) {
  13482. curLevel = level;
  13483. var i = 0;
  13484. for(; i < loggers.length; i++) {
  13485. loggers[i].setLevel(level);
  13486. }
  13487. for(var id in idLoggers) {
  13488. var l = idLoggers[id] || [];
  13489. for(i = 0; i < l.length; i++) {
  13490. l[i].setLevel(level);
  13491. }
  13492. }
  13493. },
  13494. /**
  13495. * The supported log levels.
  13496. */
  13497. levels: Logger.levels
  13498. };
  13499. },{"./Logger":47}],49:[function(require,module,exports){
  13500. // Top level file is just a mixin of submodules & constants
  13501. 'use strict';
  13502. var assign = require('./lib/utils/common').assign;
  13503. var deflate = require('./lib/deflate');
  13504. var inflate = require('./lib/inflate');
  13505. var constants = require('./lib/zlib/constants');
  13506. var pako = {};
  13507. assign(pako, deflate, inflate, constants);
  13508. module.exports = pako;
  13509. },{"./lib/deflate":50,"./lib/inflate":51,"./lib/utils/common":52,"./lib/zlib/constants":55}],50:[function(require,module,exports){
  13510. 'use strict';
  13511. var zlib_deflate = require('./zlib/deflate.js');
  13512. var utils = require('./utils/common');
  13513. var strings = require('./utils/strings');
  13514. var msg = require('./zlib/messages');
  13515. var zstream = require('./zlib/zstream');
  13516. var toString = Object.prototype.toString;
  13517. /* Public constants ==========================================================*/
  13518. /* ===========================================================================*/
  13519. var Z_NO_FLUSH = 0;
  13520. var Z_FINISH = 4;
  13521. var Z_OK = 0;
  13522. var Z_STREAM_END = 1;
  13523. var Z_SYNC_FLUSH = 2;
  13524. var Z_DEFAULT_COMPRESSION = -1;
  13525. var Z_DEFAULT_STRATEGY = 0;
  13526. var Z_DEFLATED = 8;
  13527. /* ===========================================================================*/
  13528. /**
  13529. * class Deflate
  13530. *
  13531. * Generic JS-style wrapper for zlib calls. If you don't need
  13532. * streaming behaviour - use more simple functions: [[deflate]],
  13533. * [[deflateRaw]] and [[gzip]].
  13534. **/
  13535. /* internal
  13536. * Deflate.chunks -> Array
  13537. *
  13538. * Chunks of output data, if [[Deflate#onData]] not overriden.
  13539. **/
  13540. /**
  13541. * Deflate.result -> Uint8Array|Array
  13542. *
  13543. * Compressed result, generated by default [[Deflate#onData]]
  13544. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  13545. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  13546. * push a chunk with explicit flush (call [[Deflate#push]] with
  13547. * `Z_SYNC_FLUSH` param).
  13548. **/
  13549. /**
  13550. * Deflate.err -> Number
  13551. *
  13552. * Error code after deflate finished. 0 (Z_OK) on success.
  13553. * You will not need it in real life, because deflate errors
  13554. * are possible only on wrong options or bad `onData` / `onEnd`
  13555. * custom handlers.
  13556. **/
  13557. /**
  13558. * Deflate.msg -> String
  13559. *
  13560. * Error message, if [[Deflate.err]] != 0
  13561. **/
  13562. /**
  13563. * new Deflate(options)
  13564. * - options (Object): zlib deflate options.
  13565. *
  13566. * Creates new deflator instance with specified params. Throws exception
  13567. * on bad params. Supported options:
  13568. *
  13569. * - `level`
  13570. * - `windowBits`
  13571. * - `memLevel`
  13572. * - `strategy`
  13573. *
  13574. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13575. * for more information on these.
  13576. *
  13577. * Additional options, for internal needs:
  13578. *
  13579. * - `chunkSize` - size of generated data chunks (16K by default)
  13580. * - `raw` (Boolean) - do raw deflate
  13581. * - `gzip` (Boolean) - create gzip wrapper
  13582. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13583. * (each char code [0..255])
  13584. * - `header` (Object) - custom header for gzip
  13585. * - `text` (Boolean) - true if compressed data believed to be text
  13586. * - `time` (Number) - modification time, unix timestamp
  13587. * - `os` (Number) - operation system code
  13588. * - `extra` (Array) - array of bytes with extra data (max 65536)
  13589. * - `name` (String) - file name (binary string)
  13590. * - `comment` (String) - comment (binary string)
  13591. * - `hcrc` (Boolean) - true if header crc should be added
  13592. *
  13593. * ##### Example:
  13594. *
  13595. * ```javascript
  13596. * var pako = require('pako')
  13597. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13598. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13599. *
  13600. * var deflate = new pako.Deflate({ level: 3});
  13601. *
  13602. * deflate.push(chunk1, false);
  13603. * deflate.push(chunk2, true); // true -> last chunk
  13604. *
  13605. * if (deflate.err) { throw new Error(deflate.err); }
  13606. *
  13607. * console.log(deflate.result);
  13608. * ```
  13609. **/
  13610. var Deflate = function(options) {
  13611. this.options = utils.assign({
  13612. level: Z_DEFAULT_COMPRESSION,
  13613. method: Z_DEFLATED,
  13614. chunkSize: 16384,
  13615. windowBits: 15,
  13616. memLevel: 8,
  13617. strategy: Z_DEFAULT_STRATEGY,
  13618. to: ''
  13619. }, options || {});
  13620. var opt = this.options;
  13621. if (opt.raw && (opt.windowBits > 0)) {
  13622. opt.windowBits = -opt.windowBits;
  13623. }
  13624. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  13625. opt.windowBits += 16;
  13626. }
  13627. this.err = 0; // error code, if happens (0 = Z_OK)
  13628. this.msg = ''; // error message
  13629. this.ended = false; // used to avoid multiple onEnd() calls
  13630. this.chunks = []; // chunks of compressed data
  13631. this.strm = new zstream();
  13632. this.strm.avail_out = 0;
  13633. var status = zlib_deflate.deflateInit2(
  13634. this.strm,
  13635. opt.level,
  13636. opt.method,
  13637. opt.windowBits,
  13638. opt.memLevel,
  13639. opt.strategy
  13640. );
  13641. if (status !== Z_OK) {
  13642. throw new Error(msg[status]);
  13643. }
  13644. if (opt.header) {
  13645. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  13646. }
  13647. };
  13648. /**
  13649. * Deflate#push(data[, mode]) -> Boolean
  13650. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  13651. * converted to utf8 byte sequence.
  13652. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13653. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13654. *
  13655. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  13656. * new compressed chunks. Returns `true` on success. The last data block must have
  13657. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13658. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13659. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  13660. *
  13661. * On fail call [[Deflate#onEnd]] with error code and return false.
  13662. *
  13663. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13664. * array format is detected automatically). Also, don't skip last param and always
  13665. * use the same type in your code (boolean or number). That will improve JS speed.
  13666. *
  13667. * For regular `Array`-s make sure all elements are [0..255].
  13668. *
  13669. * ##### Example
  13670. *
  13671. * ```javascript
  13672. * push(chunk, false); // push one of data chunks
  13673. * ...
  13674. * push(chunk, true); // push last chunk
  13675. * ```
  13676. **/
  13677. Deflate.prototype.push = function(data, mode) {
  13678. var strm = this.strm;
  13679. var chunkSize = this.options.chunkSize;
  13680. var status, _mode;
  13681. if (this.ended) { return false; }
  13682. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  13683. // Convert data if needed
  13684. if (typeof data === 'string') {
  13685. // If we need to compress text, change encoding to utf8.
  13686. strm.input = strings.string2buf(data);
  13687. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13688. strm.input = new Uint8Array(data);
  13689. } else {
  13690. strm.input = data;
  13691. }
  13692. strm.next_in = 0;
  13693. strm.avail_in = strm.input.length;
  13694. do {
  13695. if (strm.avail_out === 0) {
  13696. strm.output = new utils.Buf8(chunkSize);
  13697. strm.next_out = 0;
  13698. strm.avail_out = chunkSize;
  13699. }
  13700. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  13701. if (status !== Z_STREAM_END && status !== Z_OK) {
  13702. this.onEnd(status);
  13703. this.ended = true;
  13704. return false;
  13705. }
  13706. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  13707. if (this.options.to === 'string') {
  13708. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  13709. } else {
  13710. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13711. }
  13712. }
  13713. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  13714. // Finalize on the last chunk.
  13715. if (_mode === Z_FINISH) {
  13716. status = zlib_deflate.deflateEnd(this.strm);
  13717. this.onEnd(status);
  13718. this.ended = true;
  13719. return status === Z_OK;
  13720. }
  13721. // callback interim results if Z_SYNC_FLUSH.
  13722. if (_mode === Z_SYNC_FLUSH) {
  13723. this.onEnd(Z_OK);
  13724. strm.avail_out = 0;
  13725. return true;
  13726. }
  13727. return true;
  13728. };
  13729. /**
  13730. * Deflate#onData(chunk) -> Void
  13731. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13732. * on js engine support. When string output requested, each chunk
  13733. * will be string.
  13734. *
  13735. * By default, stores data blocks in `chunks[]` property and glue
  13736. * those in `onEnd`. Override this handler, if you need another behaviour.
  13737. **/
  13738. Deflate.prototype.onData = function(chunk) {
  13739. this.chunks.push(chunk);
  13740. };
  13741. /**
  13742. * Deflate#onEnd(status) -> Void
  13743. * - status (Number): deflate status. 0 (Z_OK) on success,
  13744. * other if not.
  13745. *
  13746. * Called once after you tell deflate that the input stream is
  13747. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13748. * or if an error happened. By default - join collected chunks,
  13749. * free memory and fill `results` / `err` properties.
  13750. **/
  13751. Deflate.prototype.onEnd = function(status) {
  13752. // On success - join
  13753. if (status === Z_OK) {
  13754. if (this.options.to === 'string') {
  13755. this.result = this.chunks.join('');
  13756. } else {
  13757. this.result = utils.flattenChunks(this.chunks);
  13758. }
  13759. }
  13760. this.chunks = [];
  13761. this.err = status;
  13762. this.msg = this.strm.msg;
  13763. };
  13764. /**
  13765. * deflate(data[, options]) -> Uint8Array|Array|String
  13766. * - data (Uint8Array|Array|String): input data to compress.
  13767. * - options (Object): zlib deflate options.
  13768. *
  13769. * Compress `data` with deflate alrorythm and `options`.
  13770. *
  13771. * Supported options are:
  13772. *
  13773. * - level
  13774. * - windowBits
  13775. * - memLevel
  13776. * - strategy
  13777. *
  13778. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13779. * for more information on these.
  13780. *
  13781. * Sugar (options):
  13782. *
  13783. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13784. * negative windowBits implicitly.
  13785. * - `to` (String) - if equal to 'string', then result will be "binary string"
  13786. * (each char code [0..255])
  13787. *
  13788. * ##### Example:
  13789. *
  13790. * ```javascript
  13791. * var pako = require('pako')
  13792. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  13793. *
  13794. * console.log(pako.deflate(data));
  13795. * ```
  13796. **/
  13797. function deflate(input, options) {
  13798. var deflator = new Deflate(options);
  13799. deflator.push(input, true);
  13800. // That will never happens, if you don't cheat with options :)
  13801. if (deflator.err) { throw deflator.msg; }
  13802. return deflator.result;
  13803. }
  13804. /**
  13805. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13806. * - data (Uint8Array|Array|String): input data to compress.
  13807. * - options (Object): zlib deflate options.
  13808. *
  13809. * The same as [[deflate]], but creates raw data, without wrapper
  13810. * (header and adler32 crc).
  13811. **/
  13812. function deflateRaw(input, options) {
  13813. options = options || {};
  13814. options.raw = true;
  13815. return deflate(input, options);
  13816. }
  13817. /**
  13818. * gzip(data[, options]) -> Uint8Array|Array|String
  13819. * - data (Uint8Array|Array|String): input data to compress.
  13820. * - options (Object): zlib deflate options.
  13821. *
  13822. * The same as [[deflate]], but create gzip wrapper instead of
  13823. * deflate one.
  13824. **/
  13825. function gzip(input, options) {
  13826. options = options || {};
  13827. options.gzip = true;
  13828. return deflate(input, options);
  13829. }
  13830. exports.Deflate = Deflate;
  13831. exports.deflate = deflate;
  13832. exports.deflateRaw = deflateRaw;
  13833. exports.gzip = gzip;
  13834. },{"./utils/common":52,"./utils/strings":53,"./zlib/deflate.js":57,"./zlib/messages":62,"./zlib/zstream":64}],51:[function(require,module,exports){
  13835. 'use strict';
  13836. var zlib_inflate = require('./zlib/inflate.js');
  13837. var utils = require('./utils/common');
  13838. var strings = require('./utils/strings');
  13839. var c = require('./zlib/constants');
  13840. var msg = require('./zlib/messages');
  13841. var zstream = require('./zlib/zstream');
  13842. var gzheader = require('./zlib/gzheader');
  13843. var toString = Object.prototype.toString;
  13844. /**
  13845. * class Inflate
  13846. *
  13847. * Generic JS-style wrapper for zlib calls. If you don't need
  13848. * streaming behaviour - use more simple functions: [[inflate]]
  13849. * and [[inflateRaw]].
  13850. **/
  13851. /* internal
  13852. * inflate.chunks -> Array
  13853. *
  13854. * Chunks of output data, if [[Inflate#onData]] not overriden.
  13855. **/
  13856. /**
  13857. * Inflate.result -> Uint8Array|Array|String
  13858. *
  13859. * Uncompressed result, generated by default [[Inflate#onData]]
  13860. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13861. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13862. * push a chunk with explicit flush (call [[Inflate#push]] with
  13863. * `Z_SYNC_FLUSH` param).
  13864. **/
  13865. /**
  13866. * Inflate.err -> Number
  13867. *
  13868. * Error code after inflate finished. 0 (Z_OK) on success.
  13869. * Should be checked if broken data possible.
  13870. **/
  13871. /**
  13872. * Inflate.msg -> String
  13873. *
  13874. * Error message, if [[Inflate.err]] != 0
  13875. **/
  13876. /**
  13877. * new Inflate(options)
  13878. * - options (Object): zlib inflate options.
  13879. *
  13880. * Creates new inflator instance with specified params. Throws exception
  13881. * on bad params. Supported options:
  13882. *
  13883. * - `windowBits`
  13884. *
  13885. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13886. * for more information on these.
  13887. *
  13888. * Additional options, for internal needs:
  13889. *
  13890. * - `chunkSize` - size of generated data chunks (16K by default)
  13891. * - `raw` (Boolean) - do raw inflate
  13892. * - `to` (String) - if equal to 'string', then result will be converted
  13893. * from utf8 to utf16 (javascript) string. When string output requested,
  13894. * chunk length can differ from `chunkSize`, depending on content.
  13895. *
  13896. * By default, when no options set, autodetect deflate/gzip data format via
  13897. * wrapper header.
  13898. *
  13899. * ##### Example:
  13900. *
  13901. * ```javascript
  13902. * var pako = require('pako')
  13903. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13904. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13905. *
  13906. * var inflate = new pako.Inflate({ level: 3});
  13907. *
  13908. * inflate.push(chunk1, false);
  13909. * inflate.push(chunk2, true); // true -> last chunk
  13910. *
  13911. * if (inflate.err) { throw new Error(inflate.err); }
  13912. *
  13913. * console.log(inflate.result);
  13914. * ```
  13915. **/
  13916. var Inflate = function(options) {
  13917. this.options = utils.assign({
  13918. chunkSize: 16384,
  13919. windowBits: 0,
  13920. to: ''
  13921. }, options || {});
  13922. var opt = this.options;
  13923. // Force window size for `raw` data, if not set directly,
  13924. // because we have no header for autodetect.
  13925. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  13926. opt.windowBits = -opt.windowBits;
  13927. if (opt.windowBits === 0) { opt.windowBits = -15; }
  13928. }
  13929. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  13930. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  13931. !(options && options.windowBits)) {
  13932. opt.windowBits += 32;
  13933. }
  13934. // Gzip header has no info about windows size, we can do autodetect only
  13935. // for deflate. So, if window size not set, force it to max when gzip possible
  13936. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  13937. // bit 3 (16) -> gzipped data
  13938. // bit 4 (32) -> autodetect gzip/deflate
  13939. if ((opt.windowBits & 15) === 0) {
  13940. opt.windowBits |= 15;
  13941. }
  13942. }
  13943. this.err = 0; // error code, if happens (0 = Z_OK)
  13944. this.msg = ''; // error message
  13945. this.ended = false; // used to avoid multiple onEnd() calls
  13946. this.chunks = []; // chunks of compressed data
  13947. this.strm = new zstream();
  13948. this.strm.avail_out = 0;
  13949. var status = zlib_inflate.inflateInit2(
  13950. this.strm,
  13951. opt.windowBits
  13952. );
  13953. if (status !== c.Z_OK) {
  13954. throw new Error(msg[status]);
  13955. }
  13956. this.header = new gzheader();
  13957. zlib_inflate.inflateGetHeader(this.strm, this.header);
  13958. };
  13959. /**
  13960. * Inflate#push(data[, mode]) -> Boolean
  13961. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  13962. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13963. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13964. *
  13965. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  13966. * new output chunks. Returns `true` on success. The last data block must have
  13967. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13968. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13969. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13970. *
  13971. * On fail call [[Inflate#onEnd]] with error code and return false.
  13972. *
  13973. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13974. * format is detected automatically). Also, don't skip last param and always
  13975. * use the same type in your code (boolean or number). That will improve JS speed.
  13976. *
  13977. * For regular `Array`-s make sure all elements are [0..255].
  13978. *
  13979. * ##### Example
  13980. *
  13981. * ```javascript
  13982. * push(chunk, false); // push one of data chunks
  13983. * ...
  13984. * push(chunk, true); // push last chunk
  13985. * ```
  13986. **/
  13987. Inflate.prototype.push = function(data, mode) {
  13988. var strm = this.strm;
  13989. var chunkSize = this.options.chunkSize;
  13990. var status, _mode;
  13991. var next_out_utf8, tail, utf8str;
  13992. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13993. // when we check that all output data was flushed.
  13994. var allowBufError = false;
  13995. if (this.ended) { return false; }
  13996. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13997. // Convert data if needed
  13998. if (typeof data === 'string') {
  13999. // Only binary strings can be decompressed on practice
  14000. strm.input = strings.binstring2buf(data);
  14001. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14002. strm.input = new Uint8Array(data);
  14003. } else {
  14004. strm.input = data;
  14005. }
  14006. strm.next_in = 0;
  14007. strm.avail_in = strm.input.length;
  14008. do {
  14009. if (strm.avail_out === 0) {
  14010. strm.output = new utils.Buf8(chunkSize);
  14011. strm.next_out = 0;
  14012. strm.avail_out = chunkSize;
  14013. }
  14014. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  14015. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  14016. status = c.Z_OK;
  14017. allowBufError = false;
  14018. }
  14019. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  14020. this.onEnd(status);
  14021. this.ended = true;
  14022. return false;
  14023. }
  14024. if (strm.next_out) {
  14025. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  14026. if (this.options.to === 'string') {
  14027. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  14028. tail = strm.next_out - next_out_utf8;
  14029. utf8str = strings.buf2string(strm.output, next_out_utf8);
  14030. // move tail
  14031. strm.next_out = tail;
  14032. strm.avail_out = chunkSize - tail;
  14033. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  14034. this.onData(utf8str);
  14035. } else {
  14036. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14037. }
  14038. }
  14039. }
  14040. // When no more input data, we should check that internal inflate buffers
  14041. // are flushed. The only way to do it when avail_out = 0 - run one more
  14042. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  14043. // Here we set flag to process this error properly.
  14044. //
  14045. // NOTE. Deflate does not return error in this case and does not needs such
  14046. // logic.
  14047. if (strm.avail_in === 0 && strm.avail_out === 0) {
  14048. allowBufError = true;
  14049. }
  14050. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  14051. if (status === c.Z_STREAM_END) {
  14052. _mode = c.Z_FINISH;
  14053. }
  14054. // Finalize on the last chunk.
  14055. if (_mode === c.Z_FINISH) {
  14056. status = zlib_inflate.inflateEnd(this.strm);
  14057. this.onEnd(status);
  14058. this.ended = true;
  14059. return status === c.Z_OK;
  14060. }
  14061. // callback interim results if Z_SYNC_FLUSH.
  14062. if (_mode === c.Z_SYNC_FLUSH) {
  14063. this.onEnd(c.Z_OK);
  14064. strm.avail_out = 0;
  14065. return true;
  14066. }
  14067. return true;
  14068. };
  14069. /**
  14070. * Inflate#onData(chunk) -> Void
  14071. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14072. * on js engine support. When string output requested, each chunk
  14073. * will be string.
  14074. *
  14075. * By default, stores data blocks in `chunks[]` property and glue
  14076. * those in `onEnd`. Override this handler, if you need another behaviour.
  14077. **/
  14078. Inflate.prototype.onData = function(chunk) {
  14079. this.chunks.push(chunk);
  14080. };
  14081. /**
  14082. * Inflate#onEnd(status) -> Void
  14083. * - status (Number): inflate status. 0 (Z_OK) on success,
  14084. * other if not.
  14085. *
  14086. * Called either after you tell inflate that the input stream is
  14087. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14088. * or if an error happened. By default - join collected chunks,
  14089. * free memory and fill `results` / `err` properties.
  14090. **/
  14091. Inflate.prototype.onEnd = function(status) {
  14092. // On success - join
  14093. if (status === c.Z_OK) {
  14094. if (this.options.to === 'string') {
  14095. // Glue & convert here, until we teach pako to send
  14096. // utf8 alligned strings to onData
  14097. this.result = this.chunks.join('');
  14098. } else {
  14099. this.result = utils.flattenChunks(this.chunks);
  14100. }
  14101. }
  14102. this.chunks = [];
  14103. this.err = status;
  14104. this.msg = this.strm.msg;
  14105. };
  14106. /**
  14107. * inflate(data[, options]) -> Uint8Array|Array|String
  14108. * - data (Uint8Array|Array|String): input data to decompress.
  14109. * - options (Object): zlib inflate options.
  14110. *
  14111. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  14112. * format via wrapper header by default. That's why we don't provide
  14113. * separate `ungzip` method.
  14114. *
  14115. * Supported options are:
  14116. *
  14117. * - windowBits
  14118. *
  14119. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14120. * for more information.
  14121. *
  14122. * Sugar (options):
  14123. *
  14124. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14125. * negative windowBits implicitly.
  14126. * - `to` (String) - if equal to 'string', then result will be converted
  14127. * from utf8 to utf16 (javascript) string. When string output requested,
  14128. * chunk length can differ from `chunkSize`, depending on content.
  14129. *
  14130. *
  14131. * ##### Example:
  14132. *
  14133. * ```javascript
  14134. * var pako = require('pako')
  14135. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  14136. * , output;
  14137. *
  14138. * try {
  14139. * output = pako.inflate(input);
  14140. * } catch (err)
  14141. * console.log(err);
  14142. * }
  14143. * ```
  14144. **/
  14145. function inflate(input, options) {
  14146. var inflator = new Inflate(options);
  14147. inflator.push(input, true);
  14148. // That will never happens, if you don't cheat with options :)
  14149. if (inflator.err) { throw inflator.msg; }
  14150. return inflator.result;
  14151. }
  14152. /**
  14153. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  14154. * - data (Uint8Array|Array|String): input data to decompress.
  14155. * - options (Object): zlib inflate options.
  14156. *
  14157. * The same as [[inflate]], but creates raw data, without wrapper
  14158. * (header and adler32 crc).
  14159. **/
  14160. function inflateRaw(input, options) {
  14161. options = options || {};
  14162. options.raw = true;
  14163. return inflate(input, options);
  14164. }
  14165. /**
  14166. * ungzip(data[, options]) -> Uint8Array|Array|String
  14167. * - data (Uint8Array|Array|String): input data to decompress.
  14168. * - options (Object): zlib inflate options.
  14169. *
  14170. * Just shortcut to [[inflate]], because it autodetects format
  14171. * by header.content. Done for convenience.
  14172. **/
  14173. exports.Inflate = Inflate;
  14174. exports.inflate = inflate;
  14175. exports.inflateRaw = inflateRaw;
  14176. exports.ungzip = inflate;
  14177. },{"./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){
  14178. 'use strict';
  14179. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  14180. (typeof Uint16Array !== 'undefined') &&
  14181. (typeof Int32Array !== 'undefined');
  14182. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  14183. var sources = Array.prototype.slice.call(arguments, 1);
  14184. while (sources.length) {
  14185. var source = sources.shift();
  14186. if (!source) { continue; }
  14187. if (typeof source !== 'object') {
  14188. throw new TypeError(source + 'must be non-object');
  14189. }
  14190. for (var p in source) {
  14191. if (source.hasOwnProperty(p)) {
  14192. obj[p] = source[p];
  14193. }
  14194. }
  14195. }
  14196. return obj;
  14197. };
  14198. // reduce buffer size, avoiding mem copy
  14199. exports.shrinkBuf = function (buf, size) {
  14200. if (buf.length === size) { return buf; }
  14201. if (buf.subarray) { return buf.subarray(0, size); }
  14202. buf.length = size;
  14203. return buf;
  14204. };
  14205. var fnTyped = {
  14206. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14207. if (src.subarray && dest.subarray) {
  14208. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  14209. return;
  14210. }
  14211. // Fallback to ordinary array
  14212. for (var i=0; i<len; i++) {
  14213. dest[dest_offs + i] = src[src_offs + i];
  14214. }
  14215. },
  14216. // Join array of chunks to single array.
  14217. flattenChunks: function(chunks) {
  14218. var i, l, len, pos, chunk, result;
  14219. // calculate data length
  14220. len = 0;
  14221. for (i=0, l=chunks.length; i<l; i++) {
  14222. len += chunks[i].length;
  14223. }
  14224. // join chunks
  14225. result = new Uint8Array(len);
  14226. pos = 0;
  14227. for (i=0, l=chunks.length; i<l; i++) {
  14228. chunk = chunks[i];
  14229. result.set(chunk, pos);
  14230. pos += chunk.length;
  14231. }
  14232. return result;
  14233. }
  14234. };
  14235. var fnUntyped = {
  14236. arraySet: function (dest, src, src_offs, len, dest_offs) {
  14237. for (var i=0; i<len; i++) {
  14238. dest[dest_offs + i] = src[src_offs + i];
  14239. }
  14240. },
  14241. // Join array of chunks to single array.
  14242. flattenChunks: function(chunks) {
  14243. return [].concat.apply([], chunks);
  14244. }
  14245. };
  14246. // Enable/Disable typed arrays use, for testing
  14247. //
  14248. exports.setTyped = function (on) {
  14249. if (on) {
  14250. exports.Buf8 = Uint8Array;
  14251. exports.Buf16 = Uint16Array;
  14252. exports.Buf32 = Int32Array;
  14253. exports.assign(exports, fnTyped);
  14254. } else {
  14255. exports.Buf8 = Array;
  14256. exports.Buf16 = Array;
  14257. exports.Buf32 = Array;
  14258. exports.assign(exports, fnUntyped);
  14259. }
  14260. };
  14261. exports.setTyped(TYPED_OK);
  14262. },{}],53:[function(require,module,exports){
  14263. // String encode/decode helpers
  14264. 'use strict';
  14265. var utils = require('./common');
  14266. // Quick check if we can use fast array to bin string conversion
  14267. //
  14268. // - apply(Array) can fail on Android 2.2
  14269. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  14270. //
  14271. var STR_APPLY_OK = true;
  14272. var STR_APPLY_UIA_OK = true;
  14273. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  14274. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  14275. // Table with utf8 lengths (calculated by first byte of sequence)
  14276. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  14277. // because max possible codepoint is 0x10ffff
  14278. var _utf8len = new utils.Buf8(256);
  14279. for (var q=0; q<256; q++) {
  14280. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  14281. }
  14282. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  14283. // convert string to array (typed, when possible)
  14284. exports.string2buf = function (str) {
  14285. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  14286. // count binary size
  14287. for (m_pos = 0; m_pos < str_len; m_pos++) {
  14288. c = str.charCodeAt(m_pos);
  14289. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14290. c2 = str.charCodeAt(m_pos+1);
  14291. if ((c2 & 0xfc00) === 0xdc00) {
  14292. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14293. m_pos++;
  14294. }
  14295. }
  14296. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  14297. }
  14298. // allocate buffer
  14299. buf = new utils.Buf8(buf_len);
  14300. // convert
  14301. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  14302. c = str.charCodeAt(m_pos);
  14303. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  14304. c2 = str.charCodeAt(m_pos+1);
  14305. if ((c2 & 0xfc00) === 0xdc00) {
  14306. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  14307. m_pos++;
  14308. }
  14309. }
  14310. if (c < 0x80) {
  14311. /* one byte */
  14312. buf[i++] = c;
  14313. } else if (c < 0x800) {
  14314. /* two bytes */
  14315. buf[i++] = 0xC0 | (c >>> 6);
  14316. buf[i++] = 0x80 | (c & 0x3f);
  14317. } else if (c < 0x10000) {
  14318. /* three bytes */
  14319. buf[i++] = 0xE0 | (c >>> 12);
  14320. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14321. buf[i++] = 0x80 | (c & 0x3f);
  14322. } else {
  14323. /* four bytes */
  14324. buf[i++] = 0xf0 | (c >>> 18);
  14325. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  14326. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  14327. buf[i++] = 0x80 | (c & 0x3f);
  14328. }
  14329. }
  14330. return buf;
  14331. };
  14332. // Helper (used in 2 places)
  14333. function buf2binstring(buf, len) {
  14334. // use fallback for big arrays to avoid stack overflow
  14335. if (len < 65537) {
  14336. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  14337. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  14338. }
  14339. }
  14340. var result = '';
  14341. for (var i=0; i < len; i++) {
  14342. result += String.fromCharCode(buf[i]);
  14343. }
  14344. return result;
  14345. }
  14346. // Convert byte array to binary string
  14347. exports.buf2binstring = function(buf) {
  14348. return buf2binstring(buf, buf.length);
  14349. };
  14350. // Convert binary string (typed, when possible)
  14351. exports.binstring2buf = function(str) {
  14352. var buf = new utils.Buf8(str.length);
  14353. for (var i=0, len=buf.length; i < len; i++) {
  14354. buf[i] = str.charCodeAt(i);
  14355. }
  14356. return buf;
  14357. };
  14358. // convert array to string
  14359. exports.buf2string = function (buf, max) {
  14360. var i, out, c, c_len;
  14361. var len = max || buf.length;
  14362. // Reserve max possible length (2 words per char)
  14363. // NB: by unknown reasons, Array is significantly faster for
  14364. // String.fromCharCode.apply than Uint16Array.
  14365. var utf16buf = new Array(len*2);
  14366. for (out=0, i=0; i<len;) {
  14367. c = buf[i++];
  14368. // quick process ascii
  14369. if (c < 0x80) { utf16buf[out++] = c; continue; }
  14370. c_len = _utf8len[c];
  14371. // skip 5 & 6 byte codes
  14372. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  14373. // apply mask on first byte
  14374. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  14375. // join the rest
  14376. while (c_len > 1 && i < len) {
  14377. c = (c << 6) | (buf[i++] & 0x3f);
  14378. c_len--;
  14379. }
  14380. // terminated by end of string?
  14381. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  14382. if (c < 0x10000) {
  14383. utf16buf[out++] = c;
  14384. } else {
  14385. c -= 0x10000;
  14386. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  14387. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  14388. }
  14389. }
  14390. return buf2binstring(utf16buf, out);
  14391. };
  14392. // Calculate max possible position in utf8 buffer,
  14393. // that will not break sequence. If that's not possible
  14394. // - (very small limits) return max size as is.
  14395. //
  14396. // buf[] - utf8 bytes array
  14397. // max - length limit (mandatory);
  14398. exports.utf8border = function(buf, max) {
  14399. var pos;
  14400. max = max || buf.length;
  14401. if (max > buf.length) { max = buf.length; }
  14402. // go back from last position, until start of sequence found
  14403. pos = max-1;
  14404. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  14405. // Fuckup - very small and broken sequence,
  14406. // return max, because we should return something anyway.
  14407. if (pos < 0) { return max; }
  14408. // If we came to start of buffer - that means vuffer is too small,
  14409. // return max too.
  14410. if (pos === 0) { return max; }
  14411. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  14412. };
  14413. },{"./common":52}],54:[function(require,module,exports){
  14414. 'use strict';
  14415. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  14416. // It doesn't worth to make additional optimizationa as in original.
  14417. // Small size is preferable.
  14418. function adler32(adler, buf, len, pos) {
  14419. var s1 = (adler & 0xffff) |0,
  14420. s2 = ((adler >>> 16) & 0xffff) |0,
  14421. n = 0;
  14422. while (len !== 0) {
  14423. // Set limit ~ twice less than 5552, to keep
  14424. // s2 in 31-bits, because we force signed ints.
  14425. // in other case %= will fail.
  14426. n = len > 2000 ? 2000 : len;
  14427. len -= n;
  14428. do {
  14429. s1 = (s1 + buf[pos++]) |0;
  14430. s2 = (s2 + s1) |0;
  14431. } while (--n);
  14432. s1 %= 65521;
  14433. s2 %= 65521;
  14434. }
  14435. return (s1 | (s2 << 16)) |0;
  14436. }
  14437. module.exports = adler32;
  14438. },{}],55:[function(require,module,exports){
  14439. module.exports = {
  14440. /* Allowed flush values; see deflate() and inflate() below for details */
  14441. Z_NO_FLUSH: 0,
  14442. Z_PARTIAL_FLUSH: 1,
  14443. Z_SYNC_FLUSH: 2,
  14444. Z_FULL_FLUSH: 3,
  14445. Z_FINISH: 4,
  14446. Z_BLOCK: 5,
  14447. Z_TREES: 6,
  14448. /* Return codes for the compression/decompression functions. Negative values
  14449. * are errors, positive values are used for special but normal events.
  14450. */
  14451. Z_OK: 0,
  14452. Z_STREAM_END: 1,
  14453. Z_NEED_DICT: 2,
  14454. Z_ERRNO: -1,
  14455. Z_STREAM_ERROR: -2,
  14456. Z_DATA_ERROR: -3,
  14457. //Z_MEM_ERROR: -4,
  14458. Z_BUF_ERROR: -5,
  14459. //Z_VERSION_ERROR: -6,
  14460. /* compression levels */
  14461. Z_NO_COMPRESSION: 0,
  14462. Z_BEST_SPEED: 1,
  14463. Z_BEST_COMPRESSION: 9,
  14464. Z_DEFAULT_COMPRESSION: -1,
  14465. Z_FILTERED: 1,
  14466. Z_HUFFMAN_ONLY: 2,
  14467. Z_RLE: 3,
  14468. Z_FIXED: 4,
  14469. Z_DEFAULT_STRATEGY: 0,
  14470. /* Possible values of the data_type field (though see inflate()) */
  14471. Z_BINARY: 0,
  14472. Z_TEXT: 1,
  14473. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  14474. Z_UNKNOWN: 2,
  14475. /* The deflate compression method */
  14476. Z_DEFLATED: 8
  14477. //Z_NULL: null // Use -1 or null inline, depending on var type
  14478. };
  14479. },{}],56:[function(require,module,exports){
  14480. 'use strict';
  14481. // Note: we can't get significant speed boost here.
  14482. // So write code to minimize size - no pregenerated tables
  14483. // and array tools dependencies.
  14484. // Use ordinary array, since untyped makes no boost here
  14485. function makeTable() {
  14486. var c, table = [];
  14487. for (var n =0; n < 256; n++) {
  14488. c = n;
  14489. for (var k =0; k < 8; k++) {
  14490. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  14491. }
  14492. table[n] = c;
  14493. }
  14494. return table;
  14495. }
  14496. // Create table on load. Just 255 signed longs. Not a problem.
  14497. var crcTable = makeTable();
  14498. function crc32(crc, buf, len, pos) {
  14499. var t = crcTable,
  14500. end = pos + len;
  14501. crc = crc ^ (-1);
  14502. for (var i = pos; i < end; i++) {
  14503. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  14504. }
  14505. return (crc ^ (-1)); // >>> 0;
  14506. }
  14507. module.exports = crc32;
  14508. },{}],57:[function(require,module,exports){
  14509. 'use strict';
  14510. var utils = require('../utils/common');
  14511. var trees = require('./trees');
  14512. var adler32 = require('./adler32');
  14513. var crc32 = require('./crc32');
  14514. var msg = require('./messages');
  14515. /* Public constants ==========================================================*/
  14516. /* ===========================================================================*/
  14517. /* Allowed flush values; see deflate() and inflate() below for details */
  14518. var Z_NO_FLUSH = 0;
  14519. var Z_PARTIAL_FLUSH = 1;
  14520. //var Z_SYNC_FLUSH = 2;
  14521. var Z_FULL_FLUSH = 3;
  14522. var Z_FINISH = 4;
  14523. var Z_BLOCK = 5;
  14524. //var Z_TREES = 6;
  14525. /* Return codes for the compression/decompression functions. Negative values
  14526. * are errors, positive values are used for special but normal events.
  14527. */
  14528. var Z_OK = 0;
  14529. var Z_STREAM_END = 1;
  14530. //var Z_NEED_DICT = 2;
  14531. //var Z_ERRNO = -1;
  14532. var Z_STREAM_ERROR = -2;
  14533. var Z_DATA_ERROR = -3;
  14534. //var Z_MEM_ERROR = -4;
  14535. var Z_BUF_ERROR = -5;
  14536. //var Z_VERSION_ERROR = -6;
  14537. /* compression levels */
  14538. //var Z_NO_COMPRESSION = 0;
  14539. //var Z_BEST_SPEED = 1;
  14540. //var Z_BEST_COMPRESSION = 9;
  14541. var Z_DEFAULT_COMPRESSION = -1;
  14542. var Z_FILTERED = 1;
  14543. var Z_HUFFMAN_ONLY = 2;
  14544. var Z_RLE = 3;
  14545. var Z_FIXED = 4;
  14546. var Z_DEFAULT_STRATEGY = 0;
  14547. /* Possible values of the data_type field (though see inflate()) */
  14548. //var Z_BINARY = 0;
  14549. //var Z_TEXT = 1;
  14550. //var Z_ASCII = 1; // = Z_TEXT
  14551. var Z_UNKNOWN = 2;
  14552. /* The deflate compression method */
  14553. var Z_DEFLATED = 8;
  14554. /*============================================================================*/
  14555. var MAX_MEM_LEVEL = 9;
  14556. /* Maximum value for memLevel in deflateInit2 */
  14557. var MAX_WBITS = 15;
  14558. /* 32K LZ77 window */
  14559. var DEF_MEM_LEVEL = 8;
  14560. var LENGTH_CODES = 29;
  14561. /* number of length codes, not counting the special END_BLOCK code */
  14562. var LITERALS = 256;
  14563. /* number of literal bytes 0..255 */
  14564. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14565. /* number of Literal or Length codes, including the END_BLOCK code */
  14566. var D_CODES = 30;
  14567. /* number of distance codes */
  14568. var BL_CODES = 19;
  14569. /* number of codes used to transfer the bit lengths */
  14570. var HEAP_SIZE = 2*L_CODES + 1;
  14571. /* maximum heap size */
  14572. var MAX_BITS = 15;
  14573. /* All codes must not exceed MAX_BITS bits */
  14574. var MIN_MATCH = 3;
  14575. var MAX_MATCH = 258;
  14576. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  14577. var PRESET_DICT = 0x20;
  14578. var INIT_STATE = 42;
  14579. var EXTRA_STATE = 69;
  14580. var NAME_STATE = 73;
  14581. var COMMENT_STATE = 91;
  14582. var HCRC_STATE = 103;
  14583. var BUSY_STATE = 113;
  14584. var FINISH_STATE = 666;
  14585. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  14586. var BS_BLOCK_DONE = 2; /* block flush performed */
  14587. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  14588. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  14589. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  14590. function err(strm, errorCode) {
  14591. strm.msg = msg[errorCode];
  14592. return errorCode;
  14593. }
  14594. function rank(f) {
  14595. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  14596. }
  14597. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14598. /* =========================================================================
  14599. * Flush as much pending output as possible. All deflate() output goes
  14600. * through this function so some applications may wish to modify it
  14601. * to avoid allocating a large strm->output buffer and copying into it.
  14602. * (See also read_buf()).
  14603. */
  14604. function flush_pending(strm) {
  14605. var s = strm.state;
  14606. //_tr_flush_bits(s);
  14607. var len = s.pending;
  14608. if (len > strm.avail_out) {
  14609. len = strm.avail_out;
  14610. }
  14611. if (len === 0) { return; }
  14612. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  14613. strm.next_out += len;
  14614. s.pending_out += len;
  14615. strm.total_out += len;
  14616. strm.avail_out -= len;
  14617. s.pending -= len;
  14618. if (s.pending === 0) {
  14619. s.pending_out = 0;
  14620. }
  14621. }
  14622. function flush_block_only (s, last) {
  14623. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  14624. s.block_start = s.strstart;
  14625. flush_pending(s.strm);
  14626. }
  14627. function put_byte(s, b) {
  14628. s.pending_buf[s.pending++] = b;
  14629. }
  14630. /* =========================================================================
  14631. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  14632. * IN assertion: the stream state is correct and there is enough room in
  14633. * pending_buf.
  14634. */
  14635. function putShortMSB(s, b) {
  14636. // put_byte(s, (Byte)(b >> 8));
  14637. // put_byte(s, (Byte)(b & 0xff));
  14638. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  14639. s.pending_buf[s.pending++] = b & 0xff;
  14640. }
  14641. /* ===========================================================================
  14642. * Read a new buffer from the current input stream, update the adler32
  14643. * and total number of bytes read. All deflate() input goes through
  14644. * this function so some applications may wish to modify it to avoid
  14645. * allocating a large strm->input buffer and copying from it.
  14646. * (See also flush_pending()).
  14647. */
  14648. function read_buf(strm, buf, start, size) {
  14649. var len = strm.avail_in;
  14650. if (len > size) { len = size; }
  14651. if (len === 0) { return 0; }
  14652. strm.avail_in -= len;
  14653. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  14654. if (strm.state.wrap === 1) {
  14655. strm.adler = adler32(strm.adler, buf, len, start);
  14656. }
  14657. else if (strm.state.wrap === 2) {
  14658. strm.adler = crc32(strm.adler, buf, len, start);
  14659. }
  14660. strm.next_in += len;
  14661. strm.total_in += len;
  14662. return len;
  14663. }
  14664. /* ===========================================================================
  14665. * Set match_start to the longest match starting at the given string and
  14666. * return its length. Matches shorter or equal to prev_length are discarded,
  14667. * in which case the result is equal to prev_length and match_start is
  14668. * garbage.
  14669. * IN assertions: cur_match is the head of the hash chain for the current
  14670. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  14671. * OUT assertion: the match length is not greater than s->lookahead.
  14672. */
  14673. function longest_match(s, cur_match) {
  14674. var chain_length = s.max_chain_length; /* max hash chain length */
  14675. var scan = s.strstart; /* current string */
  14676. var match; /* matched string */
  14677. var len; /* length of current match */
  14678. var best_len = s.prev_length; /* best match length so far */
  14679. var nice_match = s.nice_match; /* stop if match long enough */
  14680. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  14681. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  14682. var _win = s.window; // shortcut
  14683. var wmask = s.w_mask;
  14684. var prev = s.prev;
  14685. /* Stop when cur_match becomes <= limit. To simplify the code,
  14686. * we prevent matches with the string of window index 0.
  14687. */
  14688. var strend = s.strstart + MAX_MATCH;
  14689. var scan_end1 = _win[scan + best_len - 1];
  14690. var scan_end = _win[scan + best_len];
  14691. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  14692. * It is easy to get rid of this optimization if necessary.
  14693. */
  14694. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  14695. /* Do not waste too much time if we already have a good match: */
  14696. if (s.prev_length >= s.good_match) {
  14697. chain_length >>= 2;
  14698. }
  14699. /* Do not look for matches beyond the end of the input. This is necessary
  14700. * to make deflate deterministic.
  14701. */
  14702. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  14703. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  14704. do {
  14705. // Assert(cur_match < s->strstart, "no future");
  14706. match = cur_match;
  14707. /* Skip to next match if the match length cannot increase
  14708. * or if the match length is less than 2. Note that the checks below
  14709. * for insufficient lookahead only occur occasionally for performance
  14710. * reasons. Therefore uninitialized memory will be accessed, and
  14711. * conditional jumps will be made that depend on those values.
  14712. * However the length of the match is limited to the lookahead, so
  14713. * the output of deflate is not affected by the uninitialized values.
  14714. */
  14715. if (_win[match + best_len] !== scan_end ||
  14716. _win[match + best_len - 1] !== scan_end1 ||
  14717. _win[match] !== _win[scan] ||
  14718. _win[++match] !== _win[scan + 1]) {
  14719. continue;
  14720. }
  14721. /* The check at best_len-1 can be removed because it will be made
  14722. * again later. (This heuristic is not always a win.)
  14723. * It is not necessary to compare scan[2] and match[2] since they
  14724. * are always equal when the other bytes match, given that
  14725. * the hash keys are equal and that HASH_BITS >= 8.
  14726. */
  14727. scan += 2;
  14728. match++;
  14729. // Assert(*scan == *match, "match[2]?");
  14730. /* We check for insufficient lookahead only every 8th comparison;
  14731. * the 256th check will be made at strstart+258.
  14732. */
  14733. do {
  14734. /*jshint noempty:false*/
  14735. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14736. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14737. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14738. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  14739. scan < strend);
  14740. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  14741. len = MAX_MATCH - (strend - scan);
  14742. scan = strend - MAX_MATCH;
  14743. if (len > best_len) {
  14744. s.match_start = cur_match;
  14745. best_len = len;
  14746. if (len >= nice_match) {
  14747. break;
  14748. }
  14749. scan_end1 = _win[scan + best_len - 1];
  14750. scan_end = _win[scan + best_len];
  14751. }
  14752. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  14753. if (best_len <= s.lookahead) {
  14754. return best_len;
  14755. }
  14756. return s.lookahead;
  14757. }
  14758. /* ===========================================================================
  14759. * Fill the window when the lookahead becomes insufficient.
  14760. * Updates strstart and lookahead.
  14761. *
  14762. * IN assertion: lookahead < MIN_LOOKAHEAD
  14763. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14764. * At least one byte has been read, or avail_in == 0; reads are
  14765. * performed for at least two bytes (required for the zip translate_eol
  14766. * option -- not supported here).
  14767. */
  14768. function fill_window(s) {
  14769. var _w_size = s.w_size;
  14770. var p, n, m, more, str;
  14771. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14772. do {
  14773. more = s.window_size - s.lookahead - s.strstart;
  14774. // JS ints have 32 bit, block below not needed
  14775. /* Deal with !@#$% 64K limit: */
  14776. //if (sizeof(int) <= 2) {
  14777. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14778. // more = wsize;
  14779. //
  14780. // } else if (more == (unsigned)(-1)) {
  14781. // /* Very unlikely, but possible on 16 bit machine if
  14782. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14783. // */
  14784. // more--;
  14785. // }
  14786. //}
  14787. /* If the window is almost full and there is insufficient lookahead,
  14788. * move the upper half to the lower one to make room in the upper half.
  14789. */
  14790. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14791. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14792. s.match_start -= _w_size;
  14793. s.strstart -= _w_size;
  14794. /* we now have strstart >= MAX_DIST */
  14795. s.block_start -= _w_size;
  14796. /* Slide the hash table (could be avoided with 32 bit values
  14797. at the expense of memory usage). We slide even when level == 0
  14798. to keep the hash table consistent if we switch back to level > 0
  14799. later. (Using level 0 permanently is not an optimal usage of
  14800. zlib, so we don't care about this pathological case.)
  14801. */
  14802. n = s.hash_size;
  14803. p = n;
  14804. do {
  14805. m = s.head[--p];
  14806. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14807. } while (--n);
  14808. n = _w_size;
  14809. p = n;
  14810. do {
  14811. m = s.prev[--p];
  14812. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14813. /* If n is not on any hash chain, prev[n] is garbage but
  14814. * its value will never be used.
  14815. */
  14816. } while (--n);
  14817. more += _w_size;
  14818. }
  14819. if (s.strm.avail_in === 0) {
  14820. break;
  14821. }
  14822. /* If there was no sliding:
  14823. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14824. * more == window_size - lookahead - strstart
  14825. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14826. * => more >= window_size - 2*WSIZE + 2
  14827. * In the BIG_MEM or MMAP case (not yet supported),
  14828. * window_size == input_size + MIN_LOOKAHEAD &&
  14829. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14830. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14831. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14832. */
  14833. //Assert(more >= 2, "more < 2");
  14834. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14835. s.lookahead += n;
  14836. /* Initialize the hash value now that we have some input: */
  14837. if (s.lookahead + s.insert >= MIN_MATCH) {
  14838. str = s.strstart - s.insert;
  14839. s.ins_h = s.window[str];
  14840. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14841. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14842. //#if MIN_MATCH != 3
  14843. // Call update_hash() MIN_MATCH-3 more times
  14844. //#endif
  14845. while (s.insert) {
  14846. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14847. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  14848. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14849. s.head[s.ins_h] = str;
  14850. str++;
  14851. s.insert--;
  14852. if (s.lookahead + s.insert < MIN_MATCH) {
  14853. break;
  14854. }
  14855. }
  14856. }
  14857. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14858. * but this is not important since only literal bytes will be emitted.
  14859. */
  14860. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14861. /* If the WIN_INIT bytes after the end of the current data have never been
  14862. * written, then zero those bytes in order to avoid memory check reports of
  14863. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14864. * the longest match routines. Update the high water mark for the next
  14865. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14866. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14867. */
  14868. // if (s.high_water < s.window_size) {
  14869. // var curr = s.strstart + s.lookahead;
  14870. // var init = 0;
  14871. //
  14872. // if (s.high_water < curr) {
  14873. // /* Previous high water mark below current data -- zero WIN_INIT
  14874. // * bytes or up to end of window, whichever is less.
  14875. // */
  14876. // init = s.window_size - curr;
  14877. // if (init > WIN_INIT)
  14878. // init = WIN_INIT;
  14879. // zmemzero(s->window + curr, (unsigned)init);
  14880. // s->high_water = curr + init;
  14881. // }
  14882. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14883. // /* High water mark at or above current data, but below current data
  14884. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14885. // * to end of window, whichever is less.
  14886. // */
  14887. // init = (ulg)curr + WIN_INIT - s->high_water;
  14888. // if (init > s->window_size - s->high_water)
  14889. // init = s->window_size - s->high_water;
  14890. // zmemzero(s->window + s->high_water, (unsigned)init);
  14891. // s->high_water += init;
  14892. // }
  14893. // }
  14894. //
  14895. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  14896. // "not enough room for search");
  14897. }
  14898. /* ===========================================================================
  14899. * Copy without compression as much as possible from the input stream, return
  14900. * the current block state.
  14901. * This function does not insert new strings in the dictionary since
  14902. * uncompressible data is probably not useful. This function is used
  14903. * only for the level=0 compression option.
  14904. * NOTE: this function should be optimized to avoid extra copying from
  14905. * window to pending_buf.
  14906. */
  14907. function deflate_stored(s, flush) {
  14908. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  14909. * to pending_buf_size, and each stored block has a 5 byte header:
  14910. */
  14911. var max_block_size = 0xffff;
  14912. if (max_block_size > s.pending_buf_size - 5) {
  14913. max_block_size = s.pending_buf_size - 5;
  14914. }
  14915. /* Copy as much as possible from input to output: */
  14916. for (;;) {
  14917. /* Fill the window as much as possible: */
  14918. if (s.lookahead <= 1) {
  14919. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  14920. // s->block_start >= (long)s->w_size, "slide too late");
  14921. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  14922. // s.block_start >= s.w_size)) {
  14923. // throw new Error("slide too late");
  14924. // }
  14925. fill_window(s);
  14926. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  14927. return BS_NEED_MORE;
  14928. }
  14929. if (s.lookahead === 0) {
  14930. break;
  14931. }
  14932. /* flush the current block */
  14933. }
  14934. //Assert(s->block_start >= 0L, "block gone");
  14935. // if (s.block_start < 0) throw new Error("block gone");
  14936. s.strstart += s.lookahead;
  14937. s.lookahead = 0;
  14938. /* Emit a stored block if pending_buf will be full: */
  14939. var max_start = s.block_start + max_block_size;
  14940. if (s.strstart === 0 || s.strstart >= max_start) {
  14941. /* strstart == 0 is possible when wraparound on 16-bit machine */
  14942. s.lookahead = s.strstart - max_start;
  14943. s.strstart = max_start;
  14944. /*** FLUSH_BLOCK(s, 0); ***/
  14945. flush_block_only(s, false);
  14946. if (s.strm.avail_out === 0) {
  14947. return BS_NEED_MORE;
  14948. }
  14949. /***/
  14950. }
  14951. /* Flush if we may have to slide, otherwise block_start may become
  14952. * negative and the data will be gone:
  14953. */
  14954. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  14955. /*** FLUSH_BLOCK(s, 0); ***/
  14956. flush_block_only(s, false);
  14957. if (s.strm.avail_out === 0) {
  14958. return BS_NEED_MORE;
  14959. }
  14960. /***/
  14961. }
  14962. }
  14963. s.insert = 0;
  14964. if (flush === Z_FINISH) {
  14965. /*** FLUSH_BLOCK(s, 1); ***/
  14966. flush_block_only(s, true);
  14967. if (s.strm.avail_out === 0) {
  14968. return BS_FINISH_STARTED;
  14969. }
  14970. /***/
  14971. return BS_FINISH_DONE;
  14972. }
  14973. if (s.strstart > s.block_start) {
  14974. /*** FLUSH_BLOCK(s, 0); ***/
  14975. flush_block_only(s, false);
  14976. if (s.strm.avail_out === 0) {
  14977. return BS_NEED_MORE;
  14978. }
  14979. /***/
  14980. }
  14981. return BS_NEED_MORE;
  14982. }
  14983. /* ===========================================================================
  14984. * Compress as much as possible from the input stream, return the current
  14985. * block state.
  14986. * This function does not perform lazy evaluation of matches and inserts
  14987. * new strings in the dictionary only for unmatched strings or for short
  14988. * matches. It is used only for the fast compression options.
  14989. */
  14990. function deflate_fast(s, flush) {
  14991. var hash_head; /* head of the hash chain */
  14992. var bflush; /* set if current block must be flushed */
  14993. for (;;) {
  14994. /* Make sure that we always have enough lookahead, except
  14995. * at the end of the input file. We need MAX_MATCH bytes
  14996. * for the next match, plus MIN_MATCH bytes to insert the
  14997. * string following the next match.
  14998. */
  14999. if (s.lookahead < MIN_LOOKAHEAD) {
  15000. fill_window(s);
  15001. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15002. return BS_NEED_MORE;
  15003. }
  15004. if (s.lookahead === 0) {
  15005. break; /* flush the current block */
  15006. }
  15007. }
  15008. /* Insert the string window[strstart .. strstart+2] in the
  15009. * dictionary, and set hash_head to the head of the hash chain:
  15010. */
  15011. hash_head = 0/*NIL*/;
  15012. if (s.lookahead >= MIN_MATCH) {
  15013. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15014. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15015. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15016. s.head[s.ins_h] = s.strstart;
  15017. /***/
  15018. }
  15019. /* Find the longest match, discarding those <= prev_length.
  15020. * At this point we have always match_length < MIN_MATCH
  15021. */
  15022. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  15023. /* To simplify the code, we prevent matches with the string
  15024. * of window index 0 (in particular we have to avoid a match
  15025. * of the string with itself at the start of the input file).
  15026. */
  15027. s.match_length = longest_match(s, hash_head);
  15028. /* longest_match() sets match_start */
  15029. }
  15030. if (s.match_length >= MIN_MATCH) {
  15031. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  15032. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  15033. s.match_length - MIN_MATCH, bflush); ***/
  15034. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  15035. s.lookahead -= s.match_length;
  15036. /* Insert new strings in the hash table only if the match length
  15037. * is not too large. This saves time but degrades compression.
  15038. */
  15039. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  15040. s.match_length--; /* string at strstart already in table */
  15041. do {
  15042. s.strstart++;
  15043. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15044. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15045. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15046. s.head[s.ins_h] = s.strstart;
  15047. /***/
  15048. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  15049. * always MIN_MATCH bytes ahead.
  15050. */
  15051. } while (--s.match_length !== 0);
  15052. s.strstart++;
  15053. } else
  15054. {
  15055. s.strstart += s.match_length;
  15056. s.match_length = 0;
  15057. s.ins_h = s.window[s.strstart];
  15058. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  15059. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  15060. //#if MIN_MATCH != 3
  15061. // Call UPDATE_HASH() MIN_MATCH-3 more times
  15062. //#endif
  15063. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  15064. * matter since it will be recomputed at next deflate call.
  15065. */
  15066. }
  15067. } else {
  15068. /* No match, output a literal byte */
  15069. //Tracevv((stderr,"%c", s.window[s.strstart]));
  15070. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15071. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15072. s.lookahead--;
  15073. s.strstart++;
  15074. }
  15075. if (bflush) {
  15076. /*** FLUSH_BLOCK(s, 0); ***/
  15077. flush_block_only(s, false);
  15078. if (s.strm.avail_out === 0) {
  15079. return BS_NEED_MORE;
  15080. }
  15081. /***/
  15082. }
  15083. }
  15084. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  15085. if (flush === Z_FINISH) {
  15086. /*** FLUSH_BLOCK(s, 1); ***/
  15087. flush_block_only(s, true);
  15088. if (s.strm.avail_out === 0) {
  15089. return BS_FINISH_STARTED;
  15090. }
  15091. /***/
  15092. return BS_FINISH_DONE;
  15093. }
  15094. if (s.last_lit) {
  15095. /*** FLUSH_BLOCK(s, 0); ***/
  15096. flush_block_only(s, false);
  15097. if (s.strm.avail_out === 0) {
  15098. return BS_NEED_MORE;
  15099. }
  15100. /***/
  15101. }
  15102. return BS_BLOCK_DONE;
  15103. }
  15104. /* ===========================================================================
  15105. * Same as above, but achieves better compression. We use a lazy
  15106. * evaluation for matches: a match is finally adopted only if there is
  15107. * no better match at the next window position.
  15108. */
  15109. function deflate_slow(s, flush) {
  15110. var hash_head; /* head of hash chain */
  15111. var bflush; /* set if current block must be flushed */
  15112. var max_insert;
  15113. /* Process the input block. */
  15114. for (;;) {
  15115. /* Make sure that we always have enough lookahead, except
  15116. * at the end of the input file. We need MAX_MATCH bytes
  15117. * for the next match, plus MIN_MATCH bytes to insert the
  15118. * string following the next match.
  15119. */
  15120. if (s.lookahead < MIN_LOOKAHEAD) {
  15121. fill_window(s);
  15122. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15123. return BS_NEED_MORE;
  15124. }
  15125. if (s.lookahead === 0) { break; } /* flush the current block */
  15126. }
  15127. /* Insert the string window[strstart .. strstart+2] in the
  15128. * dictionary, and set hash_head to the head of the hash chain:
  15129. */
  15130. hash_head = 0/*NIL*/;
  15131. if (s.lookahead >= MIN_MATCH) {
  15132. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15133. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15134. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15135. s.head[s.ins_h] = s.strstart;
  15136. /***/
  15137. }
  15138. /* Find the longest match, discarding those <= prev_length.
  15139. */
  15140. s.prev_length = s.match_length;
  15141. s.prev_match = s.match_start;
  15142. s.match_length = MIN_MATCH-1;
  15143. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  15144. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  15145. /* To simplify the code, we prevent matches with the string
  15146. * of window index 0 (in particular we have to avoid a match
  15147. * of the string with itself at the start of the input file).
  15148. */
  15149. s.match_length = longest_match(s, hash_head);
  15150. /* longest_match() sets match_start */
  15151. if (s.match_length <= 5 &&
  15152. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  15153. /* If prev_match is also MIN_MATCH, match_start is garbage
  15154. * but we will ignore the current match anyway.
  15155. */
  15156. s.match_length = MIN_MATCH-1;
  15157. }
  15158. }
  15159. /* If there was a match at the previous step and the current
  15160. * match is not better, output the previous match:
  15161. */
  15162. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  15163. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  15164. /* Do not insert strings in hash table beyond this. */
  15165. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  15166. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  15167. s.prev_length - MIN_MATCH, bflush);***/
  15168. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  15169. /* Insert in hash table all strings up to the end of the match.
  15170. * strstart-1 and strstart are already inserted. If there is not
  15171. * enough lookahead, the last two strings are not inserted in
  15172. * the hash table.
  15173. */
  15174. s.lookahead -= s.prev_length-1;
  15175. s.prev_length -= 2;
  15176. do {
  15177. if (++s.strstart <= max_insert) {
  15178. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15179. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15180. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15181. s.head[s.ins_h] = s.strstart;
  15182. /***/
  15183. }
  15184. } while (--s.prev_length !== 0);
  15185. s.match_available = 0;
  15186. s.match_length = MIN_MATCH-1;
  15187. s.strstart++;
  15188. if (bflush) {
  15189. /*** FLUSH_BLOCK(s, 0); ***/
  15190. flush_block_only(s, false);
  15191. if (s.strm.avail_out === 0) {
  15192. return BS_NEED_MORE;
  15193. }
  15194. /***/
  15195. }
  15196. } else if (s.match_available) {
  15197. /* If there was no match at the previous position, output a
  15198. * single literal. If there was a match but the current match
  15199. * is longer, truncate the previous match to a single literal.
  15200. */
  15201. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15202. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15203. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15204. if (bflush) {
  15205. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  15206. flush_block_only(s, false);
  15207. /***/
  15208. }
  15209. s.strstart++;
  15210. s.lookahead--;
  15211. if (s.strm.avail_out === 0) {
  15212. return BS_NEED_MORE;
  15213. }
  15214. } else {
  15215. /* There is no previous match to compare with, wait for
  15216. * the next step to decide.
  15217. */
  15218. s.match_available = 1;
  15219. s.strstart++;
  15220. s.lookahead--;
  15221. }
  15222. }
  15223. //Assert (flush != Z_NO_FLUSH, "no flush?");
  15224. if (s.match_available) {
  15225. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  15226. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  15227. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  15228. s.match_available = 0;
  15229. }
  15230. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  15231. if (flush === Z_FINISH) {
  15232. /*** FLUSH_BLOCK(s, 1); ***/
  15233. flush_block_only(s, true);
  15234. if (s.strm.avail_out === 0) {
  15235. return BS_FINISH_STARTED;
  15236. }
  15237. /***/
  15238. return BS_FINISH_DONE;
  15239. }
  15240. if (s.last_lit) {
  15241. /*** FLUSH_BLOCK(s, 0); ***/
  15242. flush_block_only(s, false);
  15243. if (s.strm.avail_out === 0) {
  15244. return BS_NEED_MORE;
  15245. }
  15246. /***/
  15247. }
  15248. return BS_BLOCK_DONE;
  15249. }
  15250. /* ===========================================================================
  15251. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  15252. * one. Do not maintain a hash table. (It will be regenerated if this run of
  15253. * deflate switches away from Z_RLE.)
  15254. */
  15255. function deflate_rle(s, flush) {
  15256. var bflush; /* set if current block must be flushed */
  15257. var prev; /* byte at distance one to match */
  15258. var scan, strend; /* scan goes up to strend for length of run */
  15259. var _win = s.window;
  15260. for (;;) {
  15261. /* Make sure that we always have enough lookahead, except
  15262. * at the end of the input file. We need MAX_MATCH bytes
  15263. * for the longest run, plus one for the unrolled loop.
  15264. */
  15265. if (s.lookahead <= MAX_MATCH) {
  15266. fill_window(s);
  15267. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  15268. return BS_NEED_MORE;
  15269. }
  15270. if (s.lookahead === 0) { break; } /* flush the current block */
  15271. }
  15272. /* See how many times the previous byte repeats */
  15273. s.match_length = 0;
  15274. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  15275. scan = s.strstart - 1;
  15276. prev = _win[scan];
  15277. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  15278. strend = s.strstart + MAX_MATCH;
  15279. do {
  15280. /*jshint noempty:false*/
  15281. } while (prev === _win[++scan] && prev === _win[++scan] &&
  15282. prev === _win[++scan] && prev === _win[++scan] &&
  15283. prev === _win[++scan] && prev === _win[++scan] &&
  15284. prev === _win[++scan] && prev === _win[++scan] &&
  15285. scan < strend);
  15286. s.match_length = MAX_MATCH - (strend - scan);
  15287. if (s.match_length > s.lookahead) {
  15288. s.match_length = s.lookahead;
  15289. }
  15290. }
  15291. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  15292. }
  15293. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  15294. if (s.match_length >= MIN_MATCH) {
  15295. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  15296. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  15297. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  15298. s.lookahead -= s.match_length;
  15299. s.strstart += s.match_length;
  15300. s.match_length = 0;
  15301. } else {
  15302. /* No match, output a literal byte */
  15303. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15304. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15305. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15306. s.lookahead--;
  15307. s.strstart++;
  15308. }
  15309. if (bflush) {
  15310. /*** FLUSH_BLOCK(s, 0); ***/
  15311. flush_block_only(s, false);
  15312. if (s.strm.avail_out === 0) {
  15313. return BS_NEED_MORE;
  15314. }
  15315. /***/
  15316. }
  15317. }
  15318. s.insert = 0;
  15319. if (flush === Z_FINISH) {
  15320. /*** FLUSH_BLOCK(s, 1); ***/
  15321. flush_block_only(s, true);
  15322. if (s.strm.avail_out === 0) {
  15323. return BS_FINISH_STARTED;
  15324. }
  15325. /***/
  15326. return BS_FINISH_DONE;
  15327. }
  15328. if (s.last_lit) {
  15329. /*** FLUSH_BLOCK(s, 0); ***/
  15330. flush_block_only(s, false);
  15331. if (s.strm.avail_out === 0) {
  15332. return BS_NEED_MORE;
  15333. }
  15334. /***/
  15335. }
  15336. return BS_BLOCK_DONE;
  15337. }
  15338. /* ===========================================================================
  15339. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  15340. * (It will be regenerated if this run of deflate switches away from Huffman.)
  15341. */
  15342. function deflate_huff(s, flush) {
  15343. var bflush; /* set if current block must be flushed */
  15344. for (;;) {
  15345. /* Make sure that we have a literal to write. */
  15346. if (s.lookahead === 0) {
  15347. fill_window(s);
  15348. if (s.lookahead === 0) {
  15349. if (flush === Z_NO_FLUSH) {
  15350. return BS_NEED_MORE;
  15351. }
  15352. break; /* flush the current block */
  15353. }
  15354. }
  15355. /* Output a literal byte */
  15356. s.match_length = 0;
  15357. //Tracevv((stderr,"%c", s->window[s->strstart]));
  15358. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15359. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15360. s.lookahead--;
  15361. s.strstart++;
  15362. if (bflush) {
  15363. /*** FLUSH_BLOCK(s, 0); ***/
  15364. flush_block_only(s, false);
  15365. if (s.strm.avail_out === 0) {
  15366. return BS_NEED_MORE;
  15367. }
  15368. /***/
  15369. }
  15370. }
  15371. s.insert = 0;
  15372. if (flush === Z_FINISH) {
  15373. /*** FLUSH_BLOCK(s, 1); ***/
  15374. flush_block_only(s, true);
  15375. if (s.strm.avail_out === 0) {
  15376. return BS_FINISH_STARTED;
  15377. }
  15378. /***/
  15379. return BS_FINISH_DONE;
  15380. }
  15381. if (s.last_lit) {
  15382. /*** FLUSH_BLOCK(s, 0); ***/
  15383. flush_block_only(s, false);
  15384. if (s.strm.avail_out === 0) {
  15385. return BS_NEED_MORE;
  15386. }
  15387. /***/
  15388. }
  15389. return BS_BLOCK_DONE;
  15390. }
  15391. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  15392. * the desired pack level (0..9). The values given below have been tuned to
  15393. * exclude worst case performance for pathological files. Better values may be
  15394. * found for specific files.
  15395. */
  15396. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  15397. this.good_length = good_length;
  15398. this.max_lazy = max_lazy;
  15399. this.nice_length = nice_length;
  15400. this.max_chain = max_chain;
  15401. this.func = func;
  15402. };
  15403. var configuration_table;
  15404. configuration_table = [
  15405. /* good lazy nice chain */
  15406. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  15407. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  15408. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  15409. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  15410. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  15411. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  15412. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  15413. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  15414. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  15415. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  15416. ];
  15417. /* ===========================================================================
  15418. * Initialize the "longest match" routines for a new zlib stream
  15419. */
  15420. function lm_init(s) {
  15421. s.window_size = 2 * s.w_size;
  15422. /*** CLEAR_HASH(s); ***/
  15423. zero(s.head); // Fill with NIL (= 0);
  15424. /* Set the default configuration parameters:
  15425. */
  15426. s.max_lazy_match = configuration_table[s.level].max_lazy;
  15427. s.good_match = configuration_table[s.level].good_length;
  15428. s.nice_match = configuration_table[s.level].nice_length;
  15429. s.max_chain_length = configuration_table[s.level].max_chain;
  15430. s.strstart = 0;
  15431. s.block_start = 0;
  15432. s.lookahead = 0;
  15433. s.insert = 0;
  15434. s.match_length = s.prev_length = MIN_MATCH - 1;
  15435. s.match_available = 0;
  15436. s.ins_h = 0;
  15437. }
  15438. function DeflateState() {
  15439. this.strm = null; /* pointer back to this zlib stream */
  15440. this.status = 0; /* as the name implies */
  15441. this.pending_buf = null; /* output still pending */
  15442. this.pending_buf_size = 0; /* size of pending_buf */
  15443. this.pending_out = 0; /* next pending byte to output to the stream */
  15444. this.pending = 0; /* nb of bytes in the pending buffer */
  15445. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15446. this.gzhead = null; /* gzip header information to write */
  15447. this.gzindex = 0; /* where in extra, name, or comment */
  15448. this.method = Z_DEFLATED; /* can only be DEFLATED */
  15449. this.last_flush = -1; /* value of flush param for previous deflate call */
  15450. this.w_size = 0; /* LZ77 window size (32K by default) */
  15451. this.w_bits = 0; /* log2(w_size) (8..16) */
  15452. this.w_mask = 0; /* w_size - 1 */
  15453. this.window = null;
  15454. /* Sliding window. Input bytes are read into the second half of the window,
  15455. * and move to the first half later to keep a dictionary of at least wSize
  15456. * bytes. With this organization, matches are limited to a distance of
  15457. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  15458. * performed with a length multiple of the block size.
  15459. */
  15460. this.window_size = 0;
  15461. /* Actual size of window: 2*wSize, except when the user input buffer
  15462. * is directly used as sliding window.
  15463. */
  15464. this.prev = null;
  15465. /* Link to older string with same hash index. To limit the size of this
  15466. * array to 64K, this link is maintained only for the last 32K strings.
  15467. * An index in this array is thus a window index modulo 32K.
  15468. */
  15469. this.head = null; /* Heads of the hash chains or NIL. */
  15470. this.ins_h = 0; /* hash index of string to be inserted */
  15471. this.hash_size = 0; /* number of elements in hash table */
  15472. this.hash_bits = 0; /* log2(hash_size) */
  15473. this.hash_mask = 0; /* hash_size-1 */
  15474. this.hash_shift = 0;
  15475. /* Number of bits by which ins_h must be shifted at each input
  15476. * step. It must be such that after MIN_MATCH steps, the oldest
  15477. * byte no longer takes part in the hash key, that is:
  15478. * hash_shift * MIN_MATCH >= hash_bits
  15479. */
  15480. this.block_start = 0;
  15481. /* Window position at the beginning of the current output block. Gets
  15482. * negative when the window is moved backwards.
  15483. */
  15484. this.match_length = 0; /* length of best match */
  15485. this.prev_match = 0; /* previous match */
  15486. this.match_available = 0; /* set if previous match exists */
  15487. this.strstart = 0; /* start of string to insert */
  15488. this.match_start = 0; /* start of matching string */
  15489. this.lookahead = 0; /* number of valid bytes ahead in window */
  15490. this.prev_length = 0;
  15491. /* Length of the best match at previous step. Matches not greater than this
  15492. * are discarded. This is used in the lazy match evaluation.
  15493. */
  15494. this.max_chain_length = 0;
  15495. /* To speed up deflation, hash chains are never searched beyond this
  15496. * length. A higher limit improves compression ratio but degrades the
  15497. * speed.
  15498. */
  15499. this.max_lazy_match = 0;
  15500. /* Attempt to find a better match only when the current match is strictly
  15501. * smaller than this value. This mechanism is used only for compression
  15502. * levels >= 4.
  15503. */
  15504. // That's alias to max_lazy_match, don't use directly
  15505. //this.max_insert_length = 0;
  15506. /* Insert new strings in the hash table only if the match length is not
  15507. * greater than this length. This saves time but degrades compression.
  15508. * max_insert_length is used only for compression levels <= 3.
  15509. */
  15510. this.level = 0; /* compression level (1..9) */
  15511. this.strategy = 0; /* favor or force Huffman coding*/
  15512. this.good_match = 0;
  15513. /* Use a faster search when the previous match is longer than this */
  15514. this.nice_match = 0; /* Stop searching when current match exceeds this */
  15515. /* used by trees.c: */
  15516. /* Didn't use ct_data typedef below to suppress compiler warning */
  15517. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  15518. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  15519. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  15520. // Use flat array of DOUBLE size, with interleaved fata,
  15521. // because JS does not support effective
  15522. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  15523. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  15524. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  15525. zero(this.dyn_ltree);
  15526. zero(this.dyn_dtree);
  15527. zero(this.bl_tree);
  15528. this.l_desc = null; /* desc. for literal tree */
  15529. this.d_desc = null; /* desc. for distance tree */
  15530. this.bl_desc = null; /* desc. for bit length tree */
  15531. //ush bl_count[MAX_BITS+1];
  15532. this.bl_count = new utils.Buf16(MAX_BITS+1);
  15533. /* number of codes at each bit length for an optimal tree */
  15534. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  15535. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  15536. zero(this.heap);
  15537. this.heap_len = 0; /* number of elements in the heap */
  15538. this.heap_max = 0; /* element of largest frequency */
  15539. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  15540. * The same heap array is used to build all trees.
  15541. */
  15542. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  15543. zero(this.depth);
  15544. /* Depth of each subtree used as tie breaker for trees of equal frequency
  15545. */
  15546. this.l_buf = 0; /* buffer index for literals or lengths */
  15547. this.lit_bufsize = 0;
  15548. /* Size of match buffer for literals/lengths. There are 4 reasons for
  15549. * limiting lit_bufsize to 64K:
  15550. * - frequencies can be kept in 16 bit counters
  15551. * - if compression is not successful for the first block, all input
  15552. * data is still in the window so we can still emit a stored block even
  15553. * when input comes from standard input. (This can also be done for
  15554. * all blocks if lit_bufsize is not greater than 32K.)
  15555. * - if compression is not successful for a file smaller than 64K, we can
  15556. * even emit a stored file instead of a stored block (saving 5 bytes).
  15557. * This is applicable only for zip (not gzip or zlib).
  15558. * - creating new Huffman trees less frequently may not provide fast
  15559. * adaptation to changes in the input data statistics. (Take for
  15560. * example a binary file with poorly compressible code followed by
  15561. * a highly compressible string table.) Smaller buffer sizes give
  15562. * fast adaptation but have of course the overhead of transmitting
  15563. * trees more frequently.
  15564. * - I can't count above 4
  15565. */
  15566. this.last_lit = 0; /* running index in l_buf */
  15567. this.d_buf = 0;
  15568. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  15569. * the same number of elements. To use different lengths, an extra flag
  15570. * array would be necessary.
  15571. */
  15572. this.opt_len = 0; /* bit length of current block with optimal trees */
  15573. this.static_len = 0; /* bit length of current block with static trees */
  15574. this.matches = 0; /* number of string matches in current block */
  15575. this.insert = 0; /* bytes at end of window left to insert */
  15576. this.bi_buf = 0;
  15577. /* Output buffer. bits are inserted starting at the bottom (least
  15578. * significant bits).
  15579. */
  15580. this.bi_valid = 0;
  15581. /* Number of valid bits in bi_buf. All bits above the last valid bit
  15582. * are always zero.
  15583. */
  15584. // Used for window memory init. We safely ignore it for JS. That makes
  15585. // sense only for pointers and memory check tools.
  15586. //this.high_water = 0;
  15587. /* High water mark offset in window for initialized bytes -- bytes above
  15588. * this are set to zero in order to avoid memory check warnings when
  15589. * longest match routines access bytes past the input. This is then
  15590. * updated to the new high water mark.
  15591. */
  15592. }
  15593. function deflateResetKeep(strm) {
  15594. var s;
  15595. if (!strm || !strm.state) {
  15596. return err(strm, Z_STREAM_ERROR);
  15597. }
  15598. strm.total_in = strm.total_out = 0;
  15599. strm.data_type = Z_UNKNOWN;
  15600. s = strm.state;
  15601. s.pending = 0;
  15602. s.pending_out = 0;
  15603. if (s.wrap < 0) {
  15604. s.wrap = -s.wrap;
  15605. /* was made negative by deflate(..., Z_FINISH); */
  15606. }
  15607. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  15608. strm.adler = (s.wrap === 2) ?
  15609. 0 // crc32(0, Z_NULL, 0)
  15610. :
  15611. 1; // adler32(0, Z_NULL, 0)
  15612. s.last_flush = Z_NO_FLUSH;
  15613. trees._tr_init(s);
  15614. return Z_OK;
  15615. }
  15616. function deflateReset(strm) {
  15617. var ret = deflateResetKeep(strm);
  15618. if (ret === Z_OK) {
  15619. lm_init(strm.state);
  15620. }
  15621. return ret;
  15622. }
  15623. function deflateSetHeader(strm, head) {
  15624. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15625. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  15626. strm.state.gzhead = head;
  15627. return Z_OK;
  15628. }
  15629. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  15630. if (!strm) { // === Z_NULL
  15631. return Z_STREAM_ERROR;
  15632. }
  15633. var wrap = 1;
  15634. if (level === Z_DEFAULT_COMPRESSION) {
  15635. level = 6;
  15636. }
  15637. if (windowBits < 0) { /* suppress zlib wrapper */
  15638. wrap = 0;
  15639. windowBits = -windowBits;
  15640. }
  15641. else if (windowBits > 15) {
  15642. wrap = 2; /* write gzip wrapper instead */
  15643. windowBits -= 16;
  15644. }
  15645. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  15646. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  15647. strategy < 0 || strategy > Z_FIXED) {
  15648. return err(strm, Z_STREAM_ERROR);
  15649. }
  15650. if (windowBits === 8) {
  15651. windowBits = 9;
  15652. }
  15653. /* until 256-byte window bug fixed */
  15654. var s = new DeflateState();
  15655. strm.state = s;
  15656. s.strm = strm;
  15657. s.wrap = wrap;
  15658. s.gzhead = null;
  15659. s.w_bits = windowBits;
  15660. s.w_size = 1 << s.w_bits;
  15661. s.w_mask = s.w_size - 1;
  15662. s.hash_bits = memLevel + 7;
  15663. s.hash_size = 1 << s.hash_bits;
  15664. s.hash_mask = s.hash_size - 1;
  15665. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  15666. s.window = new utils.Buf8(s.w_size * 2);
  15667. s.head = new utils.Buf16(s.hash_size);
  15668. s.prev = new utils.Buf16(s.w_size);
  15669. // Don't need mem init magic for JS.
  15670. //s.high_water = 0; /* nothing written to s->window yet */
  15671. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  15672. s.pending_buf_size = s.lit_bufsize * 4;
  15673. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  15674. s.d_buf = s.lit_bufsize >> 1;
  15675. s.l_buf = (1 + 2) * s.lit_bufsize;
  15676. s.level = level;
  15677. s.strategy = strategy;
  15678. s.method = method;
  15679. return deflateReset(strm);
  15680. }
  15681. function deflateInit(strm, level) {
  15682. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  15683. }
  15684. function deflate(strm, flush) {
  15685. var old_flush, s;
  15686. var beg, val; // for gzip header write only
  15687. if (!strm || !strm.state ||
  15688. flush > Z_BLOCK || flush < 0) {
  15689. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  15690. }
  15691. s = strm.state;
  15692. if (!strm.output ||
  15693. (!strm.input && strm.avail_in !== 0) ||
  15694. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  15695. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  15696. }
  15697. s.strm = strm; /* just in case */
  15698. old_flush = s.last_flush;
  15699. s.last_flush = flush;
  15700. /* Write the header */
  15701. if (s.status === INIT_STATE) {
  15702. if (s.wrap === 2) { // GZIP header
  15703. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15704. put_byte(s, 31);
  15705. put_byte(s, 139);
  15706. put_byte(s, 8);
  15707. if (!s.gzhead) { // s->gzhead == Z_NULL
  15708. put_byte(s, 0);
  15709. put_byte(s, 0);
  15710. put_byte(s, 0);
  15711. put_byte(s, 0);
  15712. put_byte(s, 0);
  15713. put_byte(s, s.level === 9 ? 2 :
  15714. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15715. 4 : 0));
  15716. put_byte(s, OS_CODE);
  15717. s.status = BUSY_STATE;
  15718. }
  15719. else {
  15720. put_byte(s, (s.gzhead.text ? 1 : 0) +
  15721. (s.gzhead.hcrc ? 2 : 0) +
  15722. (!s.gzhead.extra ? 0 : 4) +
  15723. (!s.gzhead.name ? 0 : 8) +
  15724. (!s.gzhead.comment ? 0 : 16)
  15725. );
  15726. put_byte(s, s.gzhead.time & 0xff);
  15727. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  15728. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  15729. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  15730. put_byte(s, s.level === 9 ? 2 :
  15731. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  15732. 4 : 0));
  15733. put_byte(s, s.gzhead.os & 0xff);
  15734. if (s.gzhead.extra && s.gzhead.extra.length) {
  15735. put_byte(s, s.gzhead.extra.length & 0xff);
  15736. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  15737. }
  15738. if (s.gzhead.hcrc) {
  15739. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  15740. }
  15741. s.gzindex = 0;
  15742. s.status = EXTRA_STATE;
  15743. }
  15744. }
  15745. else // DEFLATE header
  15746. {
  15747. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  15748. var level_flags = -1;
  15749. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  15750. level_flags = 0;
  15751. } else if (s.level < 6) {
  15752. level_flags = 1;
  15753. } else if (s.level === 6) {
  15754. level_flags = 2;
  15755. } else {
  15756. level_flags = 3;
  15757. }
  15758. header |= (level_flags << 6);
  15759. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15760. header += 31 - (header % 31);
  15761. s.status = BUSY_STATE;
  15762. putShortMSB(s, header);
  15763. /* Save the adler32 of the preset dictionary: */
  15764. if (s.strstart !== 0) {
  15765. putShortMSB(s, strm.adler >>> 16);
  15766. putShortMSB(s, strm.adler & 0xffff);
  15767. }
  15768. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15769. }
  15770. }
  15771. //#ifdef GZIP
  15772. if (s.status === EXTRA_STATE) {
  15773. if (s.gzhead.extra/* != Z_NULL*/) {
  15774. beg = s.pending; /* start of bytes to update crc */
  15775. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15776. if (s.pending === s.pending_buf_size) {
  15777. if (s.gzhead.hcrc && s.pending > beg) {
  15778. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15779. }
  15780. flush_pending(strm);
  15781. beg = s.pending;
  15782. if (s.pending === s.pending_buf_size) {
  15783. break;
  15784. }
  15785. }
  15786. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15787. s.gzindex++;
  15788. }
  15789. if (s.gzhead.hcrc && s.pending > beg) {
  15790. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15791. }
  15792. if (s.gzindex === s.gzhead.extra.length) {
  15793. s.gzindex = 0;
  15794. s.status = NAME_STATE;
  15795. }
  15796. }
  15797. else {
  15798. s.status = NAME_STATE;
  15799. }
  15800. }
  15801. if (s.status === NAME_STATE) {
  15802. if (s.gzhead.name/* != Z_NULL*/) {
  15803. beg = s.pending; /* start of bytes to update crc */
  15804. //int val;
  15805. do {
  15806. if (s.pending === s.pending_buf_size) {
  15807. if (s.gzhead.hcrc && s.pending > beg) {
  15808. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15809. }
  15810. flush_pending(strm);
  15811. beg = s.pending;
  15812. if (s.pending === s.pending_buf_size) {
  15813. val = 1;
  15814. break;
  15815. }
  15816. }
  15817. // JS specific: little magic to add zero terminator to end of string
  15818. if (s.gzindex < s.gzhead.name.length) {
  15819. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15820. } else {
  15821. val = 0;
  15822. }
  15823. put_byte(s, val);
  15824. } while (val !== 0);
  15825. if (s.gzhead.hcrc && s.pending > beg) {
  15826. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15827. }
  15828. if (val === 0) {
  15829. s.gzindex = 0;
  15830. s.status = COMMENT_STATE;
  15831. }
  15832. }
  15833. else {
  15834. s.status = COMMENT_STATE;
  15835. }
  15836. }
  15837. if (s.status === COMMENT_STATE) {
  15838. if (s.gzhead.comment/* != Z_NULL*/) {
  15839. beg = s.pending; /* start of bytes to update crc */
  15840. //int val;
  15841. do {
  15842. if (s.pending === s.pending_buf_size) {
  15843. if (s.gzhead.hcrc && s.pending > beg) {
  15844. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15845. }
  15846. flush_pending(strm);
  15847. beg = s.pending;
  15848. if (s.pending === s.pending_buf_size) {
  15849. val = 1;
  15850. break;
  15851. }
  15852. }
  15853. // JS specific: little magic to add zero terminator to end of string
  15854. if (s.gzindex < s.gzhead.comment.length) {
  15855. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15856. } else {
  15857. val = 0;
  15858. }
  15859. put_byte(s, val);
  15860. } while (val !== 0);
  15861. if (s.gzhead.hcrc && s.pending > beg) {
  15862. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15863. }
  15864. if (val === 0) {
  15865. s.status = HCRC_STATE;
  15866. }
  15867. }
  15868. else {
  15869. s.status = HCRC_STATE;
  15870. }
  15871. }
  15872. if (s.status === HCRC_STATE) {
  15873. if (s.gzhead.hcrc) {
  15874. if (s.pending + 2 > s.pending_buf_size) {
  15875. flush_pending(strm);
  15876. }
  15877. if (s.pending + 2 <= s.pending_buf_size) {
  15878. put_byte(s, strm.adler & 0xff);
  15879. put_byte(s, (strm.adler >> 8) & 0xff);
  15880. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15881. s.status = BUSY_STATE;
  15882. }
  15883. }
  15884. else {
  15885. s.status = BUSY_STATE;
  15886. }
  15887. }
  15888. //#endif
  15889. /* Flush as much pending output as possible */
  15890. if (s.pending !== 0) {
  15891. flush_pending(strm);
  15892. if (strm.avail_out === 0) {
  15893. /* Since avail_out is 0, deflate will be called again with
  15894. * more output space, but possibly with both pending and
  15895. * avail_in equal to zero. There won't be anything to do,
  15896. * but this is not an error situation so make sure we
  15897. * return OK instead of BUF_ERROR at next call of deflate:
  15898. */
  15899. s.last_flush = -1;
  15900. return Z_OK;
  15901. }
  15902. /* Make sure there is something to do and avoid duplicate consecutive
  15903. * flushes. For repeated and useless calls with Z_FINISH, we keep
  15904. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  15905. */
  15906. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  15907. flush !== Z_FINISH) {
  15908. return err(strm, Z_BUF_ERROR);
  15909. }
  15910. /* User must not provide more input after the first FINISH: */
  15911. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  15912. return err(strm, Z_BUF_ERROR);
  15913. }
  15914. /* Start a new block or continue the current one.
  15915. */
  15916. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  15917. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  15918. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  15919. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  15920. configuration_table[s.level].func(s, flush));
  15921. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  15922. s.status = FINISH_STATE;
  15923. }
  15924. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  15925. if (strm.avail_out === 0) {
  15926. s.last_flush = -1;
  15927. /* avoid BUF_ERROR next call, see above */
  15928. }
  15929. return Z_OK;
  15930. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  15931. * of deflate should use the same flush parameter to make sure
  15932. * that the flush is complete. So we don't have to output an
  15933. * empty block here, this will be done at next call. This also
  15934. * ensures that for a very small output buffer, we emit at most
  15935. * one empty block.
  15936. */
  15937. }
  15938. if (bstate === BS_BLOCK_DONE) {
  15939. if (flush === Z_PARTIAL_FLUSH) {
  15940. trees._tr_align(s);
  15941. }
  15942. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  15943. trees._tr_stored_block(s, 0, 0, false);
  15944. /* For a full flush, this empty block will be recognized
  15945. * as a special marker by inflate_sync().
  15946. */
  15947. if (flush === Z_FULL_FLUSH) {
  15948. /*** CLEAR_HASH(s); ***/ /* forget history */
  15949. zero(s.head); // Fill with NIL (= 0);
  15950. if (s.lookahead === 0) {
  15951. s.strstart = 0;
  15952. s.block_start = 0;
  15953. s.insert = 0;
  15954. }
  15955. }
  15956. }
  15957. flush_pending(strm);
  15958. if (strm.avail_out === 0) {
  15959. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  15960. return Z_OK;
  15961. }
  15962. }
  15963. }
  15964. //Assert(strm->avail_out > 0, "bug2");
  15965. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  15966. if (flush !== Z_FINISH) { return Z_OK; }
  15967. if (s.wrap <= 0) { return Z_STREAM_END; }
  15968. /* Write the trailer */
  15969. if (s.wrap === 2) {
  15970. put_byte(s, strm.adler & 0xff);
  15971. put_byte(s, (strm.adler >> 8) & 0xff);
  15972. put_byte(s, (strm.adler >> 16) & 0xff);
  15973. put_byte(s, (strm.adler >> 24) & 0xff);
  15974. put_byte(s, strm.total_in & 0xff);
  15975. put_byte(s, (strm.total_in >> 8) & 0xff);
  15976. put_byte(s, (strm.total_in >> 16) & 0xff);
  15977. put_byte(s, (strm.total_in >> 24) & 0xff);
  15978. }
  15979. else
  15980. {
  15981. putShortMSB(s, strm.adler >>> 16);
  15982. putShortMSB(s, strm.adler & 0xffff);
  15983. }
  15984. flush_pending(strm);
  15985. /* If avail_out is zero, the application will call deflate again
  15986. * to flush the rest.
  15987. */
  15988. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15989. /* write the trailer only once! */
  15990. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15991. }
  15992. function deflateEnd(strm) {
  15993. var status;
  15994. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15995. return Z_STREAM_ERROR;
  15996. }
  15997. status = strm.state.status;
  15998. if (status !== INIT_STATE &&
  15999. status !== EXTRA_STATE &&
  16000. status !== NAME_STATE &&
  16001. status !== COMMENT_STATE &&
  16002. status !== HCRC_STATE &&
  16003. status !== BUSY_STATE &&
  16004. status !== FINISH_STATE
  16005. ) {
  16006. return err(strm, Z_STREAM_ERROR);
  16007. }
  16008. strm.state = null;
  16009. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  16010. }
  16011. /* =========================================================================
  16012. * Copy the source state to the destination state
  16013. */
  16014. //function deflateCopy(dest, source) {
  16015. //
  16016. //}
  16017. exports.deflateInit = deflateInit;
  16018. exports.deflateInit2 = deflateInit2;
  16019. exports.deflateReset = deflateReset;
  16020. exports.deflateResetKeep = deflateResetKeep;
  16021. exports.deflateSetHeader = deflateSetHeader;
  16022. exports.deflate = deflate;
  16023. exports.deflateEnd = deflateEnd;
  16024. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  16025. /* Not implemented
  16026. exports.deflateBound = deflateBound;
  16027. exports.deflateCopy = deflateCopy;
  16028. exports.deflateSetDictionary = deflateSetDictionary;
  16029. exports.deflateParams = deflateParams;
  16030. exports.deflatePending = deflatePending;
  16031. exports.deflatePrime = deflatePrime;
  16032. exports.deflateTune = deflateTune;
  16033. */
  16034. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./messages":62,"./trees":63}],58:[function(require,module,exports){
  16035. 'use strict';
  16036. function GZheader() {
  16037. /* true if compressed data believed to be text */
  16038. this.text = 0;
  16039. /* modification time */
  16040. this.time = 0;
  16041. /* extra flags (not used when writing a gzip file) */
  16042. this.xflags = 0;
  16043. /* operating system */
  16044. this.os = 0;
  16045. /* pointer to extra field or Z_NULL if none */
  16046. this.extra = null;
  16047. /* extra field length (valid if extra != Z_NULL) */
  16048. this.extra_len = 0; // Actually, we don't need it in JS,
  16049. // but leave for few code modifications
  16050. //
  16051. // Setup limits is not necessary because in js we should not preallocate memory
  16052. // for inflate use constant limit in 65536 bytes
  16053. //
  16054. /* space at extra (only when reading header) */
  16055. // this.extra_max = 0;
  16056. /* pointer to zero-terminated file name or Z_NULL */
  16057. this.name = '';
  16058. /* space at name (only when reading header) */
  16059. // this.name_max = 0;
  16060. /* pointer to zero-terminated comment or Z_NULL */
  16061. this.comment = '';
  16062. /* space at comment (only when reading header) */
  16063. // this.comm_max = 0;
  16064. /* true if there was or will be a header crc */
  16065. this.hcrc = 0;
  16066. /* true when done reading gzip header (not used when writing a gzip file) */
  16067. this.done = false;
  16068. }
  16069. module.exports = GZheader;
  16070. },{}],59:[function(require,module,exports){
  16071. 'use strict';
  16072. // See state defs from inflate.js
  16073. var BAD = 30; /* got a data error -- remain here until reset */
  16074. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16075. /*
  16076. Decode literal, length, and distance codes and write out the resulting
  16077. literal and match bytes until either not enough input or output is
  16078. available, an end-of-block is encountered, or a data error is encountered.
  16079. When large enough input and output buffers are supplied to inflate(), for
  16080. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  16081. inflate execution time is spent in this routine.
  16082. Entry assumptions:
  16083. state.mode === LEN
  16084. strm.avail_in >= 6
  16085. strm.avail_out >= 258
  16086. start >= strm.avail_out
  16087. state.bits < 8
  16088. On return, state.mode is one of:
  16089. LEN -- ran out of enough output space or enough available input
  16090. TYPE -- reached end of block code, inflate() to interpret next block
  16091. BAD -- error in block data
  16092. Notes:
  16093. - The maximum input bits used by a length/distance pair is 15 bits for the
  16094. length code, 5 bits for the length extra, 15 bits for the distance code,
  16095. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  16096. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  16097. checking for available input while decoding.
  16098. - The maximum bytes that a single length/distance pair can output is 258
  16099. bytes, which is the maximum length that can be coded. inflate_fast()
  16100. requires strm.avail_out >= 258 for each loop to avoid checking for
  16101. output space.
  16102. */
  16103. module.exports = function inflate_fast(strm, start) {
  16104. var state;
  16105. var _in; /* local strm.input */
  16106. var last; /* have enough input while in < last */
  16107. var _out; /* local strm.output */
  16108. var beg; /* inflate()'s initial strm.output */
  16109. var end; /* while out < end, enough space available */
  16110. //#ifdef INFLATE_STRICT
  16111. var dmax; /* maximum distance from zlib header */
  16112. //#endif
  16113. var wsize; /* window size or zero if not using window */
  16114. var whave; /* valid bytes in the window */
  16115. var wnext; /* window write index */
  16116. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  16117. var s_window; /* allocated sliding window, if wsize != 0 */
  16118. var hold; /* local strm.hold */
  16119. var bits; /* local strm.bits */
  16120. var lcode; /* local strm.lencode */
  16121. var dcode; /* local strm.distcode */
  16122. var lmask; /* mask for first level of length codes */
  16123. var dmask; /* mask for first level of distance codes */
  16124. var here; /* retrieved table entry */
  16125. var op; /* code bits, operation, extra bits, or */
  16126. /* window position, window bytes to copy */
  16127. var len; /* match length, unused bytes */
  16128. var dist; /* match distance */
  16129. var from; /* where to copy match from */
  16130. var from_source;
  16131. var input, output; // JS specific, because we have no pointers
  16132. /* copy state to local variables */
  16133. state = strm.state;
  16134. //here = state.here;
  16135. _in = strm.next_in;
  16136. input = strm.input;
  16137. last = _in + (strm.avail_in - 5);
  16138. _out = strm.next_out;
  16139. output = strm.output;
  16140. beg = _out - (start - strm.avail_out);
  16141. end = _out + (strm.avail_out - 257);
  16142. //#ifdef INFLATE_STRICT
  16143. dmax = state.dmax;
  16144. //#endif
  16145. wsize = state.wsize;
  16146. whave = state.whave;
  16147. wnext = state.wnext;
  16148. s_window = state.window;
  16149. hold = state.hold;
  16150. bits = state.bits;
  16151. lcode = state.lencode;
  16152. dcode = state.distcode;
  16153. lmask = (1 << state.lenbits) - 1;
  16154. dmask = (1 << state.distbits) - 1;
  16155. /* decode literals and length/distances until end-of-block or not enough
  16156. input data or output space */
  16157. top:
  16158. do {
  16159. if (bits < 15) {
  16160. hold += input[_in++] << bits;
  16161. bits += 8;
  16162. hold += input[_in++] << bits;
  16163. bits += 8;
  16164. }
  16165. here = lcode[hold & lmask];
  16166. dolen:
  16167. for (;;) { // Goto emulation
  16168. op = here >>> 24/*here.bits*/;
  16169. hold >>>= op;
  16170. bits -= op;
  16171. op = (here >>> 16) & 0xff/*here.op*/;
  16172. if (op === 0) { /* literal */
  16173. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16174. // "inflate: literal '%c'\n" :
  16175. // "inflate: literal 0x%02x\n", here.val));
  16176. output[_out++] = here & 0xffff/*here.val*/;
  16177. }
  16178. else if (op & 16) { /* length base */
  16179. len = here & 0xffff/*here.val*/;
  16180. op &= 15; /* number of extra bits */
  16181. if (op) {
  16182. if (bits < op) {
  16183. hold += input[_in++] << bits;
  16184. bits += 8;
  16185. }
  16186. len += hold & ((1 << op) - 1);
  16187. hold >>>= op;
  16188. bits -= op;
  16189. }
  16190. //Tracevv((stderr, "inflate: length %u\n", len));
  16191. if (bits < 15) {
  16192. hold += input[_in++] << bits;
  16193. bits += 8;
  16194. hold += input[_in++] << bits;
  16195. bits += 8;
  16196. }
  16197. here = dcode[hold & dmask];
  16198. dodist:
  16199. for (;;) { // goto emulation
  16200. op = here >>> 24/*here.bits*/;
  16201. hold >>>= op;
  16202. bits -= op;
  16203. op = (here >>> 16) & 0xff/*here.op*/;
  16204. if (op & 16) { /* distance base */
  16205. dist = here & 0xffff/*here.val*/;
  16206. op &= 15; /* number of extra bits */
  16207. if (bits < op) {
  16208. hold += input[_in++] << bits;
  16209. bits += 8;
  16210. if (bits < op) {
  16211. hold += input[_in++] << bits;
  16212. bits += 8;
  16213. }
  16214. }
  16215. dist += hold & ((1 << op) - 1);
  16216. //#ifdef INFLATE_STRICT
  16217. if (dist > dmax) {
  16218. strm.msg = 'invalid distance too far back';
  16219. state.mode = BAD;
  16220. break top;
  16221. }
  16222. //#endif
  16223. hold >>>= op;
  16224. bits -= op;
  16225. //Tracevv((stderr, "inflate: distance %u\n", dist));
  16226. op = _out - beg; /* max distance in output */
  16227. if (dist > op) { /* see if copy from window */
  16228. op = dist - op; /* distance back in window */
  16229. if (op > whave) {
  16230. if (state.sane) {
  16231. strm.msg = 'invalid distance too far back';
  16232. state.mode = BAD;
  16233. break top;
  16234. }
  16235. // (!) This block is disabled in zlib defailts,
  16236. // don't enable it for binary compatibility
  16237. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16238. // if (len <= op - whave) {
  16239. // do {
  16240. // output[_out++] = 0;
  16241. // } while (--len);
  16242. // continue top;
  16243. // }
  16244. // len -= op - whave;
  16245. // do {
  16246. // output[_out++] = 0;
  16247. // } while (--op > whave);
  16248. // if (op === 0) {
  16249. // from = _out - dist;
  16250. // do {
  16251. // output[_out++] = output[from++];
  16252. // } while (--len);
  16253. // continue top;
  16254. // }
  16255. //#endif
  16256. }
  16257. from = 0; // window index
  16258. from_source = s_window;
  16259. if (wnext === 0) { /* very common case */
  16260. from += wsize - op;
  16261. if (op < len) { /* some from window */
  16262. len -= op;
  16263. do {
  16264. output[_out++] = s_window[from++];
  16265. } while (--op);
  16266. from = _out - dist; /* rest from output */
  16267. from_source = output;
  16268. }
  16269. }
  16270. else if (wnext < op) { /* wrap around window */
  16271. from += wsize + wnext - op;
  16272. op -= wnext;
  16273. if (op < len) { /* some from end of window */
  16274. len -= op;
  16275. do {
  16276. output[_out++] = s_window[from++];
  16277. } while (--op);
  16278. from = 0;
  16279. if (wnext < len) { /* some from start of window */
  16280. op = wnext;
  16281. len -= op;
  16282. do {
  16283. output[_out++] = s_window[from++];
  16284. } while (--op);
  16285. from = _out - dist; /* rest from output */
  16286. from_source = output;
  16287. }
  16288. }
  16289. }
  16290. else { /* contiguous in window */
  16291. from += wnext - op;
  16292. if (op < len) { /* some from window */
  16293. len -= op;
  16294. do {
  16295. output[_out++] = s_window[from++];
  16296. } while (--op);
  16297. from = _out - dist; /* rest from output */
  16298. from_source = output;
  16299. }
  16300. }
  16301. while (len > 2) {
  16302. output[_out++] = from_source[from++];
  16303. output[_out++] = from_source[from++];
  16304. output[_out++] = from_source[from++];
  16305. len -= 3;
  16306. }
  16307. if (len) {
  16308. output[_out++] = from_source[from++];
  16309. if (len > 1) {
  16310. output[_out++] = from_source[from++];
  16311. }
  16312. }
  16313. }
  16314. else {
  16315. from = _out - dist; /* copy direct from output */
  16316. do { /* minimum length is three */
  16317. output[_out++] = output[from++];
  16318. output[_out++] = output[from++];
  16319. output[_out++] = output[from++];
  16320. len -= 3;
  16321. } while (len > 2);
  16322. if (len) {
  16323. output[_out++] = output[from++];
  16324. if (len > 1) {
  16325. output[_out++] = output[from++];
  16326. }
  16327. }
  16328. }
  16329. }
  16330. else if ((op & 64) === 0) { /* 2nd level distance code */
  16331. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16332. continue dodist;
  16333. }
  16334. else {
  16335. strm.msg = 'invalid distance code';
  16336. state.mode = BAD;
  16337. break top;
  16338. }
  16339. break; // need to emulate goto via "continue"
  16340. }
  16341. }
  16342. else if ((op & 64) === 0) { /* 2nd level length code */
  16343. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  16344. continue dolen;
  16345. }
  16346. else if (op & 32) { /* end-of-block */
  16347. //Tracevv((stderr, "inflate: end of block\n"));
  16348. state.mode = TYPE;
  16349. break top;
  16350. }
  16351. else {
  16352. strm.msg = 'invalid literal/length code';
  16353. state.mode = BAD;
  16354. break top;
  16355. }
  16356. break; // need to emulate goto via "continue"
  16357. }
  16358. } while (_in < last && _out < end);
  16359. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  16360. len = bits >> 3;
  16361. _in -= len;
  16362. bits -= len << 3;
  16363. hold &= (1 << bits) - 1;
  16364. /* update state and return */
  16365. strm.next_in = _in;
  16366. strm.next_out = _out;
  16367. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  16368. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  16369. state.hold = hold;
  16370. state.bits = bits;
  16371. return;
  16372. };
  16373. },{}],60:[function(require,module,exports){
  16374. 'use strict';
  16375. var utils = require('../utils/common');
  16376. var adler32 = require('./adler32');
  16377. var crc32 = require('./crc32');
  16378. var inflate_fast = require('./inffast');
  16379. var inflate_table = require('./inftrees');
  16380. var CODES = 0;
  16381. var LENS = 1;
  16382. var DISTS = 2;
  16383. /* Public constants ==========================================================*/
  16384. /* ===========================================================================*/
  16385. /* Allowed flush values; see deflate() and inflate() below for details */
  16386. //var Z_NO_FLUSH = 0;
  16387. //var Z_PARTIAL_FLUSH = 1;
  16388. //var Z_SYNC_FLUSH = 2;
  16389. //var Z_FULL_FLUSH = 3;
  16390. var Z_FINISH = 4;
  16391. var Z_BLOCK = 5;
  16392. var Z_TREES = 6;
  16393. /* Return codes for the compression/decompression functions. Negative values
  16394. * are errors, positive values are used for special but normal events.
  16395. */
  16396. var Z_OK = 0;
  16397. var Z_STREAM_END = 1;
  16398. var Z_NEED_DICT = 2;
  16399. //var Z_ERRNO = -1;
  16400. var Z_STREAM_ERROR = -2;
  16401. var Z_DATA_ERROR = -3;
  16402. var Z_MEM_ERROR = -4;
  16403. var Z_BUF_ERROR = -5;
  16404. //var Z_VERSION_ERROR = -6;
  16405. /* The deflate compression method */
  16406. var Z_DEFLATED = 8;
  16407. /* STATES ====================================================================*/
  16408. /* ===========================================================================*/
  16409. var HEAD = 1; /* i: waiting for magic header */
  16410. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  16411. var TIME = 3; /* i: waiting for modification time (gzip) */
  16412. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  16413. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  16414. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  16415. var NAME = 7; /* i: waiting for end of file name (gzip) */
  16416. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  16417. var HCRC = 9; /* i: waiting for header crc (gzip) */
  16418. var DICTID = 10; /* i: waiting for dictionary check value */
  16419. var DICT = 11; /* waiting for inflateSetDictionary() call */
  16420. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16421. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  16422. var STORED = 14; /* i: waiting for stored size (length and complement) */
  16423. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  16424. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  16425. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  16426. var LENLENS = 18; /* i: waiting for code length code lengths */
  16427. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  16428. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  16429. var LEN = 21; /* i: waiting for length/lit/eob code */
  16430. var LENEXT = 22; /* i: waiting for length extra bits */
  16431. var DIST = 23; /* i: waiting for distance code */
  16432. var DISTEXT = 24; /* i: waiting for distance extra bits */
  16433. var MATCH = 25; /* o: waiting for output space to copy string */
  16434. var LIT = 26; /* o: waiting for output space to write literal */
  16435. var CHECK = 27; /* i: waiting for 32-bit check value */
  16436. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  16437. var DONE = 29; /* finished check, done -- remain here until reset */
  16438. var BAD = 30; /* got a data error -- remain here until reset */
  16439. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  16440. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  16441. /* ===========================================================================*/
  16442. var ENOUGH_LENS = 852;
  16443. var ENOUGH_DISTS = 592;
  16444. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16445. var MAX_WBITS = 15;
  16446. /* 32K LZ77 window */
  16447. var DEF_WBITS = MAX_WBITS;
  16448. function ZSWAP32(q) {
  16449. return (((q >>> 24) & 0xff) +
  16450. ((q >>> 8) & 0xff00) +
  16451. ((q & 0xff00) << 8) +
  16452. ((q & 0xff) << 24));
  16453. }
  16454. function InflateState() {
  16455. this.mode = 0; /* current inflate mode */
  16456. this.last = false; /* true if processing last block */
  16457. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16458. this.havedict = false; /* true if dictionary provided */
  16459. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  16460. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  16461. this.check = 0; /* protected copy of check value */
  16462. this.total = 0; /* protected copy of output count */
  16463. // TODO: may be {}
  16464. this.head = null; /* where to save gzip header information */
  16465. /* sliding window */
  16466. this.wbits = 0; /* log base 2 of requested window size */
  16467. this.wsize = 0; /* window size or zero if not using window */
  16468. this.whave = 0; /* valid bytes in the window */
  16469. this.wnext = 0; /* window write index */
  16470. this.window = null; /* allocated sliding window, if needed */
  16471. /* bit accumulator */
  16472. this.hold = 0; /* input bit accumulator */
  16473. this.bits = 0; /* number of bits in "in" */
  16474. /* for string and stored block copying */
  16475. this.length = 0; /* literal or length of data to copy */
  16476. this.offset = 0; /* distance back to copy string from */
  16477. /* for table and code decoding */
  16478. this.extra = 0; /* extra bits needed */
  16479. /* fixed and dynamic code tables */
  16480. this.lencode = null; /* starting table for length/literal codes */
  16481. this.distcode = null; /* starting table for distance codes */
  16482. this.lenbits = 0; /* index bits for lencode */
  16483. this.distbits = 0; /* index bits for distcode */
  16484. /* dynamic table building */
  16485. this.ncode = 0; /* number of code length code lengths */
  16486. this.nlen = 0; /* number of length code lengths */
  16487. this.ndist = 0; /* number of distance code lengths */
  16488. this.have = 0; /* number of code lengths in lens[] */
  16489. this.next = null; /* next available space in codes[] */
  16490. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  16491. this.work = new utils.Buf16(288); /* work area for code table building */
  16492. /*
  16493. because we don't have pointers in js, we use lencode and distcode directly
  16494. as buffers so we don't need codes
  16495. */
  16496. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  16497. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  16498. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  16499. this.sane = 0; /* if false, allow invalid distance too far */
  16500. this.back = 0; /* bits back of last unprocessed length/lit */
  16501. this.was = 0; /* initial length of match */
  16502. }
  16503. function inflateResetKeep(strm) {
  16504. var state;
  16505. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16506. state = strm.state;
  16507. strm.total_in = strm.total_out = state.total = 0;
  16508. strm.msg = ''; /*Z_NULL*/
  16509. if (state.wrap) { /* to support ill-conceived Java test suite */
  16510. strm.adler = state.wrap & 1;
  16511. }
  16512. state.mode = HEAD;
  16513. state.last = 0;
  16514. state.havedict = 0;
  16515. state.dmax = 32768;
  16516. state.head = null/*Z_NULL*/;
  16517. state.hold = 0;
  16518. state.bits = 0;
  16519. //state.lencode = state.distcode = state.next = state.codes;
  16520. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  16521. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  16522. state.sane = 1;
  16523. state.back = -1;
  16524. //Tracev((stderr, "inflate: reset\n"));
  16525. return Z_OK;
  16526. }
  16527. function inflateReset(strm) {
  16528. var state;
  16529. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16530. state = strm.state;
  16531. state.wsize = 0;
  16532. state.whave = 0;
  16533. state.wnext = 0;
  16534. return inflateResetKeep(strm);
  16535. }
  16536. function inflateReset2(strm, windowBits) {
  16537. var wrap;
  16538. var state;
  16539. /* get the state */
  16540. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16541. state = strm.state;
  16542. /* extract wrap request from windowBits parameter */
  16543. if (windowBits < 0) {
  16544. wrap = 0;
  16545. windowBits = -windowBits;
  16546. }
  16547. else {
  16548. wrap = (windowBits >> 4) + 1;
  16549. if (windowBits < 48) {
  16550. windowBits &= 15;
  16551. }
  16552. }
  16553. /* set number of window bits, free window if different */
  16554. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  16555. return Z_STREAM_ERROR;
  16556. }
  16557. if (state.window !== null && state.wbits !== windowBits) {
  16558. state.window = null;
  16559. }
  16560. /* update state and reset the rest of it */
  16561. state.wrap = wrap;
  16562. state.wbits = windowBits;
  16563. return inflateReset(strm);
  16564. }
  16565. function inflateInit2(strm, windowBits) {
  16566. var ret;
  16567. var state;
  16568. if (!strm) { return Z_STREAM_ERROR; }
  16569. //strm.msg = Z_NULL; /* in case we return an error */
  16570. state = new InflateState();
  16571. //if (state === Z_NULL) return Z_MEM_ERROR;
  16572. //Tracev((stderr, "inflate: allocated\n"));
  16573. strm.state = state;
  16574. state.window = null/*Z_NULL*/;
  16575. ret = inflateReset2(strm, windowBits);
  16576. if (ret !== Z_OK) {
  16577. strm.state = null/*Z_NULL*/;
  16578. }
  16579. return ret;
  16580. }
  16581. function inflateInit(strm) {
  16582. return inflateInit2(strm, DEF_WBITS);
  16583. }
  16584. /*
  16585. Return state with length and distance decoding tables and index sizes set to
  16586. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  16587. If BUILDFIXED is defined, then instead this routine builds the tables the
  16588. first time it's called, and returns those tables the first time and
  16589. thereafter. This reduces the size of the code by about 2K bytes, in
  16590. exchange for a little execution time. However, BUILDFIXED should not be
  16591. used for threaded applications, since the rewriting of the tables and virgin
  16592. may not be thread-safe.
  16593. */
  16594. var virgin = true;
  16595. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  16596. function fixedtables(state) {
  16597. /* build fixed huffman tables if first call (may not be thread safe) */
  16598. if (virgin) {
  16599. var sym;
  16600. lenfix = new utils.Buf32(512);
  16601. distfix = new utils.Buf32(32);
  16602. /* literal/length table */
  16603. sym = 0;
  16604. while (sym < 144) { state.lens[sym++] = 8; }
  16605. while (sym < 256) { state.lens[sym++] = 9; }
  16606. while (sym < 280) { state.lens[sym++] = 7; }
  16607. while (sym < 288) { state.lens[sym++] = 8; }
  16608. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  16609. /* distance table */
  16610. sym = 0;
  16611. while (sym < 32) { state.lens[sym++] = 5; }
  16612. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  16613. /* do this just once */
  16614. virgin = false;
  16615. }
  16616. state.lencode = lenfix;
  16617. state.lenbits = 9;
  16618. state.distcode = distfix;
  16619. state.distbits = 5;
  16620. }
  16621. /*
  16622. Update the window with the last wsize (normally 32K) bytes written before
  16623. returning. If window does not exist yet, create it. This is only called
  16624. when a window is already in use, or when output has been written during this
  16625. inflate call, but the end of the deflate stream has not been reached yet.
  16626. It is also called to create a window for dictionary data when a dictionary
  16627. is loaded.
  16628. Providing output buffers larger than 32K to inflate() should provide a speed
  16629. advantage, since only the last 32K of output is copied to the sliding window
  16630. upon return from inflate(), and since all distances after the first 32K of
  16631. output will fall in the output data, making match copies simpler and faster.
  16632. The advantage may be dependent on the size of the processor's data caches.
  16633. */
  16634. function updatewindow(strm, src, end, copy) {
  16635. var dist;
  16636. var state = strm.state;
  16637. /* if it hasn't been done already, allocate space for the window */
  16638. if (state.window === null) {
  16639. state.wsize = 1 << state.wbits;
  16640. state.wnext = 0;
  16641. state.whave = 0;
  16642. state.window = new utils.Buf8(state.wsize);
  16643. }
  16644. /* copy state->wsize or less output bytes into the circular window */
  16645. if (copy >= state.wsize) {
  16646. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  16647. state.wnext = 0;
  16648. state.whave = state.wsize;
  16649. }
  16650. else {
  16651. dist = state.wsize - state.wnext;
  16652. if (dist > copy) {
  16653. dist = copy;
  16654. }
  16655. //zmemcpy(state->window + state->wnext, end - copy, dist);
  16656. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  16657. copy -= dist;
  16658. if (copy) {
  16659. //zmemcpy(state->window, end - copy, copy);
  16660. utils.arraySet(state.window,src, end - copy, copy, 0);
  16661. state.wnext = copy;
  16662. state.whave = state.wsize;
  16663. }
  16664. else {
  16665. state.wnext += dist;
  16666. if (state.wnext === state.wsize) { state.wnext = 0; }
  16667. if (state.whave < state.wsize) { state.whave += dist; }
  16668. }
  16669. }
  16670. return 0;
  16671. }
  16672. function inflate(strm, flush) {
  16673. var state;
  16674. var input, output; // input/output buffers
  16675. var next; /* next input INDEX */
  16676. var put; /* next output INDEX */
  16677. var have, left; /* available input and output */
  16678. var hold; /* bit buffer */
  16679. var bits; /* bits in bit buffer */
  16680. var _in, _out; /* save starting available input and output */
  16681. var copy; /* number of stored or match bytes to copy */
  16682. var from; /* where to copy match bytes from */
  16683. var from_source;
  16684. var here = 0; /* current decoding table entry */
  16685. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16686. //var last; /* parent table entry */
  16687. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16688. var len; /* length to copy for repeats, bits to drop */
  16689. var ret; /* return code */
  16690. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16691. var opts;
  16692. var n; // temporary var for NEED_BITS
  16693. var order = /* permutation of code lengths */
  16694. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  16695. if (!strm || !strm.state || !strm.output ||
  16696. (!strm.input && strm.avail_in !== 0)) {
  16697. return Z_STREAM_ERROR;
  16698. }
  16699. state = strm.state;
  16700. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16701. //--- LOAD() ---
  16702. put = strm.next_out;
  16703. output = strm.output;
  16704. left = strm.avail_out;
  16705. next = strm.next_in;
  16706. input = strm.input;
  16707. have = strm.avail_in;
  16708. hold = state.hold;
  16709. bits = state.bits;
  16710. //---
  16711. _in = have;
  16712. _out = left;
  16713. ret = Z_OK;
  16714. inf_leave: // goto emulation
  16715. for (;;) {
  16716. switch (state.mode) {
  16717. case HEAD:
  16718. if (state.wrap === 0) {
  16719. state.mode = TYPEDO;
  16720. break;
  16721. }
  16722. //=== NEEDBITS(16);
  16723. while (bits < 16) {
  16724. if (have === 0) { break inf_leave; }
  16725. have--;
  16726. hold += input[next++] << bits;
  16727. bits += 8;
  16728. }
  16729. //===//
  16730. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16731. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16732. //=== CRC2(state.check, hold);
  16733. hbuf[0] = hold & 0xff;
  16734. hbuf[1] = (hold >>> 8) & 0xff;
  16735. state.check = crc32(state.check, hbuf, 2, 0);
  16736. //===//
  16737. //=== INITBITS();
  16738. hold = 0;
  16739. bits = 0;
  16740. //===//
  16741. state.mode = FLAGS;
  16742. break;
  16743. }
  16744. state.flags = 0; /* expect zlib header */
  16745. if (state.head) {
  16746. state.head.done = false;
  16747. }
  16748. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16749. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16750. strm.msg = 'incorrect header check';
  16751. state.mode = BAD;
  16752. break;
  16753. }
  16754. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16755. strm.msg = 'unknown compression method';
  16756. state.mode = BAD;
  16757. break;
  16758. }
  16759. //--- DROPBITS(4) ---//
  16760. hold >>>= 4;
  16761. bits -= 4;
  16762. //---//
  16763. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16764. if (state.wbits === 0) {
  16765. state.wbits = len;
  16766. }
  16767. else if (len > state.wbits) {
  16768. strm.msg = 'invalid window size';
  16769. state.mode = BAD;
  16770. break;
  16771. }
  16772. state.dmax = 1 << len;
  16773. //Tracev((stderr, "inflate: zlib header ok\n"));
  16774. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16775. state.mode = hold & 0x200 ? DICTID : TYPE;
  16776. //=== INITBITS();
  16777. hold = 0;
  16778. bits = 0;
  16779. //===//
  16780. break;
  16781. case FLAGS:
  16782. //=== NEEDBITS(16); */
  16783. while (bits < 16) {
  16784. if (have === 0) { break inf_leave; }
  16785. have--;
  16786. hold += input[next++] << bits;
  16787. bits += 8;
  16788. }
  16789. //===//
  16790. state.flags = hold;
  16791. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16792. strm.msg = 'unknown compression method';
  16793. state.mode = BAD;
  16794. break;
  16795. }
  16796. if (state.flags & 0xe000) {
  16797. strm.msg = 'unknown header flags set';
  16798. state.mode = BAD;
  16799. break;
  16800. }
  16801. if (state.head) {
  16802. state.head.text = ((hold >> 8) & 1);
  16803. }
  16804. if (state.flags & 0x0200) {
  16805. //=== CRC2(state.check, hold);
  16806. hbuf[0] = hold & 0xff;
  16807. hbuf[1] = (hold >>> 8) & 0xff;
  16808. state.check = crc32(state.check, hbuf, 2, 0);
  16809. //===//
  16810. }
  16811. //=== INITBITS();
  16812. hold = 0;
  16813. bits = 0;
  16814. //===//
  16815. state.mode = TIME;
  16816. /* falls through */
  16817. case TIME:
  16818. //=== NEEDBITS(32); */
  16819. while (bits < 32) {
  16820. if (have === 0) { break inf_leave; }
  16821. have--;
  16822. hold += input[next++] << bits;
  16823. bits += 8;
  16824. }
  16825. //===//
  16826. if (state.head) {
  16827. state.head.time = hold;
  16828. }
  16829. if (state.flags & 0x0200) {
  16830. //=== CRC4(state.check, hold)
  16831. hbuf[0] = hold & 0xff;
  16832. hbuf[1] = (hold >>> 8) & 0xff;
  16833. hbuf[2] = (hold >>> 16) & 0xff;
  16834. hbuf[3] = (hold >>> 24) & 0xff;
  16835. state.check = crc32(state.check, hbuf, 4, 0);
  16836. //===
  16837. }
  16838. //=== INITBITS();
  16839. hold = 0;
  16840. bits = 0;
  16841. //===//
  16842. state.mode = OS;
  16843. /* falls through */
  16844. case OS:
  16845. //=== NEEDBITS(16); */
  16846. while (bits < 16) {
  16847. if (have === 0) { break inf_leave; }
  16848. have--;
  16849. hold += input[next++] << bits;
  16850. bits += 8;
  16851. }
  16852. //===//
  16853. if (state.head) {
  16854. state.head.xflags = (hold & 0xff);
  16855. state.head.os = (hold >> 8);
  16856. }
  16857. if (state.flags & 0x0200) {
  16858. //=== CRC2(state.check, hold);
  16859. hbuf[0] = hold & 0xff;
  16860. hbuf[1] = (hold >>> 8) & 0xff;
  16861. state.check = crc32(state.check, hbuf, 2, 0);
  16862. //===//
  16863. }
  16864. //=== INITBITS();
  16865. hold = 0;
  16866. bits = 0;
  16867. //===//
  16868. state.mode = EXLEN;
  16869. /* falls through */
  16870. case EXLEN:
  16871. if (state.flags & 0x0400) {
  16872. //=== NEEDBITS(16); */
  16873. while (bits < 16) {
  16874. if (have === 0) { break inf_leave; }
  16875. have--;
  16876. hold += input[next++] << bits;
  16877. bits += 8;
  16878. }
  16879. //===//
  16880. state.length = hold;
  16881. if (state.head) {
  16882. state.head.extra_len = hold;
  16883. }
  16884. if (state.flags & 0x0200) {
  16885. //=== CRC2(state.check, hold);
  16886. hbuf[0] = hold & 0xff;
  16887. hbuf[1] = (hold >>> 8) & 0xff;
  16888. state.check = crc32(state.check, hbuf, 2, 0);
  16889. //===//
  16890. }
  16891. //=== INITBITS();
  16892. hold = 0;
  16893. bits = 0;
  16894. //===//
  16895. }
  16896. else if (state.head) {
  16897. state.head.extra = null/*Z_NULL*/;
  16898. }
  16899. state.mode = EXTRA;
  16900. /* falls through */
  16901. case EXTRA:
  16902. if (state.flags & 0x0400) {
  16903. copy = state.length;
  16904. if (copy > have) { copy = have; }
  16905. if (copy) {
  16906. if (state.head) {
  16907. len = state.head.extra_len - state.length;
  16908. if (!state.head.extra) {
  16909. // Use untyped array for more conveniend processing later
  16910. state.head.extra = new Array(state.head.extra_len);
  16911. }
  16912. utils.arraySet(
  16913. state.head.extra,
  16914. input,
  16915. next,
  16916. // extra field is limited to 65536 bytes
  16917. // - no need for additional size check
  16918. copy,
  16919. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  16920. len
  16921. );
  16922. //zmemcpy(state.head.extra + len, next,
  16923. // len + copy > state.head.extra_max ?
  16924. // state.head.extra_max - len : copy);
  16925. }
  16926. if (state.flags & 0x0200) {
  16927. state.check = crc32(state.check, input, copy, next);
  16928. }
  16929. have -= copy;
  16930. next += copy;
  16931. state.length -= copy;
  16932. }
  16933. if (state.length) { break inf_leave; }
  16934. }
  16935. state.length = 0;
  16936. state.mode = NAME;
  16937. /* falls through */
  16938. case NAME:
  16939. if (state.flags & 0x0800) {
  16940. if (have === 0) { break inf_leave; }
  16941. copy = 0;
  16942. do {
  16943. // TODO: 2 or 1 bytes?
  16944. len = input[next + copy++];
  16945. /* use constant limit because in js we should not preallocate memory */
  16946. if (state.head && len &&
  16947. (state.length < 65536 /*state.head.name_max*/)) {
  16948. state.head.name += String.fromCharCode(len);
  16949. }
  16950. } while (len && copy < have);
  16951. if (state.flags & 0x0200) {
  16952. state.check = crc32(state.check, input, copy, next);
  16953. }
  16954. have -= copy;
  16955. next += copy;
  16956. if (len) { break inf_leave; }
  16957. }
  16958. else if (state.head) {
  16959. state.head.name = null;
  16960. }
  16961. state.length = 0;
  16962. state.mode = COMMENT;
  16963. /* falls through */
  16964. case COMMENT:
  16965. if (state.flags & 0x1000) {
  16966. if (have === 0) { break inf_leave; }
  16967. copy = 0;
  16968. do {
  16969. len = input[next + copy++];
  16970. /* use constant limit because in js we should not preallocate memory */
  16971. if (state.head && len &&
  16972. (state.length < 65536 /*state.head.comm_max*/)) {
  16973. state.head.comment += String.fromCharCode(len);
  16974. }
  16975. } while (len && copy < have);
  16976. if (state.flags & 0x0200) {
  16977. state.check = crc32(state.check, input, copy, next);
  16978. }
  16979. have -= copy;
  16980. next += copy;
  16981. if (len) { break inf_leave; }
  16982. }
  16983. else if (state.head) {
  16984. state.head.comment = null;
  16985. }
  16986. state.mode = HCRC;
  16987. /* falls through */
  16988. case HCRC:
  16989. if (state.flags & 0x0200) {
  16990. //=== NEEDBITS(16); */
  16991. while (bits < 16) {
  16992. if (have === 0) { break inf_leave; }
  16993. have--;
  16994. hold += input[next++] << bits;
  16995. bits += 8;
  16996. }
  16997. //===//
  16998. if (hold !== (state.check & 0xffff)) {
  16999. strm.msg = 'header crc mismatch';
  17000. state.mode = BAD;
  17001. break;
  17002. }
  17003. //=== INITBITS();
  17004. hold = 0;
  17005. bits = 0;
  17006. //===//
  17007. }
  17008. if (state.head) {
  17009. state.head.hcrc = ((state.flags >> 9) & 1);
  17010. state.head.done = true;
  17011. }
  17012. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  17013. state.mode = TYPE;
  17014. break;
  17015. case DICTID:
  17016. //=== NEEDBITS(32); */
  17017. while (bits < 32) {
  17018. if (have === 0) { break inf_leave; }
  17019. have--;
  17020. hold += input[next++] << bits;
  17021. bits += 8;
  17022. }
  17023. //===//
  17024. strm.adler = state.check = ZSWAP32(hold);
  17025. //=== INITBITS();
  17026. hold = 0;
  17027. bits = 0;
  17028. //===//
  17029. state.mode = DICT;
  17030. /* falls through */
  17031. case DICT:
  17032. if (state.havedict === 0) {
  17033. //--- RESTORE() ---
  17034. strm.next_out = put;
  17035. strm.avail_out = left;
  17036. strm.next_in = next;
  17037. strm.avail_in = have;
  17038. state.hold = hold;
  17039. state.bits = bits;
  17040. //---
  17041. return Z_NEED_DICT;
  17042. }
  17043. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17044. state.mode = TYPE;
  17045. /* falls through */
  17046. case TYPE:
  17047. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  17048. /* falls through */
  17049. case TYPEDO:
  17050. if (state.last) {
  17051. //--- BYTEBITS() ---//
  17052. hold >>>= bits & 7;
  17053. bits -= bits & 7;
  17054. //---//
  17055. state.mode = CHECK;
  17056. break;
  17057. }
  17058. //=== NEEDBITS(3); */
  17059. while (bits < 3) {
  17060. if (have === 0) { break inf_leave; }
  17061. have--;
  17062. hold += input[next++] << bits;
  17063. bits += 8;
  17064. }
  17065. //===//
  17066. state.last = (hold & 0x01)/*BITS(1)*/;
  17067. //--- DROPBITS(1) ---//
  17068. hold >>>= 1;
  17069. bits -= 1;
  17070. //---//
  17071. switch ((hold & 0x03)/*BITS(2)*/) {
  17072. case 0: /* stored block */
  17073. //Tracev((stderr, "inflate: stored block%s\n",
  17074. // state.last ? " (last)" : ""));
  17075. state.mode = STORED;
  17076. break;
  17077. case 1: /* fixed block */
  17078. fixedtables(state);
  17079. //Tracev((stderr, "inflate: fixed codes block%s\n",
  17080. // state.last ? " (last)" : ""));
  17081. state.mode = LEN_; /* decode codes */
  17082. if (flush === Z_TREES) {
  17083. //--- DROPBITS(2) ---//
  17084. hold >>>= 2;
  17085. bits -= 2;
  17086. //---//
  17087. break inf_leave;
  17088. }
  17089. break;
  17090. case 2: /* dynamic block */
  17091. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  17092. // state.last ? " (last)" : ""));
  17093. state.mode = TABLE;
  17094. break;
  17095. case 3:
  17096. strm.msg = 'invalid block type';
  17097. state.mode = BAD;
  17098. }
  17099. //--- DROPBITS(2) ---//
  17100. hold >>>= 2;
  17101. bits -= 2;
  17102. //---//
  17103. break;
  17104. case STORED:
  17105. //--- BYTEBITS() ---// /* go to byte boundary */
  17106. hold >>>= bits & 7;
  17107. bits -= bits & 7;
  17108. //---//
  17109. //=== NEEDBITS(32); */
  17110. while (bits < 32) {
  17111. if (have === 0) { break inf_leave; }
  17112. have--;
  17113. hold += input[next++] << bits;
  17114. bits += 8;
  17115. }
  17116. //===//
  17117. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  17118. strm.msg = 'invalid stored block lengths';
  17119. state.mode = BAD;
  17120. break;
  17121. }
  17122. state.length = hold & 0xffff;
  17123. //Tracev((stderr, "inflate: stored length %u\n",
  17124. // state.length));
  17125. //=== INITBITS();
  17126. hold = 0;
  17127. bits = 0;
  17128. //===//
  17129. state.mode = COPY_;
  17130. if (flush === Z_TREES) { break inf_leave; }
  17131. /* falls through */
  17132. case COPY_:
  17133. state.mode = COPY;
  17134. /* falls through */
  17135. case COPY:
  17136. copy = state.length;
  17137. if (copy) {
  17138. if (copy > have) { copy = have; }
  17139. if (copy > left) { copy = left; }
  17140. if (copy === 0) { break inf_leave; }
  17141. //--- zmemcpy(put, next, copy); ---
  17142. utils.arraySet(output, input, next, copy, put);
  17143. //---//
  17144. have -= copy;
  17145. next += copy;
  17146. left -= copy;
  17147. put += copy;
  17148. state.length -= copy;
  17149. break;
  17150. }
  17151. //Tracev((stderr, "inflate: stored end\n"));
  17152. state.mode = TYPE;
  17153. break;
  17154. case TABLE:
  17155. //=== NEEDBITS(14); */
  17156. while (bits < 14) {
  17157. if (have === 0) { break inf_leave; }
  17158. have--;
  17159. hold += input[next++] << bits;
  17160. bits += 8;
  17161. }
  17162. //===//
  17163. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  17164. //--- DROPBITS(5) ---//
  17165. hold >>>= 5;
  17166. bits -= 5;
  17167. //---//
  17168. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  17169. //--- DROPBITS(5) ---//
  17170. hold >>>= 5;
  17171. bits -= 5;
  17172. //---//
  17173. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  17174. //--- DROPBITS(4) ---//
  17175. hold >>>= 4;
  17176. bits -= 4;
  17177. //---//
  17178. //#ifndef PKZIP_BUG_WORKAROUND
  17179. if (state.nlen > 286 || state.ndist > 30) {
  17180. strm.msg = 'too many length or distance symbols';
  17181. state.mode = BAD;
  17182. break;
  17183. }
  17184. //#endif
  17185. //Tracev((stderr, "inflate: table sizes ok\n"));
  17186. state.have = 0;
  17187. state.mode = LENLENS;
  17188. /* falls through */
  17189. case LENLENS:
  17190. while (state.have < state.ncode) {
  17191. //=== NEEDBITS(3);
  17192. while (bits < 3) {
  17193. if (have === 0) { break inf_leave; }
  17194. have--;
  17195. hold += input[next++] << bits;
  17196. bits += 8;
  17197. }
  17198. //===//
  17199. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  17200. //--- DROPBITS(3) ---//
  17201. hold >>>= 3;
  17202. bits -= 3;
  17203. //---//
  17204. }
  17205. while (state.have < 19) {
  17206. state.lens[order[state.have++]] = 0;
  17207. }
  17208. // We have separate tables & no pointers. 2 commented lines below not needed.
  17209. //state.next = state.codes;
  17210. //state.lencode = state.next;
  17211. // Switch to use dynamic table
  17212. state.lencode = state.lendyn;
  17213. state.lenbits = 7;
  17214. opts = {bits: state.lenbits};
  17215. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  17216. state.lenbits = opts.bits;
  17217. if (ret) {
  17218. strm.msg = 'invalid code lengths set';
  17219. state.mode = BAD;
  17220. break;
  17221. }
  17222. //Tracev((stderr, "inflate: code lengths ok\n"));
  17223. state.have = 0;
  17224. state.mode = CODELENS;
  17225. /* falls through */
  17226. case CODELENS:
  17227. while (state.have < state.nlen + state.ndist) {
  17228. for (;;) {
  17229. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  17230. here_bits = here >>> 24;
  17231. here_op = (here >>> 16) & 0xff;
  17232. here_val = here & 0xffff;
  17233. if ((here_bits) <= bits) { break; }
  17234. //--- PULLBYTE() ---//
  17235. if (have === 0) { break inf_leave; }
  17236. have--;
  17237. hold += input[next++] << bits;
  17238. bits += 8;
  17239. //---//
  17240. }
  17241. if (here_val < 16) {
  17242. //--- DROPBITS(here.bits) ---//
  17243. hold >>>= here_bits;
  17244. bits -= here_bits;
  17245. //---//
  17246. state.lens[state.have++] = here_val;
  17247. }
  17248. else {
  17249. if (here_val === 16) {
  17250. //=== NEEDBITS(here.bits + 2);
  17251. n = here_bits + 2;
  17252. while (bits < n) {
  17253. if (have === 0) { break inf_leave; }
  17254. have--;
  17255. hold += input[next++] << bits;
  17256. bits += 8;
  17257. }
  17258. //===//
  17259. //--- DROPBITS(here.bits) ---//
  17260. hold >>>= here_bits;
  17261. bits -= here_bits;
  17262. //---//
  17263. if (state.have === 0) {
  17264. strm.msg = 'invalid bit length repeat';
  17265. state.mode = BAD;
  17266. break;
  17267. }
  17268. len = state.lens[state.have - 1];
  17269. copy = 3 + (hold & 0x03);//BITS(2);
  17270. //--- DROPBITS(2) ---//
  17271. hold >>>= 2;
  17272. bits -= 2;
  17273. //---//
  17274. }
  17275. else if (here_val === 17) {
  17276. //=== NEEDBITS(here.bits + 3);
  17277. n = here_bits + 3;
  17278. while (bits < n) {
  17279. if (have === 0) { break inf_leave; }
  17280. have--;
  17281. hold += input[next++] << bits;
  17282. bits += 8;
  17283. }
  17284. //===//
  17285. //--- DROPBITS(here.bits) ---//
  17286. hold >>>= here_bits;
  17287. bits -= here_bits;
  17288. //---//
  17289. len = 0;
  17290. copy = 3 + (hold & 0x07);//BITS(3);
  17291. //--- DROPBITS(3) ---//
  17292. hold >>>= 3;
  17293. bits -= 3;
  17294. //---//
  17295. }
  17296. else {
  17297. //=== NEEDBITS(here.bits + 7);
  17298. n = here_bits + 7;
  17299. while (bits < n) {
  17300. if (have === 0) { break inf_leave; }
  17301. have--;
  17302. hold += input[next++] << bits;
  17303. bits += 8;
  17304. }
  17305. //===//
  17306. //--- DROPBITS(here.bits) ---//
  17307. hold >>>= here_bits;
  17308. bits -= here_bits;
  17309. //---//
  17310. len = 0;
  17311. copy = 11 + (hold & 0x7f);//BITS(7);
  17312. //--- DROPBITS(7) ---//
  17313. hold >>>= 7;
  17314. bits -= 7;
  17315. //---//
  17316. }
  17317. if (state.have + copy > state.nlen + state.ndist) {
  17318. strm.msg = 'invalid bit length repeat';
  17319. state.mode = BAD;
  17320. break;
  17321. }
  17322. while (copy--) {
  17323. state.lens[state.have++] = len;
  17324. }
  17325. }
  17326. }
  17327. /* handle error breaks in while */
  17328. if (state.mode === BAD) { break; }
  17329. /* check for end-of-block code (better have one) */
  17330. if (state.lens[256] === 0) {
  17331. strm.msg = 'invalid code -- missing end-of-block';
  17332. state.mode = BAD;
  17333. break;
  17334. }
  17335. /* build code tables -- note: do not change the lenbits or distbits
  17336. values here (9 and 6) without reading the comments in inftrees.h
  17337. concerning the ENOUGH constants, which depend on those values */
  17338. state.lenbits = 9;
  17339. opts = {bits: state.lenbits};
  17340. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  17341. // We have separate tables & no pointers. 2 commented lines below not needed.
  17342. // state.next_index = opts.table_index;
  17343. state.lenbits = opts.bits;
  17344. // state.lencode = state.next;
  17345. if (ret) {
  17346. strm.msg = 'invalid literal/lengths set';
  17347. state.mode = BAD;
  17348. break;
  17349. }
  17350. state.distbits = 6;
  17351. //state.distcode.copy(state.codes);
  17352. // Switch to use dynamic table
  17353. state.distcode = state.distdyn;
  17354. opts = {bits: state.distbits};
  17355. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  17356. // We have separate tables & no pointers. 2 commented lines below not needed.
  17357. // state.next_index = opts.table_index;
  17358. state.distbits = opts.bits;
  17359. // state.distcode = state.next;
  17360. if (ret) {
  17361. strm.msg = 'invalid distances set';
  17362. state.mode = BAD;
  17363. break;
  17364. }
  17365. //Tracev((stderr, 'inflate: codes ok\n'));
  17366. state.mode = LEN_;
  17367. if (flush === Z_TREES) { break inf_leave; }
  17368. /* falls through */
  17369. case LEN_:
  17370. state.mode = LEN;
  17371. /* falls through */
  17372. case LEN:
  17373. if (have >= 6 && left >= 258) {
  17374. //--- RESTORE() ---
  17375. strm.next_out = put;
  17376. strm.avail_out = left;
  17377. strm.next_in = next;
  17378. strm.avail_in = have;
  17379. state.hold = hold;
  17380. state.bits = bits;
  17381. //---
  17382. inflate_fast(strm, _out);
  17383. //--- LOAD() ---
  17384. put = strm.next_out;
  17385. output = strm.output;
  17386. left = strm.avail_out;
  17387. next = strm.next_in;
  17388. input = strm.input;
  17389. have = strm.avail_in;
  17390. hold = state.hold;
  17391. bits = state.bits;
  17392. //---
  17393. if (state.mode === TYPE) {
  17394. state.back = -1;
  17395. }
  17396. break;
  17397. }
  17398. state.back = 0;
  17399. for (;;) {
  17400. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  17401. here_bits = here >>> 24;
  17402. here_op = (here >>> 16) & 0xff;
  17403. here_val = here & 0xffff;
  17404. if (here_bits <= bits) { break; }
  17405. //--- PULLBYTE() ---//
  17406. if (have === 0) { break inf_leave; }
  17407. have--;
  17408. hold += input[next++] << bits;
  17409. bits += 8;
  17410. //---//
  17411. }
  17412. if (here_op && (here_op & 0xf0) === 0) {
  17413. last_bits = here_bits;
  17414. last_op = here_op;
  17415. last_val = here_val;
  17416. for (;;) {
  17417. here = state.lencode[last_val +
  17418. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17419. here_bits = here >>> 24;
  17420. here_op = (here >>> 16) & 0xff;
  17421. here_val = here & 0xffff;
  17422. if ((last_bits + here_bits) <= bits) { break; }
  17423. //--- PULLBYTE() ---//
  17424. if (have === 0) { break inf_leave; }
  17425. have--;
  17426. hold += input[next++] << bits;
  17427. bits += 8;
  17428. //---//
  17429. }
  17430. //--- DROPBITS(last.bits) ---//
  17431. hold >>>= last_bits;
  17432. bits -= last_bits;
  17433. //---//
  17434. state.back += last_bits;
  17435. }
  17436. //--- DROPBITS(here.bits) ---//
  17437. hold >>>= here_bits;
  17438. bits -= here_bits;
  17439. //---//
  17440. state.back += here_bits;
  17441. state.length = here_val;
  17442. if (here_op === 0) {
  17443. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17444. // "inflate: literal '%c'\n" :
  17445. // "inflate: literal 0x%02x\n", here.val));
  17446. state.mode = LIT;
  17447. break;
  17448. }
  17449. if (here_op & 32) {
  17450. //Tracevv((stderr, "inflate: end of block\n"));
  17451. state.back = -1;
  17452. state.mode = TYPE;
  17453. break;
  17454. }
  17455. if (here_op & 64) {
  17456. strm.msg = 'invalid literal/length code';
  17457. state.mode = BAD;
  17458. break;
  17459. }
  17460. state.extra = here_op & 15;
  17461. state.mode = LENEXT;
  17462. /* falls through */
  17463. case LENEXT:
  17464. if (state.extra) {
  17465. //=== NEEDBITS(state.extra);
  17466. n = state.extra;
  17467. while (bits < n) {
  17468. if (have === 0) { break inf_leave; }
  17469. have--;
  17470. hold += input[next++] << bits;
  17471. bits += 8;
  17472. }
  17473. //===//
  17474. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17475. //--- DROPBITS(state.extra) ---//
  17476. hold >>>= state.extra;
  17477. bits -= state.extra;
  17478. //---//
  17479. state.back += state.extra;
  17480. }
  17481. //Tracevv((stderr, "inflate: length %u\n", state.length));
  17482. state.was = state.length;
  17483. state.mode = DIST;
  17484. /* falls through */
  17485. case DIST:
  17486. for (;;) {
  17487. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  17488. here_bits = here >>> 24;
  17489. here_op = (here >>> 16) & 0xff;
  17490. here_val = here & 0xffff;
  17491. if ((here_bits) <= bits) { break; }
  17492. //--- PULLBYTE() ---//
  17493. if (have === 0) { break inf_leave; }
  17494. have--;
  17495. hold += input[next++] << bits;
  17496. bits += 8;
  17497. //---//
  17498. }
  17499. if ((here_op & 0xf0) === 0) {
  17500. last_bits = here_bits;
  17501. last_op = here_op;
  17502. last_val = here_val;
  17503. for (;;) {
  17504. here = state.distcode[last_val +
  17505. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  17506. here_bits = here >>> 24;
  17507. here_op = (here >>> 16) & 0xff;
  17508. here_val = here & 0xffff;
  17509. if ((last_bits + here_bits) <= bits) { break; }
  17510. //--- PULLBYTE() ---//
  17511. if (have === 0) { break inf_leave; }
  17512. have--;
  17513. hold += input[next++] << bits;
  17514. bits += 8;
  17515. //---//
  17516. }
  17517. //--- DROPBITS(last.bits) ---//
  17518. hold >>>= last_bits;
  17519. bits -= last_bits;
  17520. //---//
  17521. state.back += last_bits;
  17522. }
  17523. //--- DROPBITS(here.bits) ---//
  17524. hold >>>= here_bits;
  17525. bits -= here_bits;
  17526. //---//
  17527. state.back += here_bits;
  17528. if (here_op & 64) {
  17529. strm.msg = 'invalid distance code';
  17530. state.mode = BAD;
  17531. break;
  17532. }
  17533. state.offset = here_val;
  17534. state.extra = (here_op) & 15;
  17535. state.mode = DISTEXT;
  17536. /* falls through */
  17537. case DISTEXT:
  17538. if (state.extra) {
  17539. //=== NEEDBITS(state.extra);
  17540. n = state.extra;
  17541. while (bits < n) {
  17542. if (have === 0) { break inf_leave; }
  17543. have--;
  17544. hold += input[next++] << bits;
  17545. bits += 8;
  17546. }
  17547. //===//
  17548. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  17549. //--- DROPBITS(state.extra) ---//
  17550. hold >>>= state.extra;
  17551. bits -= state.extra;
  17552. //---//
  17553. state.back += state.extra;
  17554. }
  17555. //#ifdef INFLATE_STRICT
  17556. if (state.offset > state.dmax) {
  17557. strm.msg = 'invalid distance too far back';
  17558. state.mode = BAD;
  17559. break;
  17560. }
  17561. //#endif
  17562. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  17563. state.mode = MATCH;
  17564. /* falls through */
  17565. case MATCH:
  17566. if (left === 0) { break inf_leave; }
  17567. copy = _out - left;
  17568. if (state.offset > copy) { /* copy from window */
  17569. copy = state.offset - copy;
  17570. if (copy > state.whave) {
  17571. if (state.sane) {
  17572. strm.msg = 'invalid distance too far back';
  17573. state.mode = BAD;
  17574. break;
  17575. }
  17576. // (!) This block is disabled in zlib defailts,
  17577. // don't enable it for binary compatibility
  17578. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17579. // Trace((stderr, "inflate.c too far\n"));
  17580. // copy -= state.whave;
  17581. // if (copy > state.length) { copy = state.length; }
  17582. // if (copy > left) { copy = left; }
  17583. // left -= copy;
  17584. // state.length -= copy;
  17585. // do {
  17586. // output[put++] = 0;
  17587. // } while (--copy);
  17588. // if (state.length === 0) { state.mode = LEN; }
  17589. // break;
  17590. //#endif
  17591. }
  17592. if (copy > state.wnext) {
  17593. copy -= state.wnext;
  17594. from = state.wsize - copy;
  17595. }
  17596. else {
  17597. from = state.wnext - copy;
  17598. }
  17599. if (copy > state.length) { copy = state.length; }
  17600. from_source = state.window;
  17601. }
  17602. else { /* copy from output */
  17603. from_source = output;
  17604. from = put - state.offset;
  17605. copy = state.length;
  17606. }
  17607. if (copy > left) { copy = left; }
  17608. left -= copy;
  17609. state.length -= copy;
  17610. do {
  17611. output[put++] = from_source[from++];
  17612. } while (--copy);
  17613. if (state.length === 0) { state.mode = LEN; }
  17614. break;
  17615. case LIT:
  17616. if (left === 0) { break inf_leave; }
  17617. output[put++] = state.length;
  17618. left--;
  17619. state.mode = LEN;
  17620. break;
  17621. case CHECK:
  17622. if (state.wrap) {
  17623. //=== NEEDBITS(32);
  17624. while (bits < 32) {
  17625. if (have === 0) { break inf_leave; }
  17626. have--;
  17627. // Use '|' insdead of '+' to make sure that result is signed
  17628. hold |= input[next++] << bits;
  17629. bits += 8;
  17630. }
  17631. //===//
  17632. _out -= left;
  17633. strm.total_out += _out;
  17634. state.total += _out;
  17635. if (_out) {
  17636. strm.adler = state.check =
  17637. /*UPDATE(state.check, put - _out, _out);*/
  17638. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  17639. }
  17640. _out = left;
  17641. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  17642. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  17643. strm.msg = 'incorrect data check';
  17644. state.mode = BAD;
  17645. break;
  17646. }
  17647. //=== INITBITS();
  17648. hold = 0;
  17649. bits = 0;
  17650. //===//
  17651. //Tracev((stderr, "inflate: check matches trailer\n"));
  17652. }
  17653. state.mode = LENGTH;
  17654. /* falls through */
  17655. case LENGTH:
  17656. if (state.wrap && state.flags) {
  17657. //=== NEEDBITS(32);
  17658. while (bits < 32) {
  17659. if (have === 0) { break inf_leave; }
  17660. have--;
  17661. hold += input[next++] << bits;
  17662. bits += 8;
  17663. }
  17664. //===//
  17665. if (hold !== (state.total & 0xffffffff)) {
  17666. strm.msg = 'incorrect length check';
  17667. state.mode = BAD;
  17668. break;
  17669. }
  17670. //=== INITBITS();
  17671. hold = 0;
  17672. bits = 0;
  17673. //===//
  17674. //Tracev((stderr, "inflate: length matches trailer\n"));
  17675. }
  17676. state.mode = DONE;
  17677. /* falls through */
  17678. case DONE:
  17679. ret = Z_STREAM_END;
  17680. break inf_leave;
  17681. case BAD:
  17682. ret = Z_DATA_ERROR;
  17683. break inf_leave;
  17684. case MEM:
  17685. return Z_MEM_ERROR;
  17686. case SYNC:
  17687. /* falls through */
  17688. default:
  17689. return Z_STREAM_ERROR;
  17690. }
  17691. }
  17692. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17693. /*
  17694. Return from inflate(), updating the total counts and the check value.
  17695. If there was no progress during the inflate() call, return a buffer
  17696. error. Call updatewindow() to create and/or update the window state.
  17697. Note: a memory error from inflate() is non-recoverable.
  17698. */
  17699. //--- RESTORE() ---
  17700. strm.next_out = put;
  17701. strm.avail_out = left;
  17702. strm.next_in = next;
  17703. strm.avail_in = have;
  17704. state.hold = hold;
  17705. state.bits = bits;
  17706. //---
  17707. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17708. (state.mode < CHECK || flush !== Z_FINISH))) {
  17709. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17710. state.mode = MEM;
  17711. return Z_MEM_ERROR;
  17712. }
  17713. }
  17714. _in -= strm.avail_in;
  17715. _out -= strm.avail_out;
  17716. strm.total_in += _in;
  17717. strm.total_out += _out;
  17718. state.total += _out;
  17719. if (state.wrap && _out) {
  17720. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17721. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17722. }
  17723. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17724. (state.mode === TYPE ? 128 : 0) +
  17725. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17726. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17727. ret = Z_BUF_ERROR;
  17728. }
  17729. return ret;
  17730. }
  17731. function inflateEnd(strm) {
  17732. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17733. return Z_STREAM_ERROR;
  17734. }
  17735. var state = strm.state;
  17736. if (state.window) {
  17737. state.window = null;
  17738. }
  17739. strm.state = null;
  17740. return Z_OK;
  17741. }
  17742. function inflateGetHeader(strm, head) {
  17743. var state;
  17744. /* check state */
  17745. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17746. state = strm.state;
  17747. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17748. /* save header structure */
  17749. state.head = head;
  17750. head.done = false;
  17751. return Z_OK;
  17752. }
  17753. exports.inflateReset = inflateReset;
  17754. exports.inflateReset2 = inflateReset2;
  17755. exports.inflateResetKeep = inflateResetKeep;
  17756. exports.inflateInit = inflateInit;
  17757. exports.inflateInit2 = inflateInit2;
  17758. exports.inflate = inflate;
  17759. exports.inflateEnd = inflateEnd;
  17760. exports.inflateGetHeader = inflateGetHeader;
  17761. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17762. /* Not implemented
  17763. exports.inflateCopy = inflateCopy;
  17764. exports.inflateGetDictionary = inflateGetDictionary;
  17765. exports.inflateMark = inflateMark;
  17766. exports.inflatePrime = inflatePrime;
  17767. exports.inflateSetDictionary = inflateSetDictionary;
  17768. exports.inflateSync = inflateSync;
  17769. exports.inflateSyncPoint = inflateSyncPoint;
  17770. exports.inflateUndermine = inflateUndermine;
  17771. */
  17772. },{"../utils/common":52,"./adler32":54,"./crc32":56,"./inffast":59,"./inftrees":61}],61:[function(require,module,exports){
  17773. 'use strict';
  17774. var utils = require('../utils/common');
  17775. var MAXBITS = 15;
  17776. var ENOUGH_LENS = 852;
  17777. var ENOUGH_DISTS = 592;
  17778. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17779. var CODES = 0;
  17780. var LENS = 1;
  17781. var DISTS = 2;
  17782. var lbase = [ /* Length codes 257..285 base */
  17783. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17784. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17785. ];
  17786. var lext = [ /* Length codes 257..285 extra */
  17787. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17788. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17789. ];
  17790. var dbase = [ /* Distance codes 0..29 base */
  17791. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17792. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17793. 8193, 12289, 16385, 24577, 0, 0
  17794. ];
  17795. var dext = [ /* Distance codes 0..29 extra */
  17796. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17797. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17798. 28, 28, 29, 29, 64, 64
  17799. ];
  17800. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17801. {
  17802. var bits = opts.bits;
  17803. //here = opts.here; /* table entry for duplication */
  17804. var len = 0; /* a code's length in bits */
  17805. var sym = 0; /* index of code symbols */
  17806. var min = 0, max = 0; /* minimum and maximum code lengths */
  17807. var root = 0; /* number of index bits for root table */
  17808. var curr = 0; /* number of index bits for current table */
  17809. var drop = 0; /* code bits to drop for sub-table */
  17810. var left = 0; /* number of prefix codes available */
  17811. var used = 0; /* code entries in table used */
  17812. var huff = 0; /* Huffman code */
  17813. var incr; /* for incrementing code, index */
  17814. var fill; /* index for replicating entries */
  17815. var low; /* low bits for current root entry */
  17816. var mask; /* mask for low root bits */
  17817. var next; /* next available space in table */
  17818. var base = null; /* base value table to use */
  17819. var base_index = 0;
  17820. // var shoextra; /* extra bits table to use */
  17821. var end; /* use base and extra for symbol > end */
  17822. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17823. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17824. var extra = null;
  17825. var extra_index = 0;
  17826. var here_bits, here_op, here_val;
  17827. /*
  17828. Process a set of code lengths to create a canonical Huffman code. The
  17829. code lengths are lens[0..codes-1]. Each length corresponds to the
  17830. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17831. symbols by length from short to long, and retaining the symbol order
  17832. for codes with equal lengths. Then the code starts with all zero bits
  17833. for the first code of the shortest length, and the codes are integer
  17834. increments for the same length, and zeros are appended as the length
  17835. increases. For the deflate format, these bits are stored backwards
  17836. from their more natural integer increment ordering, and so when the
  17837. decoding tables are built in the large loop below, the integer codes
  17838. are incremented backwards.
  17839. This routine assumes, but does not check, that all of the entries in
  17840. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17841. 1..MAXBITS is interpreted as that code length. zero means that that
  17842. symbol does not occur in this code.
  17843. The codes are sorted by computing a count of codes for each length,
  17844. creating from that a table of starting indices for each length in the
  17845. sorted table, and then entering the symbols in order in the sorted
  17846. table. The sorted table is work[], with that space being provided by
  17847. the caller.
  17848. The length counts are used for other purposes as well, i.e. finding
  17849. the minimum and maximum length codes, determining if there are any
  17850. codes at all, checking for a valid set of lengths, and looking ahead
  17851. at length counts to determine sub-table sizes when building the
  17852. decoding tables.
  17853. */
  17854. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17855. for (len = 0; len <= MAXBITS; len++) {
  17856. count[len] = 0;
  17857. }
  17858. for (sym = 0; sym < codes; sym++) {
  17859. count[lens[lens_index + sym]]++;
  17860. }
  17861. /* bound code lengths, force root to be within code lengths */
  17862. root = bits;
  17863. for (max = MAXBITS; max >= 1; max--) {
  17864. if (count[max] !== 0) { break; }
  17865. }
  17866. if (root > max) {
  17867. root = max;
  17868. }
  17869. if (max === 0) { /* no symbols to code at all */
  17870. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17871. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17872. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17873. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17874. //table.op[opts.table_index] = 64;
  17875. //table.bits[opts.table_index] = 1;
  17876. //table.val[opts.table_index++] = 0;
  17877. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17878. opts.bits = 1;
  17879. return 0; /* no symbols, but wait for decoding to report error */
  17880. }
  17881. for (min = 1; min < max; min++) {
  17882. if (count[min] !== 0) { break; }
  17883. }
  17884. if (root < min) {
  17885. root = min;
  17886. }
  17887. /* check for an over-subscribed or incomplete set of lengths */
  17888. left = 1;
  17889. for (len = 1; len <= MAXBITS; len++) {
  17890. left <<= 1;
  17891. left -= count[len];
  17892. if (left < 0) {
  17893. return -1;
  17894. } /* over-subscribed */
  17895. }
  17896. if (left > 0 && (type === CODES || max !== 1)) {
  17897. return -1; /* incomplete set */
  17898. }
  17899. /* generate offsets into symbol table for each length for sorting */
  17900. offs[1] = 0;
  17901. for (len = 1; len < MAXBITS; len++) {
  17902. offs[len + 1] = offs[len] + count[len];
  17903. }
  17904. /* sort symbols by length, by symbol order within each length */
  17905. for (sym = 0; sym < codes; sym++) {
  17906. if (lens[lens_index + sym] !== 0) {
  17907. work[offs[lens[lens_index + sym]]++] = sym;
  17908. }
  17909. }
  17910. /*
  17911. Create and fill in decoding tables. In this loop, the table being
  17912. filled is at next and has curr index bits. The code being used is huff
  17913. with length len. That code is converted to an index by dropping drop
  17914. bits off of the bottom. For codes where len is less than drop + curr,
  17915. those top drop + curr - len bits are incremented through all values to
  17916. fill the table with replicated entries.
  17917. root is the number of index bits for the root table. When len exceeds
  17918. root, sub-tables are created pointed to by the root entry with an index
  17919. of the low root bits of huff. This is saved in low to check for when a
  17920. new sub-table should be started. drop is zero when the root table is
  17921. being filled, and drop is root when sub-tables are being filled.
  17922. When a new sub-table is needed, it is necessary to look ahead in the
  17923. code lengths to determine what size sub-table is needed. The length
  17924. counts are used for this, and so count[] is decremented as codes are
  17925. entered in the tables.
  17926. used keeps track of how many table entries have been allocated from the
  17927. provided *table space. It is checked for LENS and DIST tables against
  17928. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  17929. the initial root table size constants. See the comments in inftrees.h
  17930. for more information.
  17931. sym increments through all symbols, and the loop terminates when
  17932. all codes of length max, i.e. all codes, have been processed. This
  17933. routine permits incomplete codes, so another loop after this one fills
  17934. in the rest of the decoding tables with invalid code markers.
  17935. */
  17936. /* set up for code type */
  17937. // poor man optimization - use if-else instead of switch,
  17938. // to avoid deopts in old v8
  17939. if (type === CODES) {
  17940. base = extra = work; /* dummy value--not used */
  17941. end = 19;
  17942. } else if (type === LENS) {
  17943. base = lbase;
  17944. base_index -= 257;
  17945. extra = lext;
  17946. extra_index -= 257;
  17947. end = 256;
  17948. } else { /* DISTS */
  17949. base = dbase;
  17950. extra = dext;
  17951. end = -1;
  17952. }
  17953. /* initialize opts for loop */
  17954. huff = 0; /* starting code */
  17955. sym = 0; /* starting code symbol */
  17956. len = min; /* starting code length */
  17957. next = table_index; /* current table to fill in */
  17958. curr = root; /* current table index bits */
  17959. drop = 0; /* current bits to drop from code for index */
  17960. low = -1; /* trigger new sub-table when len > root */
  17961. used = 1 << root; /* use root table entries */
  17962. mask = used - 1; /* mask for comparing low */
  17963. /* check available table space */
  17964. if ((type === LENS && used > ENOUGH_LENS) ||
  17965. (type === DISTS && used > ENOUGH_DISTS)) {
  17966. return 1;
  17967. }
  17968. var i=0;
  17969. /* process all codes and make table entries */
  17970. for (;;) {
  17971. i++;
  17972. /* create table entry */
  17973. here_bits = len - drop;
  17974. if (work[sym] < end) {
  17975. here_op = 0;
  17976. here_val = work[sym];
  17977. }
  17978. else if (work[sym] > end) {
  17979. here_op = extra[extra_index + work[sym]];
  17980. here_val = base[base_index + work[sym]];
  17981. }
  17982. else {
  17983. here_op = 32 + 64; /* end of block */
  17984. here_val = 0;
  17985. }
  17986. /* replicate for those indices with low len bits equal to huff */
  17987. incr = 1 << (len - drop);
  17988. fill = 1 << curr;
  17989. min = fill; /* save offset to next table */
  17990. do {
  17991. fill -= incr;
  17992. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17993. } while (fill !== 0);
  17994. /* backwards increment the len-bit code huff */
  17995. incr = 1 << (len - 1);
  17996. while (huff & incr) {
  17997. incr >>= 1;
  17998. }
  17999. if (incr !== 0) {
  18000. huff &= incr - 1;
  18001. huff += incr;
  18002. } else {
  18003. huff = 0;
  18004. }
  18005. /* go to next symbol, update count, len */
  18006. sym++;
  18007. if (--count[len] === 0) {
  18008. if (len === max) { break; }
  18009. len = lens[lens_index + work[sym]];
  18010. }
  18011. /* create new sub-table if needed */
  18012. if (len > root && (huff & mask) !== low) {
  18013. /* if first time, transition to sub-tables */
  18014. if (drop === 0) {
  18015. drop = root;
  18016. }
  18017. /* increment past last table */
  18018. next += min; /* here min is 1 << curr */
  18019. /* determine length of next table */
  18020. curr = len - drop;
  18021. left = 1 << curr;
  18022. while (curr + drop < max) {
  18023. left -= count[curr + drop];
  18024. if (left <= 0) { break; }
  18025. curr++;
  18026. left <<= 1;
  18027. }
  18028. /* check for enough space */
  18029. used += 1 << curr;
  18030. if ((type === LENS && used > ENOUGH_LENS) ||
  18031. (type === DISTS && used > ENOUGH_DISTS)) {
  18032. return 1;
  18033. }
  18034. /* point entry in root table to sub-table */
  18035. low = huff & mask;
  18036. /*table.op[low] = curr;
  18037. table.bits[low] = root;
  18038. table.val[low] = next - opts.table_index;*/
  18039. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  18040. }
  18041. }
  18042. /* fill in remaining table entry if code is incomplete (guaranteed to have
  18043. at most one remaining entry, since if the code is incomplete, the
  18044. maximum code length that was allowed to get this far is one bit) */
  18045. if (huff !== 0) {
  18046. //table.op[next + huff] = 64; /* invalid code marker */
  18047. //table.bits[next + huff] = len - drop;
  18048. //table.val[next + huff] = 0;
  18049. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  18050. }
  18051. /* set return parameters */
  18052. //opts.table_index += used;
  18053. opts.bits = root;
  18054. return 0;
  18055. };
  18056. },{"../utils/common":52}],62:[function(require,module,exports){
  18057. 'use strict';
  18058. module.exports = {
  18059. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  18060. '1': 'stream end', /* Z_STREAM_END 1 */
  18061. '0': '', /* Z_OK 0 */
  18062. '-1': 'file error', /* Z_ERRNO (-1) */
  18063. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  18064. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  18065. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  18066. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  18067. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  18068. };
  18069. },{}],63:[function(require,module,exports){
  18070. 'use strict';
  18071. var utils = require('../utils/common');
  18072. /* Public constants ==========================================================*/
  18073. /* ===========================================================================*/
  18074. //var Z_FILTERED = 1;
  18075. //var Z_HUFFMAN_ONLY = 2;
  18076. //var Z_RLE = 3;
  18077. var Z_FIXED = 4;
  18078. //var Z_DEFAULT_STRATEGY = 0;
  18079. /* Possible values of the data_type field (though see inflate()) */
  18080. var Z_BINARY = 0;
  18081. var Z_TEXT = 1;
  18082. //var Z_ASCII = 1; // = Z_TEXT
  18083. var Z_UNKNOWN = 2;
  18084. /*============================================================================*/
  18085. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18086. // From zutil.h
  18087. var STORED_BLOCK = 0;
  18088. var STATIC_TREES = 1;
  18089. var DYN_TREES = 2;
  18090. /* The three kinds of block type */
  18091. var MIN_MATCH = 3;
  18092. var MAX_MATCH = 258;
  18093. /* The minimum and maximum match lengths */
  18094. // From deflate.h
  18095. /* ===========================================================================
  18096. * Internal compression state.
  18097. */
  18098. var LENGTH_CODES = 29;
  18099. /* number of length codes, not counting the special END_BLOCK code */
  18100. var LITERALS = 256;
  18101. /* number of literal bytes 0..255 */
  18102. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18103. /* number of Literal or Length codes, including the END_BLOCK code */
  18104. var D_CODES = 30;
  18105. /* number of distance codes */
  18106. var BL_CODES = 19;
  18107. /* number of codes used to transfer the bit lengths */
  18108. var HEAP_SIZE = 2*L_CODES + 1;
  18109. /* maximum heap size */
  18110. var MAX_BITS = 15;
  18111. /* All codes must not exceed MAX_BITS bits */
  18112. var Buf_size = 16;
  18113. /* size of bit buffer in bi_buf */
  18114. /* ===========================================================================
  18115. * Constants
  18116. */
  18117. var MAX_BL_BITS = 7;
  18118. /* Bit length codes must not exceed MAX_BL_BITS bits */
  18119. var END_BLOCK = 256;
  18120. /* end of block literal code */
  18121. var REP_3_6 = 16;
  18122. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  18123. var REPZ_3_10 = 17;
  18124. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  18125. var REPZ_11_138 = 18;
  18126. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  18127. var extra_lbits = /* extra bits for each length code */
  18128. [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];
  18129. var extra_dbits = /* extra bits for each distance code */
  18130. [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];
  18131. var extra_blbits = /* extra bits for each bit length code */
  18132. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  18133. var bl_order =
  18134. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  18135. /* The lengths of the bit length codes are sent in order of decreasing
  18136. * probability, to avoid transmitting the lengths for unused bit length codes.
  18137. */
  18138. /* ===========================================================================
  18139. * Local data. These are initialized only once.
  18140. */
  18141. // We pre-fill arrays with 0 to avoid uninitialized gaps
  18142. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  18143. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  18144. var static_ltree = new Array((L_CODES+2) * 2);
  18145. zero(static_ltree);
  18146. /* The static literal tree. Since the bit lengths are imposed, there is no
  18147. * need for the L_CODES extra codes used during heap construction. However
  18148. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  18149. * below).
  18150. */
  18151. var static_dtree = new Array(D_CODES * 2);
  18152. zero(static_dtree);
  18153. /* The static distance tree. (Actually a trivial tree since all codes use
  18154. * 5 bits.)
  18155. */
  18156. var _dist_code = new Array(DIST_CODE_LEN);
  18157. zero(_dist_code);
  18158. /* Distance codes. The first 256 values correspond to the distances
  18159. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  18160. * the 15 bit distances.
  18161. */
  18162. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  18163. zero(_length_code);
  18164. /* length code for each normalized match length (0 == MIN_MATCH) */
  18165. var base_length = new Array(LENGTH_CODES);
  18166. zero(base_length);
  18167. /* First normalized length for each code (0 = MIN_MATCH) */
  18168. var base_dist = new Array(D_CODES);
  18169. zero(base_dist);
  18170. /* First normalized distance for each code (0 = distance of 1) */
  18171. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  18172. this.static_tree = static_tree; /* static tree or NULL */
  18173. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  18174. this.extra_base = extra_base; /* base index for extra_bits */
  18175. this.elems = elems; /* max number of elements in the tree */
  18176. this.max_length = max_length; /* max bit length for the codes */
  18177. // show if `static_tree` has data or dummy - needed for monomorphic objects
  18178. this.has_stree = static_tree && static_tree.length;
  18179. };
  18180. var static_l_desc;
  18181. var static_d_desc;
  18182. var static_bl_desc;
  18183. var TreeDesc = function(dyn_tree, stat_desc) {
  18184. this.dyn_tree = dyn_tree; /* the dynamic tree */
  18185. this.max_code = 0; /* largest code with non zero frequency */
  18186. this.stat_desc = stat_desc; /* the corresponding static tree */
  18187. };
  18188. function d_code(dist) {
  18189. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  18190. }
  18191. /* ===========================================================================
  18192. * Output a short LSB first on the stream.
  18193. * IN assertion: there is enough room in pendingBuf.
  18194. */
  18195. function put_short (s, w) {
  18196. // put_byte(s, (uch)((w) & 0xff));
  18197. // put_byte(s, (uch)((ush)(w) >> 8));
  18198. s.pending_buf[s.pending++] = (w) & 0xff;
  18199. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  18200. }
  18201. /* ===========================================================================
  18202. * Send a value on a given number of bits.
  18203. * IN assertion: length <= 16 and value fits in length bits.
  18204. */
  18205. function send_bits(s, value, length) {
  18206. if (s.bi_valid > (Buf_size - length)) {
  18207. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18208. put_short(s, s.bi_buf);
  18209. s.bi_buf = value >> (Buf_size - s.bi_valid);
  18210. s.bi_valid += length - Buf_size;
  18211. } else {
  18212. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  18213. s.bi_valid += length;
  18214. }
  18215. }
  18216. function send_code(s, c, tree) {
  18217. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  18218. }
  18219. /* ===========================================================================
  18220. * Reverse the first len bits of a code, using straightforward code (a faster
  18221. * method would use a table)
  18222. * IN assertion: 1 <= len <= 15
  18223. */
  18224. function bi_reverse(code, len) {
  18225. var res = 0;
  18226. do {
  18227. res |= code & 1;
  18228. code >>>= 1;
  18229. res <<= 1;
  18230. } while (--len > 0);
  18231. return res >>> 1;
  18232. }
  18233. /* ===========================================================================
  18234. * Flush the bit buffer, keeping at most 7 bits in it.
  18235. */
  18236. function bi_flush(s) {
  18237. if (s.bi_valid === 16) {
  18238. put_short(s, s.bi_buf);
  18239. s.bi_buf = 0;
  18240. s.bi_valid = 0;
  18241. } else if (s.bi_valid >= 8) {
  18242. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  18243. s.bi_buf >>= 8;
  18244. s.bi_valid -= 8;
  18245. }
  18246. }
  18247. /* ===========================================================================
  18248. * Compute the optimal bit lengths for a tree and update the total bit length
  18249. * for the current block.
  18250. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  18251. * above are the tree nodes sorted by increasing frequency.
  18252. * OUT assertions: the field len is set to the optimal bit length, the
  18253. * array bl_count contains the frequencies for each bit length.
  18254. * The length opt_len is updated; static_len is also updated if stree is
  18255. * not null.
  18256. */
  18257. function gen_bitlen(s, desc)
  18258. // deflate_state *s;
  18259. // tree_desc *desc; /* the tree descriptor */
  18260. {
  18261. var tree = desc.dyn_tree;
  18262. var max_code = desc.max_code;
  18263. var stree = desc.stat_desc.static_tree;
  18264. var has_stree = desc.stat_desc.has_stree;
  18265. var extra = desc.stat_desc.extra_bits;
  18266. var base = desc.stat_desc.extra_base;
  18267. var max_length = desc.stat_desc.max_length;
  18268. var h; /* heap index */
  18269. var n, m; /* iterate over the tree elements */
  18270. var bits; /* bit length */
  18271. var xbits; /* extra bits */
  18272. var f; /* frequency */
  18273. var overflow = 0; /* number of elements with bit length too large */
  18274. for (bits = 0; bits <= MAX_BITS; bits++) {
  18275. s.bl_count[bits] = 0;
  18276. }
  18277. /* In a first pass, compute the optimal bit lengths (which may
  18278. * overflow in the case of the bit length tree).
  18279. */
  18280. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  18281. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  18282. n = s.heap[h];
  18283. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  18284. if (bits > max_length) {
  18285. bits = max_length;
  18286. overflow++;
  18287. }
  18288. tree[n*2 + 1]/*.Len*/ = bits;
  18289. /* We overwrite tree[n].Dad which is no longer needed */
  18290. if (n > max_code) { continue; } /* not a leaf node */
  18291. s.bl_count[bits]++;
  18292. xbits = 0;
  18293. if (n >= base) {
  18294. xbits = extra[n-base];
  18295. }
  18296. f = tree[n * 2]/*.Freq*/;
  18297. s.opt_len += f * (bits + xbits);
  18298. if (has_stree) {
  18299. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  18300. }
  18301. }
  18302. if (overflow === 0) { return; }
  18303. // Trace((stderr,"\nbit length overflow\n"));
  18304. /* This happens for example on obj2 and pic of the Calgary corpus */
  18305. /* Find the first bit length which could increase: */
  18306. do {
  18307. bits = max_length-1;
  18308. while (s.bl_count[bits] === 0) { bits--; }
  18309. s.bl_count[bits]--; /* move one leaf down the tree */
  18310. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  18311. s.bl_count[max_length]--;
  18312. /* The brother of the overflow item also moves one step up,
  18313. * but this does not affect bl_count[max_length]
  18314. */
  18315. overflow -= 2;
  18316. } while (overflow > 0);
  18317. /* Now recompute all bit lengths, scanning in increasing frequency.
  18318. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  18319. * lengths instead of fixing only the wrong ones. This idea is taken
  18320. * from 'ar' written by Haruhiko Okumura.)
  18321. */
  18322. for (bits = max_length; bits !== 0; bits--) {
  18323. n = s.bl_count[bits];
  18324. while (n !== 0) {
  18325. m = s.heap[--h];
  18326. if (m > max_code) { continue; }
  18327. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  18328. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  18329. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  18330. tree[m*2 + 1]/*.Len*/ = bits;
  18331. }
  18332. n--;
  18333. }
  18334. }
  18335. }
  18336. /* ===========================================================================
  18337. * Generate the codes for a given tree and bit counts (which need not be
  18338. * optimal).
  18339. * IN assertion: the array bl_count contains the bit length statistics for
  18340. * the given tree and the field len is set for all tree elements.
  18341. * OUT assertion: the field code is set for all tree elements of non
  18342. * zero code length.
  18343. */
  18344. function gen_codes(tree, max_code, bl_count)
  18345. // ct_data *tree; /* the tree to decorate */
  18346. // int max_code; /* largest code with non zero frequency */
  18347. // ushf *bl_count; /* number of codes at each bit length */
  18348. {
  18349. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  18350. var code = 0; /* running code value */
  18351. var bits; /* bit index */
  18352. var n; /* code index */
  18353. /* The distribution counts are first used to generate the code values
  18354. * without bit reversal.
  18355. */
  18356. for (bits = 1; bits <= MAX_BITS; bits++) {
  18357. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  18358. }
  18359. /* Check that the bit counts in bl_count are consistent. The last code
  18360. * must be all ones.
  18361. */
  18362. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  18363. // "inconsistent bit counts");
  18364. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  18365. for (n = 0; n <= max_code; n++) {
  18366. var len = tree[n*2 + 1]/*.Len*/;
  18367. if (len === 0) { continue; }
  18368. /* Now reverse the bits */
  18369. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  18370. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  18371. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  18372. }
  18373. }
  18374. /* ===========================================================================
  18375. * Initialize the various 'constant' tables.
  18376. */
  18377. function tr_static_init() {
  18378. var n; /* iterates over tree elements */
  18379. var bits; /* bit counter */
  18380. var length; /* length value */
  18381. var code; /* code value */
  18382. var dist; /* distance index */
  18383. var bl_count = new Array(MAX_BITS+1);
  18384. /* number of codes at each bit length for an optimal tree */
  18385. // do check in _tr_init()
  18386. //if (static_init_done) return;
  18387. /* For some embedded targets, global variables are not initialized: */
  18388. /*#ifdef NO_INIT_GLOBAL_POINTERS
  18389. static_l_desc.static_tree = static_ltree;
  18390. static_l_desc.extra_bits = extra_lbits;
  18391. static_d_desc.static_tree = static_dtree;
  18392. static_d_desc.extra_bits = extra_dbits;
  18393. static_bl_desc.extra_bits = extra_blbits;
  18394. #endif*/
  18395. /* Initialize the mapping length (0..255) -> length code (0..28) */
  18396. length = 0;
  18397. for (code = 0; code < LENGTH_CODES-1; code++) {
  18398. base_length[code] = length;
  18399. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  18400. _length_code[length++] = code;
  18401. }
  18402. }
  18403. //Assert (length == 256, "tr_static_init: length != 256");
  18404. /* Note that the length 255 (match length 258) can be represented
  18405. * in two different ways: code 284 + 5 bits or code 285, so we
  18406. * overwrite length_code[255] to use the best encoding:
  18407. */
  18408. _length_code[length-1] = code;
  18409. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  18410. dist = 0;
  18411. for (code = 0 ; code < 16; code++) {
  18412. base_dist[code] = dist;
  18413. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  18414. _dist_code[dist++] = code;
  18415. }
  18416. }
  18417. //Assert (dist == 256, "tr_static_init: dist != 256");
  18418. dist >>= 7; /* from now on, all distances are divided by 128 */
  18419. for (; code < D_CODES; code++) {
  18420. base_dist[code] = dist << 7;
  18421. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  18422. _dist_code[256 + dist++] = code;
  18423. }
  18424. }
  18425. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  18426. /* Construct the codes of the static literal tree */
  18427. for (bits = 0; bits <= MAX_BITS; bits++) {
  18428. bl_count[bits] = 0;
  18429. }
  18430. n = 0;
  18431. while (n <= 143) {
  18432. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18433. n++;
  18434. bl_count[8]++;
  18435. }
  18436. while (n <= 255) {
  18437. static_ltree[n*2 + 1]/*.Len*/ = 9;
  18438. n++;
  18439. bl_count[9]++;
  18440. }
  18441. while (n <= 279) {
  18442. static_ltree[n*2 + 1]/*.Len*/ = 7;
  18443. n++;
  18444. bl_count[7]++;
  18445. }
  18446. while (n <= 287) {
  18447. static_ltree[n*2 + 1]/*.Len*/ = 8;
  18448. n++;
  18449. bl_count[8]++;
  18450. }
  18451. /* Codes 286 and 287 do not exist, but we must include them in the
  18452. * tree construction to get a canonical Huffman tree (longest code
  18453. * all ones)
  18454. */
  18455. gen_codes(static_ltree, L_CODES+1, bl_count);
  18456. /* The static distance tree is trivial: */
  18457. for (n = 0; n < D_CODES; n++) {
  18458. static_dtree[n*2 + 1]/*.Len*/ = 5;
  18459. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  18460. }
  18461. // Now data ready and we can init static trees
  18462. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  18463. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  18464. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  18465. //static_init_done = true;
  18466. }
  18467. /* ===========================================================================
  18468. * Initialize a new block.
  18469. */
  18470. function init_block(s) {
  18471. var n; /* iterates over tree elements */
  18472. /* Initialize the trees. */
  18473. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  18474. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  18475. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  18476. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  18477. s.opt_len = s.static_len = 0;
  18478. s.last_lit = s.matches = 0;
  18479. }
  18480. /* ===========================================================================
  18481. * Flush the bit buffer and align the output on a byte boundary
  18482. */
  18483. function bi_windup(s)
  18484. {
  18485. if (s.bi_valid > 8) {
  18486. put_short(s, s.bi_buf);
  18487. } else if (s.bi_valid > 0) {
  18488. //put_byte(s, (Byte)s->bi_buf);
  18489. s.pending_buf[s.pending++] = s.bi_buf;
  18490. }
  18491. s.bi_buf = 0;
  18492. s.bi_valid = 0;
  18493. }
  18494. /* ===========================================================================
  18495. * Copy a stored block, storing first the length and its
  18496. * one's complement if requested.
  18497. */
  18498. function copy_block(s, buf, len, header)
  18499. //DeflateState *s;
  18500. //charf *buf; /* the input data */
  18501. //unsigned len; /* its length */
  18502. //int header; /* true if block header must be written */
  18503. {
  18504. bi_windup(s); /* align on byte boundary */
  18505. if (header) {
  18506. put_short(s, len);
  18507. put_short(s, ~len);
  18508. }
  18509. // while (len--) {
  18510. // put_byte(s, *buf++);
  18511. // }
  18512. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  18513. s.pending += len;
  18514. }
  18515. /* ===========================================================================
  18516. * Compares to subtrees, using the tree depth as tie breaker when
  18517. * the subtrees have equal frequency. This minimizes the worst case length.
  18518. */
  18519. function smaller(tree, n, m, depth) {
  18520. var _n2 = n*2;
  18521. var _m2 = m*2;
  18522. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  18523. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  18524. }
  18525. /* ===========================================================================
  18526. * Restore the heap property by moving down the tree starting at node k,
  18527. * exchanging a node with the smallest of its two sons if necessary, stopping
  18528. * when the heap property is re-established (each father smaller than its
  18529. * two sons).
  18530. */
  18531. function pqdownheap(s, tree, k)
  18532. // deflate_state *s;
  18533. // ct_data *tree; /* the tree to restore */
  18534. // int k; /* node to move down */
  18535. {
  18536. var v = s.heap[k];
  18537. var j = k << 1; /* left son of k */
  18538. while (j <= s.heap_len) {
  18539. /* Set j to the smallest of the two sons: */
  18540. if (j < s.heap_len &&
  18541. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  18542. j++;
  18543. }
  18544. /* Exit if v is smaller than both sons */
  18545. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  18546. /* Exchange v with the smallest son */
  18547. s.heap[k] = s.heap[j];
  18548. k = j;
  18549. /* And continue down the tree, setting j to the left son of k */
  18550. j <<= 1;
  18551. }
  18552. s.heap[k] = v;
  18553. }
  18554. // inlined manually
  18555. // var SMALLEST = 1;
  18556. /* ===========================================================================
  18557. * Send the block data compressed using the given Huffman trees
  18558. */
  18559. function compress_block(s, ltree, dtree)
  18560. // deflate_state *s;
  18561. // const ct_data *ltree; /* literal tree */
  18562. // const ct_data *dtree; /* distance tree */
  18563. {
  18564. var dist; /* distance of matched string */
  18565. var lc; /* match length or unmatched char (if dist == 0) */
  18566. var lx = 0; /* running index in l_buf */
  18567. var code; /* the code to send */
  18568. var extra; /* number of extra bits to send */
  18569. if (s.last_lit !== 0) {
  18570. do {
  18571. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  18572. lc = s.pending_buf[s.l_buf + lx];
  18573. lx++;
  18574. if (dist === 0) {
  18575. send_code(s, lc, ltree); /* send a literal byte */
  18576. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  18577. } else {
  18578. /* Here, lc is the match length - MIN_MATCH */
  18579. code = _length_code[lc];
  18580. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  18581. extra = extra_lbits[code];
  18582. if (extra !== 0) {
  18583. lc -= base_length[code];
  18584. send_bits(s, lc, extra); /* send the extra length bits */
  18585. }
  18586. dist--; /* dist is now the match distance - 1 */
  18587. code = d_code(dist);
  18588. //Assert (code < D_CODES, "bad d_code");
  18589. send_code(s, code, dtree); /* send the distance code */
  18590. extra = extra_dbits[code];
  18591. if (extra !== 0) {
  18592. dist -= base_dist[code];
  18593. send_bits(s, dist, extra); /* send the extra distance bits */
  18594. }
  18595. } /* literal or match pair ? */
  18596. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  18597. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  18598. // "pendingBuf overflow");
  18599. } while (lx < s.last_lit);
  18600. }
  18601. send_code(s, END_BLOCK, ltree);
  18602. }
  18603. /* ===========================================================================
  18604. * Construct one Huffman tree and assigns the code bit strings and lengths.
  18605. * Update the total bit length for the current block.
  18606. * IN assertion: the field freq is set for all tree elements.
  18607. * OUT assertions: the fields len and code are set to the optimal bit length
  18608. * and corresponding code. The length opt_len is updated; static_len is
  18609. * also updated if stree is not null. The field max_code is set.
  18610. */
  18611. function build_tree(s, desc)
  18612. // deflate_state *s;
  18613. // tree_desc *desc; /* the tree descriptor */
  18614. {
  18615. var tree = desc.dyn_tree;
  18616. var stree = desc.stat_desc.static_tree;
  18617. var has_stree = desc.stat_desc.has_stree;
  18618. var elems = desc.stat_desc.elems;
  18619. var n, m; /* iterate over heap elements */
  18620. var max_code = -1; /* largest code with non zero frequency */
  18621. var node; /* new node being created */
  18622. /* Construct the initial heap, with least frequent element in
  18623. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  18624. * heap[0] is not used.
  18625. */
  18626. s.heap_len = 0;
  18627. s.heap_max = HEAP_SIZE;
  18628. for (n = 0; n < elems; n++) {
  18629. if (tree[n * 2]/*.Freq*/ !== 0) {
  18630. s.heap[++s.heap_len] = max_code = n;
  18631. s.depth[n] = 0;
  18632. } else {
  18633. tree[n*2 + 1]/*.Len*/ = 0;
  18634. }
  18635. }
  18636. /* The pkzip format requires that at least one distance code exists,
  18637. * and that at least one bit should be sent even if there is only one
  18638. * possible code. So to avoid special checks later on we force at least
  18639. * two codes of non zero frequency.
  18640. */
  18641. while (s.heap_len < 2) {
  18642. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  18643. tree[node * 2]/*.Freq*/ = 1;
  18644. s.depth[node] = 0;
  18645. s.opt_len--;
  18646. if (has_stree) {
  18647. s.static_len -= stree[node*2 + 1]/*.Len*/;
  18648. }
  18649. /* node is 0 or 1 so it does not have extra bits */
  18650. }
  18651. desc.max_code = max_code;
  18652. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  18653. * establish sub-heaps of increasing lengths:
  18654. */
  18655. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  18656. /* Construct the Huffman tree by repeatedly combining the least two
  18657. * frequent nodes.
  18658. */
  18659. node = elems; /* next internal node of the tree */
  18660. do {
  18661. //pqremove(s, tree, n); /* n = node of least frequency */
  18662. /*** pqremove ***/
  18663. n = s.heap[1/*SMALLEST*/];
  18664. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  18665. pqdownheap(s, tree, 1/*SMALLEST*/);
  18666. /***/
  18667. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  18668. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  18669. s.heap[--s.heap_max] = m;
  18670. /* Create a new node father of n and m */
  18671. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  18672. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  18673. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  18674. /* and insert the new node in the heap */
  18675. s.heap[1/*SMALLEST*/] = node++;
  18676. pqdownheap(s, tree, 1/*SMALLEST*/);
  18677. } while (s.heap_len >= 2);
  18678. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  18679. /* At this point, the fields freq and dad are set. We can now
  18680. * generate the bit lengths.
  18681. */
  18682. gen_bitlen(s, desc);
  18683. /* The field len is now set, we can generate the bit codes */
  18684. gen_codes(tree, max_code, s.bl_count);
  18685. }
  18686. /* ===========================================================================
  18687. * Scan a literal or distance tree to determine the frequencies of the codes
  18688. * in the bit length tree.
  18689. */
  18690. function scan_tree(s, tree, max_code)
  18691. // deflate_state *s;
  18692. // ct_data *tree; /* the tree to be scanned */
  18693. // int max_code; /* and its largest code of non zero frequency */
  18694. {
  18695. var n; /* iterates over all tree elements */
  18696. var prevlen = -1; /* last emitted length */
  18697. var curlen; /* length of current code */
  18698. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18699. var count = 0; /* repeat count of the current code */
  18700. var max_count = 7; /* max repeat count */
  18701. var min_count = 4; /* min repeat count */
  18702. if (nextlen === 0) {
  18703. max_count = 138;
  18704. min_count = 3;
  18705. }
  18706. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  18707. for (n = 0; n <= max_code; n++) {
  18708. curlen = nextlen;
  18709. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18710. if (++count < max_count && curlen === nextlen) {
  18711. continue;
  18712. } else if (count < min_count) {
  18713. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18714. } else if (curlen !== 0) {
  18715. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18716. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  18717. } else if (count <= 10) {
  18718. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  18719. } else {
  18720. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  18721. }
  18722. count = 0;
  18723. prevlen = curlen;
  18724. if (nextlen === 0) {
  18725. max_count = 138;
  18726. min_count = 3;
  18727. } else if (curlen === nextlen) {
  18728. max_count = 6;
  18729. min_count = 3;
  18730. } else {
  18731. max_count = 7;
  18732. min_count = 4;
  18733. }
  18734. }
  18735. }
  18736. /* ===========================================================================
  18737. * Send a literal or distance tree in compressed form, using the codes in
  18738. * bl_tree.
  18739. */
  18740. function send_tree(s, tree, max_code)
  18741. // deflate_state *s;
  18742. // ct_data *tree; /* the tree to be scanned */
  18743. // int max_code; /* and its largest code of non zero frequency */
  18744. {
  18745. var n; /* iterates over all tree elements */
  18746. var prevlen = -1; /* last emitted length */
  18747. var curlen; /* length of current code */
  18748. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  18749. var count = 0; /* repeat count of the current code */
  18750. var max_count = 7; /* max repeat count */
  18751. var min_count = 4; /* min repeat count */
  18752. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18753. if (nextlen === 0) {
  18754. max_count = 138;
  18755. min_count = 3;
  18756. }
  18757. for (n = 0; n <= max_code; n++) {
  18758. curlen = nextlen;
  18759. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  18760. if (++count < max_count && curlen === nextlen) {
  18761. continue;
  18762. } else if (count < min_count) {
  18763. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18764. } else if (curlen !== 0) {
  18765. if (curlen !== prevlen) {
  18766. send_code(s, curlen, s.bl_tree);
  18767. count--;
  18768. }
  18769. //Assert(count >= 3 && count <= 6, " 3_6?");
  18770. send_code(s, REP_3_6, s.bl_tree);
  18771. send_bits(s, count-3, 2);
  18772. } else if (count <= 10) {
  18773. send_code(s, REPZ_3_10, s.bl_tree);
  18774. send_bits(s, count-3, 3);
  18775. } else {
  18776. send_code(s, REPZ_11_138, s.bl_tree);
  18777. send_bits(s, count-11, 7);
  18778. }
  18779. count = 0;
  18780. prevlen = curlen;
  18781. if (nextlen === 0) {
  18782. max_count = 138;
  18783. min_count = 3;
  18784. } else if (curlen === nextlen) {
  18785. max_count = 6;
  18786. min_count = 3;
  18787. } else {
  18788. max_count = 7;
  18789. min_count = 4;
  18790. }
  18791. }
  18792. }
  18793. /* ===========================================================================
  18794. * Construct the Huffman tree for the bit lengths and return the index in
  18795. * bl_order of the last bit length code to send.
  18796. */
  18797. function build_bl_tree(s) {
  18798. var max_blindex; /* index of last bit length code of non zero freq */
  18799. /* Determine the bit length frequencies for literal and distance trees */
  18800. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18801. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18802. /* Build the bit length tree: */
  18803. build_tree(s, s.bl_desc);
  18804. /* opt_len now includes the length of the tree representations, except
  18805. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18806. */
  18807. /* Determine the number of bit length codes to send. The pkzip format
  18808. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18809. * 3 but the actual value used is 4.)
  18810. */
  18811. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18812. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18813. break;
  18814. }
  18815. }
  18816. /* Update opt_len to include the bit length tree and counts */
  18817. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18818. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18819. // s->opt_len, s->static_len));
  18820. return max_blindex;
  18821. }
  18822. /* ===========================================================================
  18823. * Send the header for a block using dynamic Huffman trees: the counts, the
  18824. * lengths of the bit length codes, the literal tree and the distance tree.
  18825. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18826. */
  18827. function send_all_trees(s, lcodes, dcodes, blcodes)
  18828. // deflate_state *s;
  18829. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18830. {
  18831. var rank; /* index in bl_order */
  18832. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18833. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18834. // "too many codes");
  18835. //Tracev((stderr, "\nbl counts: "));
  18836. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  18837. send_bits(s, dcodes-1, 5);
  18838. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  18839. for (rank = 0; rank < blcodes; rank++) {
  18840. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18841. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  18842. }
  18843. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18844. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  18845. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18846. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  18847. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18848. }
  18849. /* ===========================================================================
  18850. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18851. * - TEXT if the two conditions below are satisfied:
  18852. * a) There are no non-portable control characters belonging to the
  18853. * "black list" (0..6, 14..25, 28..31).
  18854. * b) There is at least one printable character belonging to the
  18855. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18856. * - BINARY otherwise.
  18857. * - The following partially-portable control characters form a
  18858. * "gray list" that is ignored in this detection algorithm:
  18859. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18860. * IN assertion: the fields Freq of dyn_ltree are set.
  18861. */
  18862. function detect_data_type(s) {
  18863. /* black_mask is the bit mask of black-listed bytes
  18864. * set bits 0..6, 14..25, and 28..31
  18865. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18866. */
  18867. var black_mask = 0xf3ffc07f;
  18868. var n;
  18869. /* Check for non-textual ("black-listed") bytes. */
  18870. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18871. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  18872. return Z_BINARY;
  18873. }
  18874. }
  18875. /* Check for textual ("white-listed") bytes. */
  18876. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18877. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18878. return Z_TEXT;
  18879. }
  18880. for (n = 32; n < LITERALS; n++) {
  18881. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18882. return Z_TEXT;
  18883. }
  18884. }
  18885. /* There are no "black-listed" or "white-listed" bytes:
  18886. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18887. */
  18888. return Z_BINARY;
  18889. }
  18890. var static_init_done = false;
  18891. /* ===========================================================================
  18892. * Initialize the tree data structures for a new zlib stream.
  18893. */
  18894. function _tr_init(s)
  18895. {
  18896. if (!static_init_done) {
  18897. tr_static_init();
  18898. static_init_done = true;
  18899. }
  18900. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  18901. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  18902. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  18903. s.bi_buf = 0;
  18904. s.bi_valid = 0;
  18905. /* Initialize the first block of the first file: */
  18906. init_block(s);
  18907. }
  18908. /* ===========================================================================
  18909. * Send a stored block
  18910. */
  18911. function _tr_stored_block(s, buf, stored_len, last)
  18912. //DeflateState *s;
  18913. //charf *buf; /* input block */
  18914. //ulg stored_len; /* length of input block */
  18915. //int last; /* one if this is the last block for a file */
  18916. {
  18917. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  18918. copy_block(s, buf, stored_len, true); /* with header */
  18919. }
  18920. /* ===========================================================================
  18921. * Send one empty static block to give enough lookahead for inflate.
  18922. * This takes 10 bits, of which 7 may remain in the bit buffer.
  18923. */
  18924. function _tr_align(s) {
  18925. send_bits(s, STATIC_TREES<<1, 3);
  18926. send_code(s, END_BLOCK, static_ltree);
  18927. bi_flush(s);
  18928. }
  18929. /* ===========================================================================
  18930. * Determine the best encoding for the current block: dynamic trees, static
  18931. * trees or store, and output the encoded block to the zip file.
  18932. */
  18933. function _tr_flush_block(s, buf, stored_len, last)
  18934. //DeflateState *s;
  18935. //charf *buf; /* input block, or NULL if too old */
  18936. //ulg stored_len; /* length of input block */
  18937. //int last; /* one if this is the last block for a file */
  18938. {
  18939. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  18940. var max_blindex = 0; /* index of last bit length code of non zero freq */
  18941. /* Build the Huffman trees unless a stored block is forced */
  18942. if (s.level > 0) {
  18943. /* Check if the file is binary or text */
  18944. if (s.strm.data_type === Z_UNKNOWN) {
  18945. s.strm.data_type = detect_data_type(s);
  18946. }
  18947. /* Construct the literal and distance trees */
  18948. build_tree(s, s.l_desc);
  18949. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  18950. // s->static_len));
  18951. build_tree(s, s.d_desc);
  18952. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  18953. // s->static_len));
  18954. /* At this point, opt_len and static_len are the total bit lengths of
  18955. * the compressed block data, excluding the tree representations.
  18956. */
  18957. /* Build the bit length tree for the above two trees, and get the index
  18958. * in bl_order of the last bit length code to send.
  18959. */
  18960. max_blindex = build_bl_tree(s);
  18961. /* Determine the best encoding. Compute the block lengths in bytes. */
  18962. opt_lenb = (s.opt_len+3+7) >>> 3;
  18963. static_lenb = (s.static_len+3+7) >>> 3;
  18964. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  18965. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  18966. // s->last_lit));
  18967. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18968. } else {
  18969. // Assert(buf != (char*)0, "lost buf");
  18970. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18971. }
  18972. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  18973. /* 4: two words for the lengths */
  18974. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18975. * Otherwise we can't have processed more than WSIZE input bytes since
  18976. * the last block flush, because compression would have been
  18977. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18978. * transform a block into a stored block.
  18979. */
  18980. _tr_stored_block(s, buf, stored_len, last);
  18981. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18982. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  18983. compress_block(s, static_ltree, static_dtree);
  18984. } else {
  18985. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  18986. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  18987. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18988. }
  18989. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18990. /* The above check is made mod 2^32, for files larger than 512 MB
  18991. * and uLong implemented on 32 bits.
  18992. */
  18993. init_block(s);
  18994. if (last) {
  18995. bi_windup(s);
  18996. }
  18997. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18998. // s->compressed_len-7*last));
  18999. }
  19000. /* ===========================================================================
  19001. * Save the match info and tally the frequency counts. Return true if
  19002. * the current block must be flushed.
  19003. */
  19004. function _tr_tally(s, dist, lc)
  19005. // deflate_state *s;
  19006. // unsigned dist; /* distance of matched string */
  19007. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  19008. {
  19009. //var out_length, in_length, dcode;
  19010. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  19011. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  19012. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  19013. s.last_lit++;
  19014. if (dist === 0) {
  19015. /* lc is the unmatched char */
  19016. s.dyn_ltree[lc*2]/*.Freq*/++;
  19017. } else {
  19018. s.matches++;
  19019. /* Here, lc is the match length - MIN_MATCH */
  19020. dist--; /* dist = match distance - 1 */
  19021. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  19022. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  19023. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  19024. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  19025. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  19026. }
  19027. // (!) This block is disabled in zlib defailts,
  19028. // don't enable it for binary compatibility
  19029. //#ifdef TRUNCATE_BLOCK
  19030. // /* Try to guess if it is profitable to stop the current block here */
  19031. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  19032. // /* Compute an upper bound for the compressed length */
  19033. // out_length = s.last_lit*8;
  19034. // in_length = s.strstart - s.block_start;
  19035. //
  19036. // for (dcode = 0; dcode < D_CODES; dcode++) {
  19037. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  19038. // }
  19039. // out_length >>>= 3;
  19040. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  19041. // // s->last_lit, in_length, out_length,
  19042. // // 100L - out_length*100L/in_length));
  19043. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  19044. // return true;
  19045. // }
  19046. // }
  19047. //#endif
  19048. return (s.last_lit === s.lit_bufsize-1);
  19049. /* We avoid equality with lit_bufsize because of wraparound at 64K
  19050. * on 16 bit machines and because stored blocks are restricted to
  19051. * 64K-1 bytes.
  19052. */
  19053. }
  19054. exports._tr_init = _tr_init;
  19055. exports._tr_stored_block = _tr_stored_block;
  19056. exports._tr_flush_block = _tr_flush_block;
  19057. exports._tr_tally = _tr_tally;
  19058. exports._tr_align = _tr_align;
  19059. },{"../utils/common":52}],64:[function(require,module,exports){
  19060. 'use strict';
  19061. function ZStream() {
  19062. /* next input byte */
  19063. this.input = null; // JS specific, because we have no pointers
  19064. this.next_in = 0;
  19065. /* number of bytes available at input */
  19066. this.avail_in = 0;
  19067. /* total number of input bytes read so far */
  19068. this.total_in = 0;
  19069. /* next output byte should be put there */
  19070. this.output = null; // JS specific, because we have no pointers
  19071. this.next_out = 0;
  19072. /* remaining free space at output */
  19073. this.avail_out = 0;
  19074. /* total number of bytes output so far */
  19075. this.total_out = 0;
  19076. /* last error message, NULL if no error */
  19077. this.msg = ''/*Z_NULL*/;
  19078. /* not visible by applications */
  19079. this.state = null;
  19080. /* best guess about the data type: binary or text */
  19081. this.data_type = 2/*Z_UNKNOWN*/;
  19082. /* adler32 value of the uncompressed data */
  19083. this.adler = 0;
  19084. }
  19085. module.exports = ZStream;
  19086. },{}],65:[function(require,module,exports){
  19087. /* Copyright @ 2015 Atlassian Pty Ltd
  19088. *
  19089. * Licensed under the Apache License, Version 2.0 (the "License");
  19090. * you may not use this file except in compliance with the License.
  19091. * You may obtain a copy of the License at
  19092. *
  19093. * http://www.apache.org/licenses/LICENSE-2.0
  19094. *
  19095. * Unless required by applicable law or agreed to in writing, software
  19096. * distributed under the License is distributed on an "AS IS" BASIS,
  19097. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19098. * See the License for the specific language governing permissions and
  19099. * limitations under the License.
  19100. */
  19101. module.exports = function arrayEquals(array) {
  19102. // if the other array is a falsy value, return
  19103. if (!array)
  19104. return false;
  19105. // compare lengths - can save a lot of time
  19106. if (this.length != array.length)
  19107. return false;
  19108. for (var i = 0, l = this.length; i < l; i++) {
  19109. // Check if we have nested arrays
  19110. if (this[i] instanceof Array && array[i] instanceof Array) {
  19111. // recurse into the nested arrays
  19112. if (!arrayEquals.apply(this[i], [array[i]]))
  19113. return false;
  19114. } else if (this[i] != array[i]) {
  19115. // Warning - two different object instances will never be equal:
  19116. // {x:20} != {x:20}
  19117. return false;
  19118. }
  19119. }
  19120. return true;
  19121. };
  19122. },{}],66:[function(require,module,exports){
  19123. /* Copyright @ 2015 Atlassian Pty Ltd
  19124. *
  19125. * Licensed under the Apache License, Version 2.0 (the "License");
  19126. * you may not use this file except in compliance with the License.
  19127. * You may obtain a copy of the License at
  19128. *
  19129. * http://www.apache.org/licenses/LICENSE-2.0
  19130. *
  19131. * Unless required by applicable law or agreed to in writing, software
  19132. * distributed under the License is distributed on an "AS IS" BASIS,
  19133. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19134. * See the License for the specific language governing permissions and
  19135. * limitations under the License.
  19136. */
  19137. exports.Interop = require('./interop');
  19138. },{"./interop":67}],67:[function(require,module,exports){
  19139. /* Copyright @ 2015 Atlassian Pty Ltd
  19140. *
  19141. * Licensed under the Apache License, Version 2.0 (the "License");
  19142. * you may not use this file except in compliance with the License.
  19143. * You may obtain a copy of the License at
  19144. *
  19145. * http://www.apache.org/licenses/LICENSE-2.0
  19146. *
  19147. * Unless required by applicable law or agreed to in writing, software
  19148. * distributed under the License is distributed on an "AS IS" BASIS,
  19149. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19150. * See the License for the specific language governing permissions and
  19151. * limitations under the License.
  19152. */
  19153. /* global RTCSessionDescription */
  19154. /* jshint -W097 */
  19155. "use strict";
  19156. var transform = require('./transform');
  19157. var arrayEquals = require('./array-equals');
  19158. function Interop() {
  19159. /**
  19160. * This map holds the most recent Unified Plan offer/answer SDP that was
  19161. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  19162. * the SDP string as values.
  19163. *
  19164. * @type {{}}
  19165. */
  19166. this.cache = {};
  19167. }
  19168. module.exports = Interop;
  19169. /**
  19170. * Returns the index of the first m-line with the given media type and with a
  19171. * direction which allows sending, in the last Unified Plan description with
  19172. * type "answer" converted to Plan B. Returns {null} if there is no saved
  19173. * answer, or if none of its m-lines with the given type allow sending.
  19174. * @param type the media type ("audio" or "video").
  19175. * @returns {*}
  19176. */
  19177. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  19178. if (!this.cache.answer) {
  19179. return null;
  19180. }
  19181. var session = transform.parse(this.cache.answer);
  19182. if (session && session.media && Array.isArray(session.media)){
  19183. for (var i = 0; i < session.media.length; i++) {
  19184. if (session.media[i].type == type &&
  19185. (!session.media[i].direction /* default to sendrecv */ ||
  19186. session.media[i].direction === 'sendrecv' ||
  19187. session.media[i].direction === 'sendonly')){
  19188. return i;
  19189. }
  19190. }
  19191. }
  19192. return null;
  19193. };
  19194. /**
  19195. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  19196. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  19197. * application.
  19198. *
  19199. * @param desc
  19200. * @returns {*}
  19201. */
  19202. Interop.prototype.toPlanB = function(desc) {
  19203. var self = this;
  19204. //#region Preliminary input validation.
  19205. if (typeof desc !== 'object' || desc === null ||
  19206. typeof desc.sdp !== 'string') {
  19207. console.warn('An empty description was passed as an argument.');
  19208. return desc;
  19209. }
  19210. // Objectify the SDP for easier manipulation.
  19211. var session = transform.parse(desc.sdp);
  19212. // If the SDP contains no media, there's nothing to transform.
  19213. if (typeof session.media === 'undefined' ||
  19214. !Array.isArray(session.media) || session.media.length === 0) {
  19215. console.warn('The description has no media.');
  19216. return desc;
  19217. }
  19218. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  19219. // SDP has a video, an audio and a data "channel" at most.
  19220. if (session.media.length <= 3 && session.media.every(function(m) {
  19221. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19222. })) {
  19223. console.warn('This description does not look like Unified Plan.');
  19224. return desc;
  19225. }
  19226. //#endregion
  19227. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  19228. var sdp = desc.sdp;
  19229. var rewrite = false;
  19230. for (var i = 0; i < session.media.length; i++) {
  19231. var uLine = session.media[i];
  19232. uLine.rtp.forEach(function(rtp) {
  19233. if (rtp.codec === 'NULL')
  19234. {
  19235. rewrite = true;
  19236. var offer = transform.parse(self.cache['offer']);
  19237. rtp.codec = offer.media[i].rtp[0].codec;
  19238. }
  19239. });
  19240. };
  19241. if (rewrite) {
  19242. sdp = transform.write(session);
  19243. }
  19244. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  19245. // -> Unified Plan transformation.
  19246. this.cache[desc.type] = sdp;
  19247. //#region Convert from Unified Plan to Plan B.
  19248. // We rebuild the session.media array.
  19249. var media = session.media;
  19250. session.media = [];
  19251. // Associative array that maps channel types to channel objects for fast
  19252. // access to channel objects by their type, e.g. type2bl['audio']->channel
  19253. // obj.
  19254. var type2bl = {};
  19255. // Used to build the group:BUNDLE value after the channels construction
  19256. // loop.
  19257. var types = [];
  19258. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  19259. media.forEach(function(uLine) {
  19260. // rtcp-mux is required in the Plan B SDP.
  19261. if ((typeof uLine.rtcpMux !== 'string' ||
  19262. uLine.rtcpMux !== 'rtcp-mux') &&
  19263. uLine.direction !== 'inactive') {
  19264. throw new Error('Cannot convert to Plan B because m-lines ' +
  19265. 'without the rtcp-mux attribute were found.');
  19266. }
  19267. if (uLine.type === 'application') {
  19268. session.media.push(uLine);
  19269. types.push(uLine.mid);
  19270. return;
  19271. }
  19272. // If we don't have a channel for this uLine.type, then use this
  19273. // uLine as the channel basis.
  19274. if (typeof type2bl[uLine.type] === 'undefined') {
  19275. type2bl[uLine.type] = uLine;
  19276. }
  19277. // Add sources to the channel and handle a=msid.
  19278. if (typeof uLine.sources === 'object') {
  19279. Object.keys(uLine.sources).forEach(function(ssrc) {
  19280. if (typeof type2bl[uLine.type].sources !== 'object')
  19281. type2bl[uLine.type].sources = {};
  19282. // Assign the sources to the channel.
  19283. type2bl[uLine.type].sources[ssrc] =
  19284. uLine.sources[ssrc];
  19285. if (typeof uLine.msid !== 'undefined') {
  19286. // In Plan B the msid is an SSRC attribute. Also, we don't
  19287. // care about the obsolete label and mslabel attributes.
  19288. //
  19289. // Note that it is not guaranteed that the uLine will
  19290. // have an msid. recvonly channels in particular don't have
  19291. // one.
  19292. type2bl[uLine.type].sources[ssrc].msid =
  19293. uLine.msid;
  19294. }
  19295. // NOTE ssrcs in ssrc groups will share msids, as
  19296. // draft-uberti-rtcweb-plan-00 mandates.
  19297. });
  19298. }
  19299. // Add ssrc groups to the channel.
  19300. if (typeof uLine.ssrcGroups !== 'undefined' &&
  19301. Array.isArray(uLine.ssrcGroups)) {
  19302. // Create the ssrcGroups array, if it's not defined.
  19303. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  19304. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  19305. type2bl[uLine.type].ssrcGroups = [];
  19306. }
  19307. type2bl[uLine.type].ssrcGroups =
  19308. type2bl[uLine.type].ssrcGroups.concat(
  19309. uLine.ssrcGroups);
  19310. }
  19311. if (type2bl[uLine.type] === uLine) {
  19312. // Copy ICE related stuff from the principal media line.
  19313. uLine.candidates = media[0].candidates;
  19314. uLine.iceUfrag = media[0].iceUfrag;
  19315. uLine.icePwd = media[0].icePwd;
  19316. uLine.fingerprint = media[0].fingerprint;
  19317. // Plan B mids are in ['audio', 'video', 'data']
  19318. uLine.mid = uLine.type;
  19319. // Plan B doesn't support/need the bundle-only attribute.
  19320. delete uLine.bundleOnly;
  19321. // In Plan B the msid is an SSRC attribute.
  19322. delete uLine.msid;
  19323. // Used to build the group:BUNDLE value after this loop.
  19324. types.push(uLine.type);
  19325. // Add the channel to the new media array.
  19326. session.media.push(uLine);
  19327. }
  19328. });
  19329. // We regenerate the BUNDLE group with the new mids.
  19330. session.groups.some(function(group) {
  19331. if (group.type === 'BUNDLE') {
  19332. group.mids = types.join(' ');
  19333. return true;
  19334. }
  19335. });
  19336. // msid semantic
  19337. session.msidSemantic = {
  19338. semantic: 'WMS',
  19339. token: '*'
  19340. };
  19341. var resStr = transform.write(session);
  19342. return new RTCSessionDescription({
  19343. type: desc.type,
  19344. sdp: resStr
  19345. });
  19346. //#endregion
  19347. };
  19348. /**
  19349. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  19350. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  19351. * to FF.
  19352. *
  19353. * @param desc
  19354. * @returns {*}
  19355. */
  19356. Interop.prototype.toUnifiedPlan = function(desc) {
  19357. var self = this;
  19358. //#region Preliminary input validation.
  19359. if (typeof desc !== 'object' || desc === null ||
  19360. typeof desc.sdp !== 'string') {
  19361. console.warn('An empty description was passed as an argument.');
  19362. return desc;
  19363. }
  19364. var session = transform.parse(desc.sdp);
  19365. // If the SDP contains no media, there's nothing to transform.
  19366. if (typeof session.media === 'undefined' ||
  19367. !Array.isArray(session.media) || session.media.length === 0) {
  19368. console.warn('The description has no media.');
  19369. return desc;
  19370. }
  19371. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  19372. // a video, an audio and a data "channel" at most.
  19373. if (session.media.length > 3 || !session.media.every(function(m) {
  19374. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  19375. })) {
  19376. console.warn('This description does not look like Plan B.');
  19377. return desc;
  19378. }
  19379. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  19380. var mids = [];
  19381. session.media.forEach(function(m) {
  19382. mids.push(m.mid);
  19383. });
  19384. var hasBundle = false;
  19385. if (typeof session.groups !== 'undefined' &&
  19386. Array.isArray(session.groups)) {
  19387. hasBundle = session.groups.every(function(g) {
  19388. return g.type !== 'BUNDLE' ||
  19389. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  19390. });
  19391. }
  19392. if (!hasBundle) {
  19393. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  19394. " are not bundled were found.");
  19395. }
  19396. //#endregion
  19397. //#region Convert from Plan B to Unified Plan.
  19398. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  19399. // rebuild an equivalent Unified Plan offer/answer.
  19400. //
  19401. // For example, if this is a local answer (in Unified Plan style) that we
  19402. // convert to Plan B prior to handing it over to the application (the
  19403. // PeerConnection wrapper called us, for instance, after a successful
  19404. // createAnswer), we want to remember the m-line at which we've seen the
  19405. // (local) SSRC. That's because when the application wants to do call the
  19406. // SLD method, forcing us to do the inverse transformation (from Plan B to
  19407. // Unified Plan), we need to know to which m-line to assign the (local)
  19408. // SSRC. We also need to know all the other m-lines that the original
  19409. // answer had and include them in the transformed answer as well.
  19410. //
  19411. // Another example is if this is a remote offer that we convert to Plan B
  19412. // prior to giving it to the application, we want to remember the mid at
  19413. // which we've seen the (remote) SSRC.
  19414. //
  19415. // In the iteration that follows, we use the cached Unified Plan (if it
  19416. // exists) to assign mids to ssrcs.
  19417. var cached;
  19418. if (typeof this.cache[desc.type] !== 'undefined') {
  19419. cached = transform.parse(this.cache[desc.type]);
  19420. }
  19421. var recvonlySsrcs = {
  19422. audio: {},
  19423. video: {}
  19424. };
  19425. // A helper map that sends mids to m-line objects. We use it later to
  19426. // rebuild the Unified Plan style session.media array.
  19427. var mid2ul = {};
  19428. session.media.forEach(function(bLine) {
  19429. if ((typeof bLine.rtcpMux !== 'string' ||
  19430. bLine.rtcpMux !== 'rtcp-mux') &&
  19431. bLine.direction !== 'inactive') {
  19432. throw new Error("Cannot convert to Unified Plan because m-lines " +
  19433. "without the rtcp-mux attribute were found.");
  19434. }
  19435. if (bLine.type === 'application') {
  19436. mid2ul[bLine.mid] = bLine;
  19437. return;
  19438. }
  19439. // With rtcp-mux and bundle all the channels should have the same ICE
  19440. // stuff.
  19441. var sources = bLine.sources;
  19442. var ssrcGroups = bLine.ssrcGroups;
  19443. var candidates = bLine.candidates;
  19444. var iceUfrag = bLine.iceUfrag;
  19445. var icePwd = bLine.icePwd;
  19446. var fingerprint = bLine.fingerprint;
  19447. var port = bLine.port;
  19448. // We'll use the "bLine" object as a prototype for each new "mLine"
  19449. // that we create, but first we need to clean it up a bit.
  19450. delete bLine.sources;
  19451. delete bLine.ssrcGroups;
  19452. delete bLine.candidates;
  19453. delete bLine.iceUfrag;
  19454. delete bLine.icePwd;
  19455. delete bLine.fingerprint;
  19456. delete bLine.port;
  19457. delete bLine.mid;
  19458. // inverted ssrc group map
  19459. var ssrc2group = {};
  19460. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  19461. ssrcGroups.forEach(function (ssrcGroup) {
  19462. // TODO(gp) find out how to receive simulcast with FF. For the
  19463. // time being, hide it.
  19464. if (ssrcGroup.semantics === 'SIM') {
  19465. return;
  19466. }
  19467. // XXX This might brake if an SSRC is in more than one group
  19468. // for some reason.
  19469. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19470. Array.isArray(ssrcGroup.ssrcs)) {
  19471. ssrcGroup.ssrcs.forEach(function (ssrc) {
  19472. if (typeof ssrc2group[ssrc] === 'undefined') {
  19473. ssrc2group[ssrc] = [];
  19474. }
  19475. ssrc2group[ssrc].push(ssrcGroup);
  19476. });
  19477. }
  19478. });
  19479. }
  19480. // ssrc to m-line index.
  19481. var ssrc2ml = {};
  19482. if (typeof sources === 'object') {
  19483. // Explode the Plan B channel sources with one m-line per source.
  19484. Object.keys(sources).forEach(function(ssrc) {
  19485. // The (unified) m-line for this SSRC. We either create it from
  19486. // scratch or, if it's a grouped SSRC, we re-use a related
  19487. // mline. In other words, if the source is grouped with another
  19488. // source, put the two together in the same m-line.
  19489. var uLine;
  19490. // We assume here that we are the answerer in the O/A, so any
  19491. // offers which we translate come from the remote side, while
  19492. // answers are local. So the check below is to make that we
  19493. // handle receive-only SSRCs in a special way only if they come
  19494. // from the remote side.
  19495. if (desc.type==='offer') {
  19496. // We want to detect SSRCs which are used by a remote peer
  19497. // in an m-line with direction=recvonly (i.e. they are
  19498. // being used for RTCP only).
  19499. // This information would have gotten lost if the remote
  19500. // peer used Unified Plan and their local description was
  19501. // translated to Plan B. So we use the lack of an MSID
  19502. // attribute to deduce a "receive only" SSRC.
  19503. if (!sources[ssrc].msid) {
  19504. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  19505. // Receive-only SSRCs must not create new m-lines. We
  19506. // will assign them to an existing m-line later.
  19507. return;
  19508. }
  19509. }
  19510. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  19511. Array.isArray(ssrc2group[ssrc])) {
  19512. ssrc2group[ssrc].some(function (ssrcGroup) {
  19513. // ssrcGroup.ssrcs *is* an Array, no need to check
  19514. // again here.
  19515. return ssrcGroup.ssrcs.some(function (related) {
  19516. if (typeof ssrc2ml[related] === 'object') {
  19517. uLine = ssrc2ml[related];
  19518. return true;
  19519. }
  19520. });
  19521. });
  19522. }
  19523. if (typeof uLine === 'object') {
  19524. // the m-line already exists. Just add the source.
  19525. uLine.sources[ssrc] = sources[ssrc];
  19526. delete sources[ssrc].msid;
  19527. } else {
  19528. // Use the "bLine" as a prototype for the "uLine".
  19529. uLine = Object.create(bLine);
  19530. ssrc2ml[ssrc] = uLine;
  19531. if (typeof sources[ssrc].msid !== 'undefined') {
  19532. // Assign the msid of the source to the m-line. Note
  19533. // that it is not guaranteed that the source will have
  19534. // msid. In particular "recvonly" sources don't have an
  19535. // msid. Note that "recvonly" is a term only defined
  19536. // for m-lines.
  19537. uLine.msid = sources[ssrc].msid;
  19538. uLine.direction = 'sendrecv';
  19539. delete sources[ssrc].msid;
  19540. }
  19541. // We assign one SSRC per media line.
  19542. uLine.sources = {};
  19543. uLine.sources[ssrc] = sources[ssrc];
  19544. uLine.ssrcGroups = ssrc2group[ssrc];
  19545. // Use the cached Unified Plan SDP (if it exists) to assign
  19546. // SSRCs to mids.
  19547. if (typeof cached !== 'undefined' &&
  19548. typeof cached.media !== 'undefined' &&
  19549. Array.isArray(cached.media)) {
  19550. cached.media.forEach(function (m) {
  19551. if (typeof m.sources === 'object') {
  19552. Object.keys(m.sources).forEach(function (s) {
  19553. if (s === ssrc) {
  19554. uLine.mid = m.mid;
  19555. }
  19556. });
  19557. }
  19558. });
  19559. }
  19560. if (typeof uLine.mid === 'undefined') {
  19561. // If this is an SSRC that we see for the first time
  19562. // assign it a new mid. This is typically the case when
  19563. // this method is called to transform a remote
  19564. // description for the first time or when there is a
  19565. // new SSRC in the remote description because a new
  19566. // peer has joined the conference. Local SSRCs should
  19567. // have already been added to the map in the toPlanB
  19568. // method.
  19569. //
  19570. // Because FF generates answers in Unified Plan style,
  19571. // we MUST already have a cached answer with all the
  19572. // local SSRCs mapped to some m-line/mid.
  19573. if (desc.type === 'answer') {
  19574. throw new Error("An unmapped SSRC was found.");
  19575. }
  19576. uLine.mid = [bLine.type, '-', ssrc].join('');
  19577. }
  19578. // Include the candidates in the 1st media line.
  19579. uLine.candidates = candidates;
  19580. uLine.iceUfrag = iceUfrag;
  19581. uLine.icePwd = icePwd;
  19582. uLine.fingerprint = fingerprint;
  19583. uLine.port = port;
  19584. mid2ul[uLine.mid] = uLine;
  19585. }
  19586. });
  19587. }
  19588. });
  19589. // Rebuild the media array in the right order and add the missing mLines
  19590. // (missing from the Plan B SDP).
  19591. session.media = [];
  19592. mids = []; // reuse
  19593. if (desc.type === 'answer') {
  19594. // The media lines in the answer must match the media lines in the
  19595. // offer. The order is important too. Here we assume that Firefox is
  19596. // the answerer, so we merely have to use the reconstructed (unified)
  19597. // answer to update the cached (unified) answer accordingly.
  19598. //
  19599. // In the general case, one would have to use the cached (unified)
  19600. // offer to find the m-lines that are missing from the reconstructed
  19601. // answer, potentially grabbing them from the cached (unified) answer.
  19602. // One has to be careful with this approach because inactive m-lines do
  19603. // not always have an mid, making it tricky (impossible?) to find where
  19604. // exactly and which m-lines are missing from the reconstructed answer.
  19605. for (var i = 0; i < cached.media.length; i++) {
  19606. var uLine = cached.media[i];
  19607. if (typeof mid2ul[uLine.mid] === 'undefined') {
  19608. // The mid isn't in the reconstructed (unified) answer.
  19609. // This is either a (unified) m-line containing a remote
  19610. // track only, or a (unified) m-line containing a remote
  19611. // track and a local track that has been removed.
  19612. // In either case, it MUST exist in the cached
  19613. // (unified) answer.
  19614. //
  19615. // In case this is a removed local track, clean-up
  19616. // the (unified) m-line and make sure it's 'recvonly' or
  19617. // 'inactive'.
  19618. delete uLine.msid;
  19619. delete uLine.sources;
  19620. delete uLine.ssrcGroups;
  19621. if (!uLine.direction
  19622. || uLine.direction === 'sendrecv')
  19623. uLine.direction = 'recvonly';
  19624. else if (uLine.direction === 'sendonly')
  19625. uLine.direction = 'inactive';
  19626. } else {
  19627. // This is an (unified) m-line/channel that contains a local
  19628. // track (sendrecv or sendonly channel) or it's a unified
  19629. // recvonly m-line/channel. In either case, since we're
  19630. // going from PlanB -> Unified Plan this m-line MUST
  19631. // exist in the cached answer.
  19632. }
  19633. session.media.push(uLine);
  19634. if (typeof uLine.mid === 'string') {
  19635. // inactive lines don't/may not have an mid.
  19636. mids.push(uLine.mid);
  19637. }
  19638. }
  19639. } else {
  19640. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  19641. // under any circumstances. If we are no longer interested in sending a
  19642. // track, we just remove the msid and ssrc attributes and set it to
  19643. // either a=recvonly (as the reofferer, we must use recvonly if the
  19644. // other side was previously sending on the m-section, but we can also
  19645. // leave the possibility open if it wasn't previously in use), or
  19646. // a=inactive.
  19647. if (typeof cached !== 'undefined' &&
  19648. typeof cached.media !== 'undefined' &&
  19649. Array.isArray(cached.media)) {
  19650. cached.media.forEach(function(uLine) {
  19651. mids.push(uLine.mid);
  19652. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  19653. session.media.push(mid2ul[uLine.mid]);
  19654. } else {
  19655. delete uLine.msid;
  19656. delete uLine.sources;
  19657. delete uLine.ssrcGroups;
  19658. if (!uLine.direction
  19659. || uLine.direction === 'sendrecv')
  19660. uLine.direction = 'recvonly';
  19661. if (!uLine.direction
  19662. || uLine.direction === 'sendonly')
  19663. uLine.direction = 'inactive';
  19664. session.media.push(uLine);
  19665. }
  19666. });
  19667. }
  19668. // Add all the remaining (new) m-lines of the transformed SDP.
  19669. Object.keys(mid2ul).forEach(function(mid) {
  19670. if (mids.indexOf(mid) === -1) {
  19671. mids.push(mid);
  19672. if (mid2ul[mid].direction === 'recvonly') {
  19673. // This is a remote recvonly channel. Add its SSRC to the
  19674. // appropriate sendrecv or sendonly channel.
  19675. // TODO(gp) what if we don't have sendrecv/sendonly
  19676. // channel?
  19677. session.media.some(function (uLine) {
  19678. if ((uLine.direction === 'sendrecv' ||
  19679. uLine.direction === 'sendonly') &&
  19680. uLine.type === mid2ul[mid].type) {
  19681. // mid2ul[mid] shouldn't have any ssrc-groups
  19682. Object.keys(mid2ul[mid].sources).forEach(
  19683. function (ssrc) {
  19684. uLine.sources[ssrc] =
  19685. mid2ul[mid].sources[ssrc];
  19686. });
  19687. return true;
  19688. }
  19689. });
  19690. } else {
  19691. session.media.push(mid2ul[mid]);
  19692. }
  19693. }
  19694. });
  19695. }
  19696. // After we have constructed the Plan Unified m-lines we can figure out
  19697. // where (in which m-line) to place the 'recvonly SSRCs'.
  19698. // Note: we assume here that we are the answerer in the O/A, so any offers
  19699. // which we translate come from the remote side, while answers are local
  19700. // (and so our last local description is cached as an 'answer').
  19701. ["audio", "video"].forEach(function (type) {
  19702. if (!session || !session.media || !Array.isArray(session.media))
  19703. return;
  19704. var idx = null;
  19705. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  19706. idx = self.getFirstSendingIndexFromAnswer(type);
  19707. if (idx === null){
  19708. // If this is the first offer we receive, we don't have a
  19709. // cached answer. Assume that we will be sending media using
  19710. // the first m-line for each media type.
  19711. for (var i = 0; i < session.media.length; i++) {
  19712. if (session.media[i].type === type) {
  19713. idx = i;
  19714. break;
  19715. }
  19716. }
  19717. }
  19718. }
  19719. if (idx && session.media.length > idx) {
  19720. var mLine = session.media[idx];
  19721. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  19722. if (mLine.sources && mLine.sources[ssrc]) {
  19723. console.warn("Replacing an existing SSRC.");
  19724. }
  19725. if (!mLine.sources) {
  19726. mLine.sources = {};
  19727. }
  19728. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  19729. });
  19730. }
  19731. });
  19732. // We regenerate the BUNDLE group (since we regenerated the mids)
  19733. session.groups.some(function(group) {
  19734. if (group.type === 'BUNDLE') {
  19735. group.mids = mids.join(' ');
  19736. return true;
  19737. }
  19738. });
  19739. // msid semantic
  19740. session.msidSemantic = {
  19741. semantic: 'WMS',
  19742. token: '*'
  19743. };
  19744. var resStr = transform.write(session);
  19745. // Cache the transformed SDP (Unified Plan) for later re-use in this
  19746. // function.
  19747. this.cache[desc.type] = resStr;
  19748. return new RTCSessionDescription({
  19749. type: desc.type,
  19750. sdp: resStr
  19751. });
  19752. //#endregion
  19753. };
  19754. },{"./array-equals":65,"./transform":68}],68:[function(require,module,exports){
  19755. /* Copyright @ 2015 Atlassian Pty Ltd
  19756. *
  19757. * Licensed under the Apache License, Version 2.0 (the "License");
  19758. * you may not use this file except in compliance with the License.
  19759. * You may obtain a copy of the License at
  19760. *
  19761. * http://www.apache.org/licenses/LICENSE-2.0
  19762. *
  19763. * Unless required by applicable law or agreed to in writing, software
  19764. * distributed under the License is distributed on an "AS IS" BASIS,
  19765. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19766. * See the License for the specific language governing permissions and
  19767. * limitations under the License.
  19768. */
  19769. var transform = require('sdp-transform');
  19770. exports.write = function(session, opts) {
  19771. if (typeof session !== 'undefined' &&
  19772. typeof session.media !== 'undefined' &&
  19773. Array.isArray(session.media)) {
  19774. session.media.forEach(function (mLine) {
  19775. // expand sources to ssrcs
  19776. if (typeof mLine.sources !== 'undefined' &&
  19777. Object.keys(mLine.sources).length !== 0) {
  19778. mLine.ssrcs = [];
  19779. Object.keys(mLine.sources).forEach(function (ssrc) {
  19780. var source = mLine.sources[ssrc];
  19781. Object.keys(source).forEach(function (attribute) {
  19782. mLine.ssrcs.push({
  19783. id: ssrc,
  19784. attribute: attribute,
  19785. value: source[attribute]
  19786. });
  19787. });
  19788. });
  19789. delete mLine.sources;
  19790. }
  19791. // join ssrcs in ssrc groups
  19792. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19793. Array.isArray(mLine.ssrcGroups)) {
  19794. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19795. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19796. Array.isArray(ssrcGroup.ssrcs)) {
  19797. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19798. }
  19799. });
  19800. }
  19801. });
  19802. }
  19803. // join group mids
  19804. if (typeof session !== 'undefined' &&
  19805. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19806. session.groups.forEach(function (g) {
  19807. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19808. g.mids = g.mids.join(' ');
  19809. }
  19810. });
  19811. }
  19812. return transform.write(session, opts);
  19813. };
  19814. exports.parse = function(sdp) {
  19815. var session = transform.parse(sdp);
  19816. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19817. Array.isArray(session.media)) {
  19818. session.media.forEach(function (mLine) {
  19819. // group sources attributes by ssrc
  19820. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19821. mLine.sources = {};
  19822. mLine.ssrcs.forEach(function (ssrc) {
  19823. if (!mLine.sources[ssrc.id])
  19824. mLine.sources[ssrc.id] = {};
  19825. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19826. });
  19827. delete mLine.ssrcs;
  19828. }
  19829. // split ssrcs in ssrc groups
  19830. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19831. Array.isArray(mLine.ssrcGroups)) {
  19832. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19833. if (typeof ssrcGroup.ssrcs === 'string') {
  19834. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19835. }
  19836. });
  19837. }
  19838. });
  19839. }
  19840. // split group mids
  19841. if (typeof session !== 'undefined' &&
  19842. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19843. session.groups.forEach(function (g) {
  19844. if (typeof g.mids === 'string') {
  19845. g.mids = g.mids.split(' ');
  19846. }
  19847. });
  19848. }
  19849. return session;
  19850. };
  19851. },{"sdp-transform":70}],69:[function(require,module,exports){
  19852. var grammar = module.exports = {
  19853. v: [{
  19854. name: 'version',
  19855. reg: /^(\d*)$/
  19856. }],
  19857. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19858. // NB: sessionId will be a String in most cases because it is huge
  19859. name: 'origin',
  19860. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19861. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19862. format: "%s %s %d %s IP%d %s"
  19863. }],
  19864. // default parsing of these only (though some of these feel outdated)
  19865. s: [{ name: 'name' }],
  19866. i: [{ name: 'description' }],
  19867. u: [{ name: 'uri' }],
  19868. e: [{ name: 'email' }],
  19869. p: [{ name: 'phone' }],
  19870. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19871. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19872. //k: [{}], // outdated thing ignored
  19873. t: [{ //t=0 0
  19874. name: 'timing',
  19875. reg: /^(\d*) (\d*)/,
  19876. names: ['start', 'stop'],
  19877. format: "%d %d"
  19878. }],
  19879. c: [{ //c=IN IP4 10.47.197.26
  19880. name: 'connection',
  19881. reg: /^IN IP(\d) (\S*)/,
  19882. names: ['version', 'ip'],
  19883. format: "IN IP%d %s"
  19884. }],
  19885. b: [{ //b=AS:4000
  19886. push: 'bandwidth',
  19887. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19888. names: ['type', 'limit'],
  19889. format: "%s:%s"
  19890. }],
  19891. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19892. // NB: special - pushes to session
  19893. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19894. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19895. names: ['type', 'port', 'protocol', 'payloads'],
  19896. format: "%s %d %s %s"
  19897. }],
  19898. a: [
  19899. { //a=rtpmap:110 opus/48000/2
  19900. push: 'rtp',
  19901. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  19902. names: ['payload', 'codec', 'rate', 'encoding'],
  19903. format: function (o) {
  19904. return (o.encoding) ?
  19905. "rtpmap:%d %s/%s/%s":
  19906. o.rate ?
  19907. "rtpmap:%d %s/%s":
  19908. "rtpmap:%d %s";
  19909. }
  19910. },
  19911. {
  19912. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19913. //a=fmtp:111 minptime=10; useinbandfec=1
  19914. push: 'fmtp',
  19915. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19916. names: ['payload', 'config'],
  19917. format: "fmtp:%d %s"
  19918. },
  19919. { //a=control:streamid=0
  19920. name: 'control',
  19921. reg: /^control:(.*)/,
  19922. format: "control:%s"
  19923. },
  19924. { //a=rtcp:65179 IN IP4 193.84.77.194
  19925. name: 'rtcp',
  19926. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19927. names: ['port', 'netType', 'ipVer', 'address'],
  19928. format: function (o) {
  19929. return (o.address != null) ?
  19930. "rtcp:%d %s IP%d %s":
  19931. "rtcp:%d";
  19932. }
  19933. },
  19934. { //a=rtcp-fb:98 trr-int 100
  19935. push: 'rtcpFbTrrInt',
  19936. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19937. names: ['payload', 'value'],
  19938. format: "rtcp-fb:%d trr-int %d"
  19939. },
  19940. { //a=rtcp-fb:98 nack rpsi
  19941. push: 'rtcpFb',
  19942. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19943. names: ['payload', 'type', 'subtype'],
  19944. format: function (o) {
  19945. return (o.subtype != null) ?
  19946. "rtcp-fb:%s %s %s":
  19947. "rtcp-fb:%s %s";
  19948. }
  19949. },
  19950. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19951. //a=extmap:1/recvonly URI-gps-string
  19952. push: 'ext',
  19953. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19954. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19955. format: function (o) {
  19956. return (o.config != null) ?
  19957. "extmap:%s %s %s":
  19958. "extmap:%s %s";
  19959. }
  19960. },
  19961. {
  19962. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19963. push: 'crypto',
  19964. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19965. names: ['id', 'suite', 'config', 'sessionConfig'],
  19966. format: function (o) {
  19967. return (o.sessionConfig != null) ?
  19968. "crypto:%d %s %s %s":
  19969. "crypto:%d %s %s";
  19970. }
  19971. },
  19972. { //a=setup:actpass
  19973. name: 'setup',
  19974. reg: /^setup:(\w*)/,
  19975. format: "setup:%s"
  19976. },
  19977. { //a=mid:1
  19978. name: 'mid',
  19979. reg: /^mid:([^\s]*)/,
  19980. format: "mid:%s"
  19981. },
  19982. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19983. name: 'msid',
  19984. reg: /^msid:(.*)/,
  19985. format: "msid:%s"
  19986. },
  19987. { //a=ptime:20
  19988. name: 'ptime',
  19989. reg: /^ptime:(\d*)/,
  19990. format: "ptime:%d"
  19991. },
  19992. { //a=maxptime:60
  19993. name: 'maxptime',
  19994. reg: /^maxptime:(\d*)/,
  19995. format: "maxptime:%d"
  19996. },
  19997. { //a=sendrecv
  19998. name: 'direction',
  19999. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20000. },
  20001. { //a=ice-lite
  20002. name: 'icelite',
  20003. reg: /^(ice-lite)/
  20004. },
  20005. { //a=ice-ufrag:F7gI
  20006. name: 'iceUfrag',
  20007. reg: /^ice-ufrag:(\S*)/,
  20008. format: "ice-ufrag:%s"
  20009. },
  20010. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20011. name: 'icePwd',
  20012. reg: /^ice-pwd:(\S*)/,
  20013. format: "ice-pwd:%s"
  20014. },
  20015. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20016. name: 'fingerprint',
  20017. reg: /^fingerprint:(\S*) (\S*)/,
  20018. names: ['type', 'hash'],
  20019. format: "fingerprint:%s %s"
  20020. },
  20021. {
  20022. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20023. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20024. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20025. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  20026. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  20027. push:'candidates',
  20028. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  20029. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  20030. format: function (o) {
  20031. var str = "candidate:%s %d %s %d %s %d typ %s";
  20032. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20033. // NB: candidate has three optional chunks, so %void middles one if it's missing
  20034. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  20035. if (o.generation != null) {
  20036. str += " generation %d";
  20037. }
  20038. return str;
  20039. }
  20040. },
  20041. { //a=end-of-candidates (keep after the candidates line for readability)
  20042. name: 'endOfCandidates',
  20043. reg: /^(end-of-candidates)/
  20044. },
  20045. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20046. name: 'remoteCandidates',
  20047. reg: /^remote-candidates:(.*)/,
  20048. format: "remote-candidates:%s"
  20049. },
  20050. { //a=ice-options:google-ice
  20051. name: 'iceOptions',
  20052. reg: /^ice-options:(\S*)/,
  20053. format: "ice-options:%s"
  20054. },
  20055. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20056. push: "ssrcs",
  20057. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20058. names: ['id', 'attribute', 'value'],
  20059. format: "ssrc:%d %s:%s"
  20060. },
  20061. { //a=ssrc-group:FEC 1 2
  20062. push: "ssrcGroups",
  20063. reg: /^ssrc-group:(\w*) (.*)/,
  20064. names: ['semantics', 'ssrcs'],
  20065. format: "ssrc-group:%s %s"
  20066. },
  20067. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20068. name: "msidSemantic",
  20069. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20070. names: ['semantic', 'token'],
  20071. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20072. },
  20073. { //a=group:BUNDLE audio video
  20074. push: 'groups',
  20075. reg: /^group:(\w*) (.*)/,
  20076. names: ['type', 'mids'],
  20077. format: "group:%s %s"
  20078. },
  20079. { //a=rtcp-mux
  20080. name: 'rtcpMux',
  20081. reg: /^(rtcp-mux)/
  20082. },
  20083. { //a=rtcp-rsize
  20084. name: 'rtcpRsize',
  20085. reg: /^(rtcp-rsize)/
  20086. },
  20087. { // any a= that we don't understand is kepts verbatim on media.invalid
  20088. push: 'invalid',
  20089. names: ["value"]
  20090. }
  20091. ]
  20092. };
  20093. // set sensible defaults to avoid polluting the grammar with boring details
  20094. Object.keys(grammar).forEach(function (key) {
  20095. var objs = grammar[key];
  20096. objs.forEach(function (obj) {
  20097. if (!obj.reg) {
  20098. obj.reg = /(.*)/;
  20099. }
  20100. if (!obj.format) {
  20101. obj.format = "%s";
  20102. }
  20103. });
  20104. });
  20105. },{}],70:[function(require,module,exports){
  20106. var parser = require('./parser');
  20107. var writer = require('./writer');
  20108. exports.write = writer;
  20109. exports.parse = parser.parse;
  20110. exports.parseFmtpConfig = parser.parseFmtpConfig;
  20111. exports.parsePayloads = parser.parsePayloads;
  20112. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  20113. },{"./parser":71,"./writer":72}],71:[function(require,module,exports){
  20114. var toIntIfInt = function (v) {
  20115. return String(Number(v)) === v ? Number(v) : v;
  20116. };
  20117. var attachProperties = function (match, location, names, rawName) {
  20118. if (rawName && !names) {
  20119. location[rawName] = toIntIfInt(match[1]);
  20120. }
  20121. else {
  20122. for (var i = 0; i < names.length; i += 1) {
  20123. if (match[i+1] != null) {
  20124. location[names[i]] = toIntIfInt(match[i+1]);
  20125. }
  20126. }
  20127. }
  20128. };
  20129. var parseReg = function (obj, location, content) {
  20130. var needsBlank = obj.name && obj.names;
  20131. if (obj.push && !location[obj.push]) {
  20132. location[obj.push] = [];
  20133. }
  20134. else if (needsBlank && !location[obj.name]) {
  20135. location[obj.name] = {};
  20136. }
  20137. var keyLocation = obj.push ?
  20138. {} : // blank object that will be pushed
  20139. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20140. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20141. if (obj.push) {
  20142. location[obj.push].push(keyLocation);
  20143. }
  20144. };
  20145. var grammar = require('./grammar');
  20146. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20147. exports.parse = function (sdp) {
  20148. var session = {}
  20149. , media = []
  20150. , location = session; // points at where properties go under (one of the above)
  20151. // parse lines we understand
  20152. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20153. var type = l[0];
  20154. var content = l.slice(2);
  20155. if (type === 'm') {
  20156. media.push({rtp: [], fmtp: []});
  20157. location = media[media.length-1]; // point at latest media line
  20158. }
  20159. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20160. var obj = grammar[type][j];
  20161. if (obj.reg.test(content)) {
  20162. return parseReg(obj, location, content);
  20163. }
  20164. }
  20165. });
  20166. session.media = media; // link it up
  20167. return session;
  20168. };
  20169. var fmtpReducer = function (acc, expr) {
  20170. var s = expr.split('=');
  20171. if (s.length === 2) {
  20172. acc[s[0]] = toIntIfInt(s[1]);
  20173. }
  20174. return acc;
  20175. };
  20176. exports.parseFmtpConfig = function (str) {
  20177. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  20178. };
  20179. exports.parsePayloads = function (str) {
  20180. return str.split(' ').map(Number);
  20181. };
  20182. exports.parseRemoteCandidates = function (str) {
  20183. var candidates = [];
  20184. var parts = str.split(' ').map(toIntIfInt);
  20185. for (var i = 0; i < parts.length; i += 3) {
  20186. candidates.push({
  20187. component: parts[i],
  20188. ip: parts[i + 1],
  20189. port: parts[i + 2]
  20190. });
  20191. }
  20192. return candidates;
  20193. };
  20194. },{"./grammar":69}],72:[function(require,module,exports){
  20195. var grammar = require('./grammar');
  20196. // customized util.format - discards excess arguments and can void middle ones
  20197. var formatRegExp = /%[sdv%]/g;
  20198. var format = function (formatStr) {
  20199. var i = 1;
  20200. var args = arguments;
  20201. var len = args.length;
  20202. return formatStr.replace(formatRegExp, function (x) {
  20203. if (i >= len) {
  20204. return x; // missing argument
  20205. }
  20206. var arg = args[i];
  20207. i += 1;
  20208. switch (x) {
  20209. case '%%':
  20210. return '%';
  20211. case '%s':
  20212. return String(arg);
  20213. case '%d':
  20214. return Number(arg);
  20215. case '%v':
  20216. return '';
  20217. }
  20218. });
  20219. // NB: we discard excess arguments - they are typically undefined from makeLine
  20220. };
  20221. var makeLine = function (type, obj, location) {
  20222. var str = obj.format instanceof Function ?
  20223. (obj.format(obj.push ? location : location[obj.name])) :
  20224. obj.format;
  20225. var args = [type + '=' + str];
  20226. if (obj.names) {
  20227. for (var i = 0; i < obj.names.length; i += 1) {
  20228. var n = obj.names[i];
  20229. if (obj.name) {
  20230. args.push(location[obj.name][n]);
  20231. }
  20232. else { // for mLine and push attributes
  20233. args.push(location[obj.names[i]]);
  20234. }
  20235. }
  20236. }
  20237. else {
  20238. args.push(location[obj.name]);
  20239. }
  20240. return format.apply(null, args);
  20241. };
  20242. // RFC specified order
  20243. // TODO: extend this with all the rest
  20244. var defaultOuterOrder = [
  20245. 'v', 'o', 's', 'i',
  20246. 'u', 'e', 'p', 'c',
  20247. 'b', 't', 'r', 'z', 'a'
  20248. ];
  20249. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  20250. module.exports = function (session, opts) {
  20251. opts = opts || {};
  20252. // ensure certain properties exist
  20253. if (session.version == null) {
  20254. session.version = 0; // "v=0" must be there (only defined version atm)
  20255. }
  20256. if (session.name == null) {
  20257. session.name = " "; // "s= " must be there if no meaningful name set
  20258. }
  20259. session.media.forEach(function (mLine) {
  20260. if (mLine.payloads == null) {
  20261. mLine.payloads = "";
  20262. }
  20263. });
  20264. var outerOrder = opts.outerOrder || defaultOuterOrder;
  20265. var innerOrder = opts.innerOrder || defaultInnerOrder;
  20266. var sdp = [];
  20267. // loop through outerOrder for matching properties on session
  20268. outerOrder.forEach(function (type) {
  20269. grammar[type].forEach(function (obj) {
  20270. if (obj.name in session && session[obj.name] != null) {
  20271. sdp.push(makeLine(type, obj, session));
  20272. }
  20273. else if (obj.push in session && session[obj.push] != null) {
  20274. session[obj.push].forEach(function (el) {
  20275. sdp.push(makeLine(type, obj, el));
  20276. });
  20277. }
  20278. });
  20279. });
  20280. // then for each media line, follow the innerOrder
  20281. session.media.forEach(function (mLine) {
  20282. sdp.push(makeLine('m', grammar.m[0], mLine));
  20283. innerOrder.forEach(function (type) {
  20284. grammar[type].forEach(function (obj) {
  20285. if (obj.name in mLine && mLine[obj.name] != null) {
  20286. sdp.push(makeLine(type, obj, mLine));
  20287. }
  20288. else if (obj.push in mLine && mLine[obj.push] != null) {
  20289. mLine[obj.push].forEach(function (el) {
  20290. sdp.push(makeLine(type, obj, el));
  20291. });
  20292. }
  20293. });
  20294. });
  20295. });
  20296. return sdp.join('\r\n') + '\r\n';
  20297. };
  20298. },{"./grammar":69}],73:[function(require,module,exports){
  20299. /* Copyright @ 2015 Atlassian Pty Ltd
  20300. *
  20301. * Licensed under the Apache License, Version 2.0 (the "License");
  20302. * you may not use this file except in compliance with the License.
  20303. * You may obtain a copy of the License at
  20304. *
  20305. * http://www.apache.org/licenses/LICENSE-2.0
  20306. *
  20307. * Unless required by applicable law or agreed to in writing, software
  20308. * distributed under the License is distributed on an "AS IS" BASIS,
  20309. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20310. * See the License for the specific language governing permissions and
  20311. * limitations under the License.
  20312. */
  20313. var transform = require('sdp-transform');
  20314. var transformUtils = require('./transform-utils');
  20315. var parseSsrcs = transformUtils.parseSsrcs;
  20316. var writeSsrcs = transformUtils.writeSsrcs;
  20317. //region Constants
  20318. var DEFAULT_NUM_OF_LAYERS = 3;
  20319. //endregion
  20320. //region Ctor
  20321. function Simulcast(options) {
  20322. this.options = options ? options : {};
  20323. if (!this.options.numOfLayers) {
  20324. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  20325. }
  20326. this.layers = [];
  20327. }
  20328. //endregion
  20329. //region Stateless private utility functions
  20330. /**
  20331. * Returns a random integer between min (included) and max (excluded)
  20332. * Using Math.round() gives a non-uniform distribution!
  20333. * @returns {number}
  20334. */
  20335. function generateSSRC() {
  20336. var min = 0, max = 0xffffffff;
  20337. return Math.floor(Math.random() * (max - min)) + min;
  20338. };
  20339. function processVideo(session, action) {
  20340. if (session == null || !Array.isArray(session.media)) {
  20341. return;
  20342. }
  20343. session.media.forEach(function (mLine) {
  20344. if (mLine.type === 'video') {
  20345. action(mLine);
  20346. }
  20347. });
  20348. }
  20349. function validateDescription(desc)
  20350. {
  20351. return desc && desc != null
  20352. && desc.type && desc.type != ''
  20353. && desc.sdp && desc.sdp != '';
  20354. }
  20355. function explodeRemoteSimulcast(mLine) {
  20356. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  20357. return;
  20358. }
  20359. var sources = parseSsrcs(mLine);
  20360. var order = [];
  20361. // Find the SIM group and explode its sources.
  20362. var j = mLine.ssrcGroups.length;
  20363. while (j--) {
  20364. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  20365. continue;
  20366. }
  20367. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  20368. for (var i = 0; i < simulcastSsrcs.length; i++) {
  20369. var ssrc = simulcastSsrcs[i];
  20370. order.push(ssrc);
  20371. var parts = sources[ssrc].msid.split(' ');
  20372. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  20373. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  20374. // Remove all the groups that this SSRC participates in.
  20375. mLine.ssrcGroups.forEach(function (relatedGroup) {
  20376. if (relatedGroup.semantics === 'SIM') {
  20377. return;
  20378. }
  20379. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  20380. if (relatedSsrcs.indexOf(ssrc) === -1) {
  20381. return;
  20382. }
  20383. // Nuke all the related SSRCs.
  20384. relatedSsrcs.forEach(function (relatedSSRC) {
  20385. sources[relatedSSRC].msid = sources[ssrc].msid;
  20386. sources[relatedSSRC].cname = sources[ssrc].cname;
  20387. if (relatedSSRC !== ssrc) {
  20388. order.push(relatedSSRC);
  20389. }
  20390. });
  20391. // Schedule the related group for nuking.
  20392. })
  20393. }
  20394. mLine.ssrcs = writeSsrcs(sources, order);
  20395. mLine.ssrcGroups.splice(j, 1);
  20396. };
  20397. }
  20398. function implodeRemoteSimulcast(mLine) {
  20399. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  20400. console.info('Halt: There are no SSRC groups in the remote ' +
  20401. 'description.');
  20402. return;
  20403. }
  20404. var sources = parseSsrcs(mLine);
  20405. // Find the SIM group and nuke it.
  20406. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  20407. if (simulcastGroup.semantics !== 'SIM') {
  20408. return;
  20409. }
  20410. console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
  20411. // Schedule the SIM group for nuking.
  20412. simulcastGroup.nuke = true;
  20413. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  20414. // Nuke all the higher layer SSRCs.
  20415. for (var i = 1; i < simulcastSsrcs.length; i++) {
  20416. var ssrc = simulcastSsrcs[i];
  20417. delete sources[ssrc];
  20418. // Remove all the groups that this SSRC participates in.
  20419. mLine.ssrcGroups.forEach(function (relatedGroup) {
  20420. if (relatedGroup.semantics === 'SIM') {
  20421. return;
  20422. }
  20423. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  20424. if (relatedSsrcs.indexOf(ssrc) === -1) {
  20425. return;
  20426. }
  20427. // Nuke all the related SSRCs.
  20428. relatedSsrcs.forEach(function (relatedSSRC) {
  20429. delete sources[relatedSSRC];
  20430. });
  20431. // Schedule the related group for nuking.
  20432. relatedGroup.nuke = true;
  20433. })
  20434. }
  20435. return;
  20436. });
  20437. mLine.ssrcs = writeSsrcs(sources);
  20438. // Nuke all the scheduled groups.
  20439. var i = mLine.ssrcGroups.length;
  20440. while (i--) {
  20441. if (mLine.ssrcGroups[i].nuke) {
  20442. mLine.ssrcGroups.splice(i, 1);
  20443. }
  20444. }
  20445. }
  20446. function removeGoogConference(mLine) {
  20447. if (!mLine || !Array.isArray(mLine.invalid)) {
  20448. return;
  20449. }
  20450. var i = mLine.invalid.length;
  20451. while (i--) {
  20452. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  20453. mLine.invalid.splice(i, 1);
  20454. }
  20455. }
  20456. }
  20457. function assertGoogConference(mLine) {
  20458. if (!mLine) {
  20459. return;
  20460. }
  20461. if (!Array.isArray(mLine.invalid)) {
  20462. mLine.invalid = [];
  20463. }
  20464. if (!mLine.invalid.some(
  20465. function (i) { return i.value === 'x-google-flag:conference' })) {
  20466. mLine.invalid.push({'value': 'x-google-flag:conference'});
  20467. }
  20468. }
  20469. //endregion
  20470. //region "Private" functions
  20471. /**
  20472. *
  20473. * @param mLine
  20474. * @private
  20475. */
  20476. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  20477. if (!mLine || mLine.type !== 'video') {
  20478. return;
  20479. }
  20480. var sources = parseSsrcs(mLine);
  20481. if (Object.keys(sources).length === 0) {
  20482. // no sources, disable simulcast.
  20483. if (this.layers.length !== 0) {
  20484. this.layers = [];
  20485. }
  20486. return;
  20487. }
  20488. // find the base layer (we'll reuse its msid and cname).
  20489. var baseLayerSSRC = Object.keys(sources)[0];
  20490. var baseLayer = sources[baseLayerSSRC];
  20491. // todo(gp) handle screen sharing.
  20492. // check if base CNAME has changed and reinitialise layers.
  20493. if (this.layers.length > 0
  20494. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  20495. this.layers = [];
  20496. }
  20497. // (re)initialise layers
  20498. if (this.layers.length < 1) {
  20499. // first push the base layer.
  20500. this.layers.push({
  20501. ssrc: baseLayerSSRC,
  20502. msid: baseLayer.msid,
  20503. cname: baseLayer.cname
  20504. });
  20505. var rtx = false; // RFC 4588
  20506. if (Array.isArray(mLine.rtp)) {
  20507. rtx = mLine.rtp.some(
  20508. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  20509. }
  20510. if (rtx) {
  20511. this.layers[0].rtx = generateSSRC();
  20512. }
  20513. // now push additional layers.
  20514. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  20515. var layer = { ssrc: generateSSRC() };
  20516. if (rtx) {
  20517. layer.rtx = generateSSRC();
  20518. }
  20519. this.layers.push(layer);
  20520. }
  20521. }
  20522. };
  20523. /**
  20524. *
  20525. * @param mLine
  20526. * @private
  20527. */
  20528. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  20529. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  20530. var sources = {};
  20531. var msid = this.layers[0].msid;
  20532. var cname = this.layers[0].cname;
  20533. var simulcastSsrcs = [];
  20534. var ssrcGroups = [];
  20535. for (var i = 0; i < this.layers.length; i++) {
  20536. var layer = this.layers[i];
  20537. sources[layer.ssrc] = { msid: msid, cname: cname };
  20538. simulcastSsrcs.push(layer.ssrc);
  20539. if (layer.rtx) {
  20540. sources[layer.rtx] = {
  20541. msid: msid,
  20542. cname: cname
  20543. }
  20544. ssrcGroups.push({
  20545. semantics: 'FID',
  20546. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  20547. });
  20548. }
  20549. }
  20550. ssrcGroups.push({
  20551. semantics: 'SIM',
  20552. ssrcs: simulcastSsrcs.join(' ')
  20553. });
  20554. mLine.ssrcGroups = ssrcGroups;
  20555. mLine.ssrcs = writeSsrcs(sources);
  20556. }
  20557. }
  20558. //endregion
  20559. //region "Public" functions
  20560. Simulcast.prototype.isSupported = function () {
  20561. return window.chrome;
  20562. // TODO this needs improvements. For example I doubt that Chrome in Android
  20563. // has simulcast support. Also, only recent versions of Chromium have native
  20564. // simulcast support.
  20565. }
  20566. /**
  20567. *
  20568. * @param desc
  20569. * @returns {RTCSessionDescription}
  20570. */
  20571. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  20572. if (!validateDescription(desc)) {
  20573. return desc;
  20574. }
  20575. var session = transform.parse(desc.sdp);
  20576. var self = this;
  20577. processVideo(session, function (mLine) {
  20578. // Handle simulcast reception.
  20579. if (self.options.explodeRemoteSimulcast) {
  20580. explodeRemoteSimulcast(mLine);
  20581. } else {
  20582. implodeRemoteSimulcast(mLine);
  20583. }
  20584. // If native simulcast is enabled, we must append the x-goog-conference
  20585. // attribute to the SDP.
  20586. if (self.layers.length < 1) {
  20587. removeGoogConference(mLine);
  20588. } else {
  20589. assertGoogConference(mLine);
  20590. }
  20591. });
  20592. return new RTCSessionDescription({
  20593. type: desc.type,
  20594. sdp: transform.write(session)
  20595. });
  20596. };
  20597. /**
  20598. *
  20599. * @param desc
  20600. * @returns {RTCSessionDescription}
  20601. */
  20602. Simulcast.prototype.mungeLocalDescription = function (desc) {
  20603. if (!validateDescription(desc) || !this.isSupported()) {
  20604. return desc;
  20605. }
  20606. var session = transform.parse(desc.sdp);
  20607. var self = this;
  20608. processVideo(session, function (mLine) {
  20609. // Initialize native simulcast layers, if not already done.
  20610. self._maybeInitializeLayers(mLine);
  20611. // Update the SDP with the simulcast layers.
  20612. self._restoreSimulcastView(mLine);
  20613. });
  20614. return new RTCSessionDescription({
  20615. type: desc.type,
  20616. sdp: transform.write(session)
  20617. });
  20618. };
  20619. //endregion
  20620. module.exports = Simulcast;
  20621. },{"./transform-utils":74,"sdp-transform":76}],74:[function(require,module,exports){
  20622. /* Copyright @ 2015 Atlassian Pty Ltd
  20623. *
  20624. * Licensed under the Apache License, Version 2.0 (the "License");
  20625. * you may not use this file except in compliance with the License.
  20626. * You may obtain a copy of the License at
  20627. *
  20628. * http://www.apache.org/licenses/LICENSE-2.0
  20629. *
  20630. * Unless required by applicable law or agreed to in writing, software
  20631. * distributed under the License is distributed on an "AS IS" BASIS,
  20632. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20633. * See the License for the specific language governing permissions and
  20634. * limitations under the License.
  20635. */
  20636. exports.writeSsrcs = function(sources, order) {
  20637. var ssrcs = [];
  20638. // expand sources to ssrcs
  20639. if (typeof sources !== 'undefined' &&
  20640. Object.keys(sources).length !== 0) {
  20641. if (Array.isArray(order)) {
  20642. for (var i = 0; i < order.length; i++) {
  20643. var ssrc = order[i];
  20644. var source = sources[ssrc];
  20645. Object.keys(source).forEach(function (attribute) {
  20646. ssrcs.push({
  20647. id: ssrc,
  20648. attribute: attribute,
  20649. value: source[attribute]
  20650. });
  20651. });
  20652. }
  20653. } else {
  20654. Object.keys(sources).forEach(function (ssrc) {
  20655. var source = sources[ssrc];
  20656. Object.keys(source).forEach(function (attribute) {
  20657. ssrcs.push({
  20658. id: ssrc,
  20659. attribute: attribute,
  20660. value: source[attribute]
  20661. });
  20662. });
  20663. });
  20664. }
  20665. }
  20666. return ssrcs;
  20667. };
  20668. exports.parseSsrcs = function (mLine) {
  20669. var sources = {};
  20670. // group sources attributes by ssrc.
  20671. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20672. mLine.ssrcs.forEach(function (ssrc) {
  20673. if (!sources[ssrc.id])
  20674. sources[ssrc.id] = {};
  20675. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20676. });
  20677. }
  20678. return sources;
  20679. };
  20680. },{}],75:[function(require,module,exports){
  20681. arguments[4][69][0].apply(exports,arguments)
  20682. },{"dup":69}],76:[function(require,module,exports){
  20683. arguments[4][70][0].apply(exports,arguments)
  20684. },{"./parser":77,"./writer":78,"dup":70}],77:[function(require,module,exports){
  20685. arguments[4][71][0].apply(exports,arguments)
  20686. },{"./grammar":75,"dup":71}],78:[function(require,module,exports){
  20687. arguments[4][72][0].apply(exports,arguments)
  20688. },{"./grammar":75,"dup":72}],79:[function(require,module,exports){
  20689. var MediaStreamType = {
  20690. VIDEO_TYPE: "Video",
  20691. AUDIO_TYPE: "Audio"
  20692. };
  20693. module.exports = MediaStreamType;
  20694. },{}],80:[function(require,module,exports){
  20695. var RTCEvents = {
  20696. RTC_READY: "rtc.ready",
  20697. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20698. LASTN_CHANGED: "rtc.lastn_changed",
  20699. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20700. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20701. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20702. };
  20703. module.exports = RTCEvents;
  20704. },{}],81:[function(require,module,exports){
  20705. var Resolutions = {
  20706. "1080": {
  20707. width: 1920,
  20708. height: 1080,
  20709. order: 7
  20710. },
  20711. "fullhd": {
  20712. width: 1920,
  20713. height: 1080,
  20714. order: 7
  20715. },
  20716. "720": {
  20717. width: 1280,
  20718. height: 720,
  20719. order: 6
  20720. },
  20721. "hd": {
  20722. width: 1280,
  20723. height: 720,
  20724. order: 6
  20725. },
  20726. "960": {
  20727. width: 960,
  20728. height: 720,
  20729. order: 5
  20730. },
  20731. "640": {
  20732. width: 640,
  20733. height: 480,
  20734. order: 4
  20735. },
  20736. "vga": {
  20737. width: 640,
  20738. height: 480,
  20739. order: 4
  20740. },
  20741. "360": {
  20742. width: 640,
  20743. height: 360,
  20744. order: 3
  20745. },
  20746. "320": {
  20747. width: 320,
  20748. height: 240,
  20749. order: 2
  20750. },
  20751. "180": {
  20752. width: 320,
  20753. height: 180,
  20754. order: 1
  20755. }
  20756. };
  20757. module.exports = Resolutions;
  20758. },{}],82:[function(require,module,exports){
  20759. var XMPPEvents = {
  20760. // Designates an event indicating that the connection to the XMPP server
  20761. // failed.
  20762. CONNECTION_FAILED: "xmpp.connection.failed",
  20763. // Designates an event indicating that the media (ICE) connection was
  20764. // interrupted. This should go to the RTC module.
  20765. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20766. // Designates an event indicating that the media (ICE) connection was
  20767. // restored. This should go to the RTC module.
  20768. CONNECTION_RESTORED: "xmpp.connection.restored",
  20769. // Designates an event indicating that an offer (e.g. Jingle
  20770. // session-initiate) was received.
  20771. CALL_INCOMING: "xmpp.callincoming.jingle",
  20772. // Designates an event indicating that we were kicked from the XMPP MUC.
  20773. KICKED: "xmpp.kicked",
  20774. // Designates an event indicating that the userID for a specific JID has
  20775. // changed.
  20776. // Note: currently this event fires every time we receive presence from
  20777. // someone (regardless of whether or not the "userID" changed).
  20778. USER_ID_CHANGED: "xmpp.user_id_changed",
  20779. // Designates an event indicating that we have joined the XMPP MUC.
  20780. MUC_JOINED: "xmpp.muc_joined",
  20781. // Designates an event indicating that a participant joined the XMPP MUC.
  20782. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20783. // Designates an event indicating that a participant left the XMPP MUC.
  20784. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20785. // Designates an event indicating that the MUC role of a participant has
  20786. // changed.
  20787. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20788. // Designates an event indicating that the XMPP MUC was destroyed.
  20789. MUC_DESTROYED: "xmpp.muc_destroyed",
  20790. // Designates an event indicating that the display name of a participant
  20791. // has changed.
  20792. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20793. // Designates an event indicating that we received statistics from a
  20794. // participant in the MUC.
  20795. REMOTE_STATS: "xmpp.remote_stats",
  20796. // Designates an event indicating that our role in the XMPP MUC has changed.
  20797. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20798. // Designates an event indicating that the subject of the XMPP MUC has
  20799. // changed.
  20800. SUBJECT_CHANGED: "xmpp.subject_changed",
  20801. // Designates an event indicating that an XMPP message in the MUC was
  20802. // received.
  20803. MESSAGE_RECEIVED: "xmpp.message_received",
  20804. // Designates an event indicating that we sent an XMPP message to the MUC.
  20805. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20806. // Designates an event indicating that the video type (e.g. 'camera' or
  20807. // 'screen') for a participant has changed.
  20808. // Note: currently this event fires every time we receive presence from
  20809. // someone (regardless of whether or not the "video type" changed).
  20810. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20811. // Designates an event indicating that a participant in the XMPP MUC has
  20812. // advertised that they have audio muted (or unmuted).
  20813. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20814. // Designates an event indicating that a participant in the XMPP MUC has
  20815. // advertised that they have video muted (or unmuted).
  20816. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20817. // Designates an event indicating that the focus has asked us to mute our
  20818. // audio.
  20819. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20820. // Designates an event indicating that a moderator in the room changed the
  20821. // "start muted" settings for the conference.
  20822. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20823. // Designates an event indicating that we should join the conference with
  20824. // audio and/or video muted.
  20825. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20826. // Designates an event indicating that a remote participant's available
  20827. // devices (whether he supports a audio and/or video) changed.
  20828. // Note: currently this event fires every time we receive presence from
  20829. // someone (regardless of whether or not the devices changed).
  20830. DEVICE_AVAILABLE: "xmpp.device_available",
  20831. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20832. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20833. PASSWORD_REQUIRED: "xmpp.password_required",
  20834. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20835. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20836. ETHERPAD: "xmpp.etherpad",
  20837. BRIDGE_DOWN: "xmpp.bridge_down",
  20838. PRESENCE_STATUS: "xmpp.presence_status",
  20839. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20840. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20841. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20842. // TODO: only used in a hack, should probably be removed.
  20843. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20844. // TODO: only used in a hack, should probably be removed.
  20845. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20846. // TODO: only used in a hack, should probably be removed.
  20847. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20848. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20849. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20850. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20851. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20852. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20853. // xmpp is connected and obtained user media
  20854. READY_TO_JOIN: 'xmpp.ready_to_join',
  20855. FOCUS_LEFT: "xmpp.focus_left",
  20856. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  20857. /**
  20858. * Indicates that recording state changed.
  20859. */
  20860. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  20861. /**
  20862. * Indicates that phone number changed.
  20863. */
  20864. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  20865. };
  20866. module.exports = XMPPEvents;
  20867. },{}],83:[function(require,module,exports){
  20868. var AuthenticationEvents = {
  20869. /**
  20870. * Event callback arguments:
  20871. * function(authenticationEnabled, userIdentity)
  20872. * authenticationEnabled - indicates whether authentication has been enabled
  20873. * in this session
  20874. * userIdentity - if user has been logged in then it contains user name. If
  20875. * contains 'null' or 'undefined' then user is not logged in.
  20876. */
  20877. IDENTITY_UPDATED: "authentication.identity_updated"
  20878. };
  20879. module.exports = AuthenticationEvents;
  20880. },{}],84:[function(require,module,exports){
  20881. var DesktopSharingEventTypes = {
  20882. INIT: "ds.init",
  20883. SWITCHING_DONE: "ds.switching_done",
  20884. NEW_STREAM_CREATED: "ds.new_stream_created",
  20885. /**
  20886. * An event which indicates that the jidesha extension for Firefox is
  20887. * needed to proceed with screen sharing, and that it is not installed.
  20888. */
  20889. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20890. };
  20891. module.exports = DesktopSharingEventTypes;
  20892. },{}],85:[function(require,module,exports){
  20893. module.exports = {
  20894. /**
  20895. * An event carrying connection statistics.
  20896. */
  20897. CONNECTION_STATS: "statistics.connectionstats",
  20898. /**
  20899. * FIXME: needs documentation.
  20900. */
  20901. AUDIO_LEVEL: "statistics.audioLevel",
  20902. /**
  20903. * FIXME: needs documentation.
  20904. */
  20905. STOP: "statistics.stop"
  20906. };
  20907. },{}],86:[function(require,module,exports){
  20908. var Constants = {
  20909. LOCAL_JID: 'local'
  20910. };
  20911. module.exports = Constants;
  20912. },{}],87:[function(require,module,exports){
  20913. arguments[4][82][0].apply(exports,arguments)
  20914. },{"dup":82}]},{},[7])(7)
  20915. });