You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lib-jitsi-meet.js 753KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121
  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, $ */
  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 RTCEvents = require("./service/RTC/RTCEvents");
  9. var EventEmitter = require("events");
  10. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  11. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  12. var JitsiParticipant = require("./JitsiParticipant");
  13. var Statistics = require("./modules/statistics/statistics");
  14. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  15. var JitsiTrackEvents = require("./JitsiTrackEvents");
  16. /**
  17. * Creates a JitsiConference object with the given name and properties.
  18. * Note: this constructor is not a part of the public API (objects should be
  19. * created using JitsiConnection.createConference).
  20. * @param options.config properties / settings related to the conference that will be created.
  21. * @param options.name the name of the conference
  22. * @param options.connection the JitsiConnection object for this JitsiConference.
  23. * @constructor
  24. */
  25. function JitsiConference(options) {
  26. if(!options.name || options.name.toLowerCase() !== options.name) {
  27. logger.error("Invalid conference name (no conference name passed or it"
  28. + "contains invalid characters like capital letters)!");
  29. return;
  30. }
  31. this.options = options;
  32. this.connection = this.options.connection;
  33. this.xmpp = this.connection.xmpp;
  34. this.eventEmitter = new EventEmitter();
  35. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  36. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  37. this.rtc = new RTC(this.room, options);
  38. if(!RTC.options.disableAudioLevels)
  39. this.statistics = new Statistics();
  40. setupListeners(this);
  41. this.participants = {};
  42. this.lastActiveSpeaker = null;
  43. this.dtmfManager = null;
  44. this.somebodySupportsDTMF = false;
  45. }
  46. /**
  47. * Joins the conference.
  48. * @param password {string} the password
  49. */
  50. JitsiConference.prototype.join = function (password) {
  51. if(this.room)
  52. this.room.join(password, this.connection.tokenPassword);
  53. };
  54. /**
  55. * Leaves the conference.
  56. */
  57. JitsiConference.prototype.leave = function () {
  58. if(this.xmpp && this.room)
  59. this.xmpp.leaveRoom(this.room.roomjid);
  60. this.room = null;
  61. };
  62. /**
  63. * Returns the local tracks.
  64. */
  65. JitsiConference.prototype.getLocalTracks = function () {
  66. if (this.rtc) {
  67. return this.rtc.localStreams;
  68. } else {
  69. return [];
  70. }
  71. };
  72. /**
  73. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  74. * in JitsiConferenceEvents.
  75. * @param eventId the event ID.
  76. * @param handler handler for the event.
  77. *
  78. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  79. */
  80. JitsiConference.prototype.on = function (eventId, handler) {
  81. if(this.eventEmitter)
  82. this.eventEmitter.on(eventId, handler);
  83. };
  84. /**
  85. * Removes event listener
  86. * @param eventId the event ID.
  87. * @param [handler] optional, the specific handler to unbind
  88. *
  89. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  90. */
  91. JitsiConference.prototype.off = function (eventId, handler) {
  92. if(this.eventEmitter)
  93. this.eventEmitter.removeListener(eventId, handler);
  94. };
  95. // Common aliases for event emitter
  96. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  97. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  98. /**
  99. * Receives notifications from another participants for commands / custom events
  100. * (send by sendPresenceCommand method).
  101. * @param command {String} the name of the command
  102. * @param handler {Function} handler for the command
  103. */
  104. JitsiConference.prototype.addCommandListener = function (command, handler) {
  105. if(this.room)
  106. this.room.addPresenceListener(command, handler);
  107. };
  108. /**
  109. * Removes command listener
  110. * @param command {String} the name of the command
  111. */
  112. JitsiConference.prototype.removeCommandListener = function (command) {
  113. if(this.room)
  114. this.room.removePresenceListener(command);
  115. };
  116. /**
  117. * Sends text message to the other participants in the conference
  118. * @param message the text message.
  119. */
  120. JitsiConference.prototype.sendTextMessage = function (message) {
  121. if(this.room)
  122. this.room.sendMessage(message);
  123. };
  124. /**
  125. * Send presence command.
  126. * @param name the name of the command.
  127. * @param values Object with keys and values that will be send.
  128. **/
  129. JitsiConference.prototype.sendCommand = function (name, values) {
  130. if(this.room) {
  131. this.room.addToPresence(name, values);
  132. this.room.sendPresence();
  133. }
  134. };
  135. /**
  136. * Send presence command one time.
  137. * @param name the name of the command.
  138. * @param values Object with keys and values that will be send.
  139. **/
  140. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  141. this.sendCommand(name, values);
  142. this.removeCommand(name);
  143. };
  144. /**
  145. * Send presence command.
  146. * @param name the name of the command.
  147. * @param values Object with keys and values that will be send.
  148. * @param persistent if false the command will be sent only one time
  149. **/
  150. JitsiConference.prototype.removeCommand = function (name) {
  151. if(this.room)
  152. this.room.removeFromPresence(name);
  153. };
  154. /**
  155. * Sets the display name for this conference.
  156. * @param name the display name to set
  157. */
  158. JitsiConference.prototype.setDisplayName = function(name) {
  159. if(this.room){
  160. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  161. this.room.sendPresence();
  162. }
  163. };
  164. /**
  165. * Adds JitsiLocalTrack object to the conference.
  166. * @param track the JitsiLocalTrack object.
  167. */
  168. JitsiConference.prototype.addTrack = function (track) {
  169. this.room.addStream(track.getOriginalStream(), function () {
  170. this.rtc.addLocalStream(track);
  171. var muteHandler = this._fireMuteChangeEvent.bind(this, track);
  172. var stopHandler = this.removeTrack.bind(this, track);
  173. var audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  174. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  175. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  176. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  177. this.addEventListener(JitsiConferenceEvents.TRACK_REMOVED, function (someTrack) {
  178. if (someTrack !== track) {
  179. return;
  180. }
  181. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, muteHandler);
  182. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, stopHandler);
  183. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, audioLevelHandler);
  184. });
  185. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  186. }.bind(this));
  187. };
  188. /**
  189. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  190. * @param audioLevel the audio level
  191. */
  192. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  193. this.eventEmitter.emit(
  194. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  195. this.myUserId(), audioLevel);
  196. };
  197. /**
  198. * Fires TRACK_MUTE_CHANGED change conference event.
  199. * @param track the JitsiTrack object related to the event.
  200. */
  201. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  202. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  203. };
  204. /**
  205. * Removes JitsiLocalTrack object to the conference.
  206. * @param track the JitsiLocalTrack object.
  207. */
  208. JitsiConference.prototype.removeTrack = function (track) {
  209. this.room.removeStream(track.getOriginalStream(), function(){
  210. this.rtc.removeLocalStream(track);
  211. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  212. }.bind(this));
  213. };
  214. /**
  215. * Get role of the local user.
  216. * @returns {string} user role: 'moderator' or 'none'
  217. */
  218. JitsiConference.prototype.getRole = function () {
  219. return this.room.role;
  220. };
  221. /**
  222. * Check if local user is moderator.
  223. * @returns {boolean} true if local user is moderator, false otherwise.
  224. */
  225. JitsiConference.prototype.isModerator = function () {
  226. return this.room.isModerator();
  227. };
  228. /**
  229. * Set password for the room.
  230. * @param {string} password new password for the room.
  231. * @returns {Promise}
  232. */
  233. JitsiConference.prototype.lock = function (password) {
  234. if (!this.isModerator()) {
  235. return Promise.reject();
  236. }
  237. var conference = this;
  238. return new Promise(function (resolve, reject) {
  239. conference.xmpp.lockRoom(password, function () {
  240. resolve();
  241. }, function (err) {
  242. reject(err);
  243. }, function () {
  244. reject(JitsiConferenceErrors.PASSWORD_REQUIRED);
  245. });
  246. });
  247. };
  248. /**
  249. * Remove password from the room.
  250. * @returns {Promise}
  251. */
  252. JitsiConference.prototype.unlock = function () {
  253. return this.lock(undefined);
  254. };
  255. /**
  256. * Elects the participant with the given id to be the selected participant or the speaker.
  257. * @param id the identifier of the participant
  258. */
  259. JitsiConference.prototype.selectParticipant = function(participantId) {
  260. if (this.rtc) {
  261. this.rtc.selectedEndpoint(participantId);
  262. }
  263. };
  264. /**
  265. *
  266. * @param id the identifier of the participant
  267. */
  268. JitsiConference.prototype.pinParticipant = function(participantId) {
  269. if (this.rtc) {
  270. this.rtc.pinEndpoint(participantId);
  271. }
  272. };
  273. /**
  274. * Returns the list of participants for this conference.
  275. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  276. */
  277. JitsiConference.prototype.getParticipants = function() {
  278. return Object.keys(this.participants).map(function (key) {
  279. return this.participants[key];
  280. }, this);
  281. };
  282. /**
  283. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  284. * undefined if there isn't one).
  285. * @param id the id of the participant.
  286. */
  287. JitsiConference.prototype.getParticipantById = function(id) {
  288. return this.participants[id];
  289. };
  290. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  291. var id = Strophe.getResourceFromJid(jid);
  292. if (id === 'focus') {
  293. return;
  294. }
  295. var participant = new JitsiParticipant(id, this, nick);
  296. this.participants[id] = participant;
  297. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  298. this.xmpp.connection.disco.info(
  299. jid, "node", function(iq) {
  300. participant._supportsDTMF = $(iq).find(
  301. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  302. this.updateDTMFSupport();
  303. }.bind(this)
  304. );
  305. };
  306. JitsiConference.prototype.onMemberLeft = function (jid) {
  307. var id = Strophe.getResourceFromJid(jid);
  308. var participant = this.participants[id];
  309. delete this.participants[id];
  310. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  311. };
  312. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  313. var id = Strophe.getResourceFromJid(jid);
  314. var participant = this.getParticipantById(id);
  315. if (!participant) {
  316. return;
  317. }
  318. participant._role = role;
  319. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  320. };
  321. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  322. var id = Strophe.getResourceFromJid(jid);
  323. var participant = this.getParticipantById(id);
  324. if (!participant) {
  325. return;
  326. }
  327. participant._displayName = displayName;
  328. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  329. };
  330. JitsiConference.prototype.onTrackAdded = function (track) {
  331. var id = track.getParticipantId();
  332. var participant = this.getParticipantById(id);
  333. if (!participant) {
  334. return;
  335. }
  336. // add track to JitsiParticipant
  337. participant._tracks.push(track);
  338. var emitter = this.eventEmitter;
  339. track.addEventListener(
  340. JitsiTrackEvents.TRACK_STOPPED,
  341. function () {
  342. // remove track from JitsiParticipant
  343. var pos = participant._tracks.indexOf(track);
  344. if (pos > -1) {
  345. participant._tracks.splice(pos, 1);
  346. }
  347. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  348. }
  349. );
  350. track.addEventListener(
  351. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  352. function () {
  353. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  354. }
  355. );
  356. track.addEventListener(
  357. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  358. function (audioLevel) {
  359. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  360. }
  361. );
  362. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  363. };
  364. JitsiConference.prototype.updateDTMFSupport = function () {
  365. var somebodySupportsDTMF = false;
  366. var participants = this.getParticipants();
  367. // check if at least 1 participant supports DTMF
  368. for (var i = 0; i < participants.length; i += 1) {
  369. if (participants[i].supportsDTMF()) {
  370. somebodySupportsDTMF = true;
  371. break;
  372. }
  373. }
  374. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  375. this.somebodySupportsDTMF = somebodySupportsDTMF;
  376. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  377. }
  378. };
  379. /**
  380. * Allows to check if there is at least one user in the conference
  381. * that supports DTMF.
  382. * @returns {boolean} true if somebody supports DTMF, false otherwise
  383. */
  384. JitsiConference.prototype.isDTMFSupported = function () {
  385. return this.somebodySupportsDTMF;
  386. };
  387. /**
  388. * Returns the local user's ID
  389. * @return {string} local user's ID
  390. */
  391. JitsiConference.prototype.myUserId = function () {
  392. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  393. };
  394. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  395. if (!this.dtmfManager) {
  396. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  397. if (!connection) {
  398. logger.warn("cannot sendTones: no conneciton");
  399. return;
  400. }
  401. var tracks = this.getLocalTracks().filter(function (track) {
  402. return track.isAudioTrack();
  403. });
  404. if (!tracks.length) {
  405. logger.warn("cannot sendTones: no local audio stream");
  406. return;
  407. }
  408. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  409. }
  410. this.dtmfManager.sendTones(tones, duration, pause);
  411. };
  412. /**
  413. * Setups the listeners needed for the conference.
  414. * @param conference the conference
  415. */
  416. function setupListeners(conference) {
  417. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  418. conference.rtc.onIncommingCall(event);
  419. if(conference.statistics)
  420. conference.statistics.startRemoteStats(event.peerconnection);
  421. });
  422. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  423. function (data, sid, thessrc) {
  424. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  425. if (track) {
  426. conference.onTrackAdded(track);
  427. }
  428. }
  429. );
  430. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  431. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  432. });
  433. // FIXME
  434. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  435. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  436. // });
  437. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  438. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  439. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  440. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  441. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  442. });
  443. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  444. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  445. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  446. });
  447. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  448. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  449. });
  450. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  451. conference.eventEmitter.emit(JitsiConferenceEvents.SETUP_FAILED);
  452. });
  453. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  454. if(conference.lastActiveSpeaker !== id && conference.room) {
  455. conference.lastActiveSpeaker = id;
  456. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  457. }
  458. });
  459. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  460. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  461. });
  462. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  463. function (lastNEndpoints, endpointsEnteringLastN) {
  464. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  465. lastNEndpoints, endpointsEnteringLastN);
  466. });
  467. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  468. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  469. });
  470. if(conference.statistics) {
  471. //FIXME: Maybe remove event should not be associated with the conference.
  472. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  473. var userId = null;
  474. var jid = conference.room.getJidBySSRC(ssrc);
  475. if (!jid)
  476. return;
  477. conference.rtc.setAudioLevel(jid, level);
  478. });
  479. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  480. function () {
  481. conference.statistics.dispose();
  482. });
  483. // FIXME: Maybe we should move this.
  484. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  485. // conference.room.updateDeviceAvailability(devices);
  486. // });
  487. }
  488. }
  489. module.exports = JitsiConference;
  490. }).call(this,"/JitsiConference.js")
  491. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":79,"./service/xmpp/XMPPEvents":85,"events":43,"jitsi-meet-logger":47}],2:[function(require,module,exports){
  492. /**
  493. * Enumeration with the errors for the conference.
  494. * @type {{string: string}}
  495. */
  496. var JitsiConferenceErrors = {
  497. /**
  498. * Indicates that a password is required in order to join the conference.
  499. */
  500. PASSWORD_REQUIRED: "conference.passwordRequired",
  501. /**
  502. * Indicates that password cannot be set for this conference.
  503. */
  504. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  505. /**
  506. * Indicates that a connection error occurred when trying to join a
  507. * conference.
  508. */
  509. CONNECTION_ERROR: "conference.connectionError",
  510. /**
  511. * Indicates that there is no available videobridge.
  512. */
  513. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  514. /**
  515. * Many more errors TBD here.
  516. */
  517. };
  518. module.exports = JitsiConferenceErrors;
  519. },{}],3:[function(require,module,exports){
  520. /**
  521. * Enumeration with the events for the conference.
  522. * @type {{string: string}}
  523. */
  524. var JitsiConferenceEvents = {
  525. /**
  526. * A new media track was added to the conference.
  527. */
  528. TRACK_ADDED: "conference.trackAdded",
  529. /**
  530. * The media track was removed from the conference.
  531. */
  532. TRACK_REMOVED: "conference.trackRemoved",
  533. /**
  534. * The active speaker was changed.
  535. */
  536. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  537. /**
  538. * A new user joinned the conference.
  539. */
  540. USER_JOINED: "conference.userJoined",
  541. /**
  542. * A user has left the conference.
  543. */
  544. USER_LEFT: "conference.userLeft",
  545. /**
  546. * User role changed.
  547. */
  548. USER_ROLE_CHANGED: "conference.roleChanged",
  549. /**
  550. * New text message was received.
  551. */
  552. MESSAGE_RECEIVED: "conference.messageReceived",
  553. /**
  554. * A user has changed it display name
  555. */
  556. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  557. /**
  558. * A participant avatar has changed.
  559. */
  560. AVATAR_CHANGED: "conference.avatarChanged",
  561. /**
  562. * New connection statistics are received.
  563. */
  564. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  565. /**
  566. * The Last N set is changed.
  567. */
  568. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  569. /**
  570. * You are included / excluded in somebody's last N set
  571. */
  572. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  573. /**
  574. * A media track ( attached to the conference) mute status was changed.
  575. */
  576. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  577. /**
  578. * Audio levels of a media track ( attached to the conference) was changed.
  579. */
  580. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  581. /**
  582. * Indicates that the connection to the conference has been interrupted
  583. * for some reason.
  584. */
  585. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  586. /**
  587. * Indicates that the connection to the conference has been restored.
  588. */
  589. CONNECTION_RESTORED: "conference.connectionRestored",
  590. /**
  591. * Indicates that the conference setup failed.
  592. */
  593. SETUP_FAILED: "conference.setup_failed",
  594. /**
  595. * Indicates that conference has been joined.
  596. */
  597. CONFERENCE_JOINED: "conference.joined",
  598. /**
  599. * Indicates that conference has been left.
  600. */
  601. CONFERENCE_LEFT: "conference.left",
  602. /**
  603. * Indicates that DTMF support changed.
  604. */
  605. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged"
  606. };
  607. module.exports = JitsiConferenceEvents;
  608. },{}],4:[function(require,module,exports){
  609. var JitsiConference = require("./JitsiConference");
  610. var XMPP = require("./modules/xmpp/xmpp");
  611. var RandomUtil = require("./modules/util/RandomUtil");
  612. /**
  613. * Utility method that generates user name based on random hex values.
  614. * Eg. 12345678-1234-1234-12345678
  615. * @returns {string}
  616. */
  617. function generateUserName() {
  618. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  619. "-" + RandomUtil.randomHexString(4) + "-" +
  620. RandomUtil.randomHexDigit(8);
  621. }
  622. /**
  623. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  624. * JitsiConference interface.
  625. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  626. * @param tokenPassword secret generated by the provider of Jitsi Meet video conferencing services.
  627. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  628. * The format is:
  629. * passwordToken = token + "_" + roomName + "_" + ts
  630. * See doc/tokens.md for more info on how tokens are generated.
  631. * @param options Object with properties / settings related to connection with the server.
  632. * @constructor
  633. */
  634. function JitsiConnection(appID, tokenPassword, options) {
  635. this.appID = appID;
  636. this.tokenPassword = tokenPassword;
  637. this.options = options;
  638. this.xmpp = new XMPP(options);
  639. this.conferences = {};
  640. }
  641. /**
  642. * Connect the client with the server.
  643. * @param options {object} connecting options (for example authentications parameters).
  644. */
  645. JitsiConnection.prototype.connect = function (options) {
  646. if(!options)
  647. options = {};
  648. // If we have token provided use it as a password and generate random username
  649. if (this.tokenPassword) {
  650. options.password = this.tokenPassword;
  651. if (!options.id) {
  652. options.id = generateUserName() + "@" + this.options.hosts.domain;
  653. }
  654. }
  655. this.xmpp.connect(options.id, options.password);
  656. }
  657. /**
  658. * Disconnect the client from the server.
  659. */
  660. JitsiConnection.prototype.disconnect = function () {
  661. this.xmpp.disconnect();
  662. }
  663. /**
  664. * This method allows renewal of the tokens if they are expiring.
  665. * @param token the new token.
  666. */
  667. JitsiConnection.prototype.setToken = function (token) {
  668. this.token = token;
  669. }
  670. /**
  671. * Creates and joins new conference.
  672. * @param name the name of the conference; if null - a generated name will be provided from the api
  673. * @param options Object with properties / settings related to the conference that will be created.
  674. * @returns {JitsiConference} returns the new conference object.
  675. */
  676. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  677. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  678. return this.conferences[name];
  679. }
  680. /**
  681. * Subscribes the passed listener to the event.
  682. * @param event {JitsiConnectionEvents} the connection event.
  683. * @param listener {Function} the function that will receive the event
  684. */
  685. JitsiConnection.prototype.addEventListener = function (event, listener) {
  686. this.xmpp.addListener(event, listener);
  687. }
  688. /**
  689. * Unsubscribes the passed handler.
  690. * @param event {JitsiConnectionEvents} the connection event.
  691. * @param listener {Function} the function that will receive the event
  692. */
  693. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  694. this.xmpp.removeListener(event, listener);
  695. }
  696. module.exports = JitsiConnection;
  697. },{"./JitsiConference":1,"./modules/util/RandomUtil":25,"./modules/xmpp/xmpp":41}],5:[function(require,module,exports){
  698. /**
  699. * Enumeration with the errors for the connection.
  700. * @type {{string: string}}
  701. */
  702. var JitsiConnectionErrors = {
  703. /**
  704. * Indicates that a password is required in order to join the conference.
  705. */
  706. PASSWORD_REQUIRED: "connection.passwordRequired",
  707. /**
  708. * Indicates that a connection error occurred when trying to join a
  709. * conference.
  710. */
  711. CONNECTION_ERROR: "connection.connectionError",
  712. /**
  713. * Not specified errors.
  714. */
  715. OTHER_ERROR: "connection.otherError"
  716. };
  717. module.exports = JitsiConnectionErrors;
  718. },{}],6:[function(require,module,exports){
  719. /**
  720. * Enumeration with the events for the connection.
  721. * @type {{string: string}}
  722. */
  723. var JitsiConnnectionEvents = {
  724. /**
  725. * Indicates that the connection has been failed for some reason.
  726. */
  727. CONNECTION_FAILED: "connection.connectionFailed",
  728. /**
  729. * Indicates that the connection has been established.
  730. */
  731. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  732. /**
  733. * Indicates that the connection has been disconnected.
  734. */
  735. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  736. /**
  737. * Indicates that the perfomed action cannot be executed because the
  738. * connection is not in the correct state(connected, disconnected, etc.)
  739. */
  740. WRONG_STATE: "connection.wrongState"
  741. };
  742. module.exports = JitsiConnnectionEvents;
  743. },{}],7:[function(require,module,exports){
  744. var JitsiConnection = require("./JitsiConnection");
  745. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  746. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  747. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  748. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  749. var JitsiTrackEvents = require("./JitsiTrackEvents");
  750. var JitsiTrackErrors = require("./JitsiTrackErrors");
  751. var Logger = require("jitsi-meet-logger");
  752. var RTC = require("./modules/RTC/RTC");
  753. var Statistics = require("./modules/statistics/statistics");
  754. /**
  755. * Namespace for the interface of Jitsi Meet Library.
  756. */
  757. var LibJitsiMeet = {
  758. JitsiConnection: JitsiConnection,
  759. events: {
  760. conference: JitsiConferenceEvents,
  761. connection: JitsiConnectionEvents,
  762. track: JitsiTrackEvents
  763. },
  764. errors: {
  765. conference: JitsiConferenceErrors,
  766. connection: JitsiConnectionErrors,
  767. track: JitsiTrackErrors
  768. },
  769. logLevels: Logger.levels,
  770. init: function (options) {
  771. return RTC.init(options || {});
  772. },
  773. setLogLevel: function (level) {
  774. Logger.setLogLevel(level);
  775. },
  776. /**
  777. * Creates the media tracks and returns them trough the callback.
  778. * @param options Object with properties / settings specifying the tracks which should be created.
  779. * should be created or some additional configurations about resolution for example.
  780. * @param {Array} options.devices the devices that will be requested
  781. * @param {string} options.resolution resolution constraints
  782. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  783. * type: "audio" or "video", videoType: "camera" or "desktop"}
  784. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  785. * @param {string} options.cameraDeviceId
  786. * @param {string} options.micDeviceId
  787. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  788. * A promise that returns an array of created JitsiTracks if resolved,
  789. * or a JitsiConferenceError if rejected.
  790. */
  791. createLocalTracks: function (options) {
  792. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  793. function(tracks) {
  794. if(!RTC.options.disableAudioLevels)
  795. for(var i = 0; i < tracks.length; i++) {
  796. var track = tracks[i];
  797. var mStream = track.getOriginalStream();
  798. if(track.getType() === "audio"){
  799. Statistics.startLocalStats(mStream,
  800. track.setAudioLevel.bind(track));
  801. track.addEventListener(
  802. JitsiTrackEvents.TRACK_STOPPED,
  803. function(){
  804. Statistics.stopLocalStats(mStream);
  805. });
  806. }
  807. }
  808. return tracks;
  809. });
  810. },
  811. isDeviceListAvailable: function () {
  812. return RTC.isDeviceListAvailable();
  813. },
  814. enumerateDevices: function (callback) {
  815. RTC.enumerateDevices(callback);
  816. }
  817. };
  818. require("es6-promise").polyfill()
  819. //Setups the promise object.
  820. window.Promise = window.Promise || require("es6-promise").Promise;
  821. module.exports = LibJitsiMeet;
  822. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"es6-promise":45,"jitsi-meet-logger":47}],8:[function(require,module,exports){
  823. /**
  824. * Represents a participant in (a member of) a conference.
  825. */
  826. function JitsiParticipant(id, conference, displayName){
  827. this._id = id;
  828. this._conference = conference;
  829. this._displayName = displayName;
  830. this._supportsDTMF = false;
  831. this._tracks = [];
  832. this._role = 'none';
  833. }
  834. /**
  835. * @returns {JitsiConference} The conference that this participant belongs to.
  836. */
  837. JitsiParticipant.prototype.getConference = function() {
  838. return this._conference;
  839. };
  840. /**
  841. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  842. */
  843. JitsiParticipant.prototype.getTracks = function() {
  844. return this._tracks;
  845. };
  846. /**
  847. * @returns {String} The ID (i.e. JID) of this participant.
  848. */
  849. JitsiParticipant.prototype.getId = function() {
  850. return this._id;
  851. };
  852. /**
  853. * @returns {String} The human-readable display name of this participant.
  854. */
  855. JitsiParticipant.prototype.getDisplayName = function() {
  856. return this._displayName;
  857. };
  858. /**
  859. * @returns {Boolean} Whether this participant is a moderator or not.
  860. */
  861. JitsiParticipant.prototype.isModerator = function() {
  862. return this._role === 'moderator';
  863. };
  864. // Gets a link to an etherpad instance advertised by the participant?
  865. //JitsiParticipant.prototype.getEtherpad = function() {
  866. //
  867. //}
  868. /*
  869. * @returns {Boolean} Whether this participant has muted their audio.
  870. */
  871. JitsiParticipant.prototype.isAudioMuted = function() {
  872. return this.getTracks().reduce(function (track, isAudioMuted) {
  873. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  874. }, true);
  875. };
  876. /*
  877. * @returns {Boolean} Whether this participant has muted their video.
  878. */
  879. JitsiParticipant.prototype.isVideoMuted = function() {
  880. return this.getTracks().reduce(function (track, isVideoMuted) {
  881. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  882. }, true);
  883. };
  884. /*
  885. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  886. * TODO: do we expose this or handle it internally?
  887. */
  888. JitsiParticipant.prototype.getLatestStats = function() {
  889. };
  890. /**
  891. * @returns {String} The role of this participant.
  892. */
  893. JitsiParticipant.prototype.getRole = function() {
  894. return this._role;
  895. };
  896. /*
  897. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  898. */
  899. JitsiParticipant.prototype.isFocus = function() {
  900. };
  901. /*
  902. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  903. */
  904. JitsiParticipant.prototype.isRecorder = function() {
  905. };
  906. /*
  907. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  908. */
  909. JitsiParticipant.prototype.isSipGateway = function() {
  910. };
  911. /**
  912. * @returns {Boolean} Whether this participant is currently sharing their screen.
  913. */
  914. JitsiParticipant.prototype.isScreenSharing = function() {
  915. };
  916. /**
  917. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  918. */
  919. JitsiParticipant.prototype.getUserAgent = function() {
  920. };
  921. /**
  922. * Kicks the participant from the conference (requires certain privileges).
  923. */
  924. JitsiParticipant.prototype.kick = function() {
  925. };
  926. /**
  927. * Asks this participant to mute themselves.
  928. */
  929. JitsiParticipant.prototype.askToMute = function() {
  930. };
  931. JitsiParticipant.prototype.supportsDTMF = function () {
  932. return this._supportsDTMF;
  933. };
  934. module.exports = JitsiParticipant;
  935. },{}],9:[function(require,module,exports){
  936. module.exports = {
  937. /**
  938. * Returns JitsiTrackErrors based on the error object passed by GUM
  939. * @param error the error
  940. * @param {Object} options the options object given to GUM.
  941. */
  942. parseError: function (error, options) {
  943. options = options || {};
  944. if (typeof error == "object" && error.constraintName && error.name
  945. && (error.name == "ConstraintNotSatisfiedError" ||
  946. error.name == "OverconstrainedError") &&
  947. (error.constraintName == "minWidth" ||
  948. error.constraintName == "maxWidth" ||
  949. error.constraintName == "minHeight" ||
  950. error.constraintName == "maxHeight") &&
  951. options.devices.indexOf("video") !== -1) {
  952. return this.UNSUPPORTED_RESOLUTION;
  953. } else {
  954. return this.GENERAL;
  955. }
  956. },
  957. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  958. GENERAL: "gum.general"
  959. };
  960. },{}],10:[function(require,module,exports){
  961. var JitsiTrackEvents = {
  962. /**
  963. * A media track mute status was changed.
  964. */
  965. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  966. /**
  967. * Audio levels of a this track was changed.
  968. */
  969. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  970. /**
  971. * The media track was removed to the conference.
  972. */
  973. TRACK_STOPPED: "track.stopped"
  974. };
  975. module.exports = JitsiTrackEvents;
  976. },{}],11:[function(require,module,exports){
  977. (function (__filename){
  978. var logger = require("jitsi-meet-logger").getLogger(__filename);
  979. function JitsiDTMFManager (localAudio, peerConnection) {
  980. var tracks = localAudio._getTracks();
  981. if (!tracks.length) {
  982. throw new Error("Failed to initialize DTMFSender: no audio track.");
  983. }
  984. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  985. logger.debug("Initialized DTMFSender");
  986. }
  987. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  988. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  989. };
  990. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  991. },{"jitsi-meet-logger":47}],12:[function(require,module,exports){
  992. (function (__filename){
  993. /* global config, APP, Strophe */
  994. // cache datachannels to avoid garbage collection
  995. // https://code.google.com/p/chromium/issues/detail?id=405545
  996. var logger = require("jitsi-meet-logger").getLogger(__filename);
  997. var RTCEvents = require("../../service/RTC/RTCEvents");
  998. /**
  999. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1000. * @param peerConnection WebRTC peer connection instance.
  1001. */
  1002. function DataChannels(peerConnection, emitter) {
  1003. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1004. this.eventEmitter = emitter;
  1005. this._dataChannels = [];
  1006. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1007. // Although it's not a requirement to open separate channels from both bridge
  1008. // and peer as single channel can be used for sending and receiving data.
  1009. // So either channel opened by the bridge or the one opened here is enough
  1010. // for communication with the bridge.
  1011. /*var dataChannelOptions =
  1012. {
  1013. reliable: true
  1014. };
  1015. var dataChannel
  1016. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1017. // Can be used only when is in open state
  1018. dataChannel.onopen = function ()
  1019. {
  1020. dataChannel.send("My channel !!!");
  1021. };
  1022. dataChannel.onmessage = function (event)
  1023. {
  1024. var msgData = event.data;
  1025. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1026. };*/
  1027. };
  1028. /**
  1029. * Callback triggered by PeerConnection when new data channel is opened
  1030. * on the bridge.
  1031. * @param event the event info object.
  1032. */
  1033. DataChannels.prototype.onDataChannel = function (event) {
  1034. var dataChannel = event.channel;
  1035. var self = this;
  1036. dataChannel.onopen = function () {
  1037. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1038. // Code sample for sending string and/or binary data
  1039. // Sends String message to the bridge
  1040. //dataChannel.send("Hello bridge!");
  1041. // Sends 12 bytes binary message to the bridge
  1042. //dataChannel.send(new ArrayBuffer(12));
  1043. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1044. };
  1045. dataChannel.onerror = function (error) {
  1046. logger.error("Data Channel Error:", error, dataChannel);
  1047. };
  1048. dataChannel.onmessage = function (event) {
  1049. var data = event.data;
  1050. // JSON
  1051. var obj;
  1052. try {
  1053. obj = JSON.parse(data);
  1054. }
  1055. catch (e) {
  1056. logger.error(
  1057. "Failed to parse data channel message as JSON: ",
  1058. data,
  1059. dataChannel);
  1060. }
  1061. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1062. var colibriClass = obj.colibriClass;
  1063. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1064. // Endpoint ID from the Videobridge.
  1065. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1066. logger.info(
  1067. "Data channel new dominant speaker event: ",
  1068. dominantSpeakerEndpoint);
  1069. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1070. }
  1071. else if ("InLastNChangeEvent" === colibriClass) {
  1072. var oldValue = obj.oldValue;
  1073. var newValue = obj.newValue;
  1074. // Make sure that oldValue and newValue are of type boolean.
  1075. var type;
  1076. if ((type = typeof oldValue) !== 'boolean') {
  1077. if (type === 'string') {
  1078. oldValue = (oldValue == "true");
  1079. } else {
  1080. oldValue = new Boolean(oldValue).valueOf();
  1081. }
  1082. }
  1083. if ((type = typeof newValue) !== 'boolean') {
  1084. if (type === 'string') {
  1085. newValue = (newValue == "true");
  1086. } else {
  1087. newValue = new Boolean(newValue).valueOf();
  1088. }
  1089. }
  1090. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1091. }
  1092. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1093. // The new/latest list of last-n endpoint IDs.
  1094. var lastNEndpoints = obj.lastNEndpoints;
  1095. // The list of endpoint IDs which are entering the list of
  1096. // last-n at this time i.e. were not in the old list of last-n
  1097. // endpoint IDs.
  1098. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1099. logger.info(
  1100. "Data channel new last-n event: ",
  1101. lastNEndpoints, endpointsEnteringLastN, obj);
  1102. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1103. lastNEndpoints, endpointsEnteringLastN, obj);
  1104. }
  1105. else {
  1106. logger.debug("Data channel JSON-formatted message: ", obj);
  1107. // The received message appears to be appropriately formatted
  1108. // (i.e. is a JSON object which assigns a value to the mandatory
  1109. // property colibriClass) so don't just swallow it, expose it to
  1110. // public consumption.
  1111. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1112. }
  1113. }
  1114. };
  1115. dataChannel.onclose = function () {
  1116. logger.info("The Data Channel closed", dataChannel);
  1117. var idx = self._dataChannels.indexOf(dataChannel);
  1118. if (idx > -1)
  1119. self._dataChannels = self._dataChannels.splice(idx, 1);
  1120. };
  1121. this._dataChannels.push(dataChannel);
  1122. };
  1123. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1124. this._onXXXEndpointChanged("selected", userResource);
  1125. }
  1126. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1127. this._onXXXEndpointChanged("pinnned", userResource);
  1128. }
  1129. /**
  1130. * Notifies Videobridge about a change in the value of a specific
  1131. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1132. *
  1133. * @param xxx the name of the endpoint-related property whose value changed
  1134. * @param userResource the new value of the endpoint-related property after the
  1135. * change
  1136. */
  1137. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1138. // Derive the correct words from xxx such as selected and Selected, pinned
  1139. // and Pinned.
  1140. var head = xxx.charAt(0);
  1141. var tail = xxx.substring(1);
  1142. var lower = head.toLowerCase() + tail;
  1143. var upper = head.toUpperCase() + tail;
  1144. // Notify Videobridge about the specified endpoint change.
  1145. console.log(lower + ' endpoint changed: ', userResource);
  1146. this._some(function (dataChannel) {
  1147. if (dataChannel.readyState == 'open') {
  1148. console.log(
  1149. 'sending ' + lower
  1150. + ' endpoint changed notification to the bridge: ',
  1151. userResource);
  1152. var jsonObject = {};
  1153. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1154. jsonObject[lower + "Endpoint"]
  1155. = (userResource ? userResource : null);
  1156. dataChannel.send(JSON.stringify(jsonObject));
  1157. return true;
  1158. }
  1159. });
  1160. }
  1161. DataChannels.prototype._some = function (callback, thisArg) {
  1162. var dataChannels = this._dataChannels;
  1163. if (dataChannels && dataChannels.length !== 0) {
  1164. if (thisArg)
  1165. return dataChannels.some(callback, thisArg);
  1166. else
  1167. return dataChannels.some(callback);
  1168. } else {
  1169. return false;
  1170. }
  1171. }
  1172. module.exports = DataChannels;
  1173. }).call(this,"/modules/RTC/DataChannels.js")
  1174. },{"../../service/RTC/RTCEvents":79,"jitsi-meet-logger":47}],13:[function(require,module,exports){
  1175. var JitsiTrack = require("./JitsiTrack");
  1176. var RTCBrowserType = require("./RTCBrowserType");
  1177. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1178. var RTC = require("./RTCUtils");
  1179. /**
  1180. * Represents a single media track (either audio or video).
  1181. * @constructor
  1182. */
  1183. function JitsiLocalTrack(stream, videoType,
  1184. resolution)
  1185. {
  1186. this.videoType = videoType;
  1187. this.dontFireRemoveEvent = false;
  1188. this.resolution = resolution;
  1189. this.startMuted = false;
  1190. var self = this;
  1191. JitsiTrack.call(this, null, stream,
  1192. function () {
  1193. if(!this.dontFireRemoveEvent)
  1194. this.eventEmitter.emit(
  1195. JitsiTrackEvents.TRACK_STOPPED);
  1196. this.dontFireRemoveEvent = false;
  1197. }.bind(this));
  1198. }
  1199. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1200. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1201. /**
  1202. * Mutes / unmutes the track.
  1203. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1204. */
  1205. JitsiLocalTrack.prototype._setMute = function (mute) {
  1206. if(!this.rtc) {
  1207. this.startMuted = mute;
  1208. return;
  1209. }
  1210. var isAudio = this.type === JitsiTrack.AUDIO;
  1211. this.dontFireRemoveEvent = false;
  1212. if ((window.location.protocol != "https:") ||
  1213. (isAudio) || this.videoType === "desktop" ||
  1214. // FIXME FF does not support 'removeStream' method used to mute
  1215. RTCBrowserType.isFirefox()) {
  1216. var tracks = this._getTracks();
  1217. for (var idx = 0; idx < tracks.length; idx++) {
  1218. tracks[idx].enabled = !mute;
  1219. }
  1220. if(isAudio)
  1221. this.rtc.room.setAudioMute(mute);
  1222. else
  1223. this.rtc.room.setVideoMute(mute);
  1224. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1225. } else {
  1226. if (mute) {
  1227. this.dontFireRemoveEvent = true;
  1228. this.rtc.room.removeStream(this.stream, function () {});
  1229. RTC.stopMediaStream(this.stream);
  1230. if(isAudio)
  1231. this.rtc.room.setAudioMute(mute);
  1232. else
  1233. this.rtc.room.setVideoMute(mute);
  1234. this.stream = null;
  1235. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1236. //FIXME: Maybe here we should set the SRC for the containers to something
  1237. } else {
  1238. var self = this;
  1239. RTC.obtainAudioAndVideoPermissions({
  1240. devices: (isAudio ? ["audio"] : ["video"]),
  1241. resolution: self.resolution})
  1242. .then(function (streams) {
  1243. var stream = null;
  1244. for(var i = 0; i < streams.length; i++) {
  1245. stream = streams[i];
  1246. if(stream.type === self.type) {
  1247. self.stream = stream.stream;
  1248. self.videoType = stream.videoType;
  1249. break;
  1250. }
  1251. }
  1252. if(!stream)
  1253. return;
  1254. for(var i = 0; i < self.containers.length; i++)
  1255. {
  1256. RTC.attachMediaStream(self.containers[i], self.stream);
  1257. }
  1258. self.rtc.room.addStream(stream.stream,
  1259. function () {
  1260. if(isAudio)
  1261. self.rtc.room.setAudioMute(mute);
  1262. else
  1263. self.rtc.room.setVideoMute(mute);
  1264. self.eventEmitter.emit(
  1265. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1266. });
  1267. });
  1268. }
  1269. }
  1270. }
  1271. /**
  1272. * Stops sending the media track. And removes it from the HTML.
  1273. * NOTE: Works for local tracks only.
  1274. */
  1275. JitsiLocalTrack.prototype.stop = function () {
  1276. if(!this.stream)
  1277. return;
  1278. if(this.rtc)
  1279. this.rtc.room.removeStream(this.stream, function () {});
  1280. RTC.stopMediaStream(this.stream);
  1281. this.detach();
  1282. }
  1283. /**
  1284. * Returns <tt>true</tt> - if the stream is muted
  1285. * and <tt>false</tt> otherwise.
  1286. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1287. * and <tt>false</tt> otherwise.
  1288. */
  1289. JitsiLocalTrack.prototype.isMuted = function () {
  1290. if (!this.stream)
  1291. return true;
  1292. var tracks = [];
  1293. var isAudio = this.type === JitsiTrack.AUDIO;
  1294. if (isAudio) {
  1295. tracks = this.stream.getAudioTracks();
  1296. } else {
  1297. if (!this.isActive())
  1298. return true;
  1299. tracks = this.stream.getVideoTracks();
  1300. }
  1301. for (var idx = 0; idx < tracks.length; idx++) {
  1302. if(tracks[idx].enabled)
  1303. return false;
  1304. }
  1305. return true;
  1306. };
  1307. /**
  1308. * Private method. Updates rtc property of the track.
  1309. * @param rtc the rtc instance.
  1310. */
  1311. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1312. this.rtc = rtc;
  1313. };
  1314. /**
  1315. * Return true;
  1316. */
  1317. JitsiLocalTrack.prototype.isLocal = function () {
  1318. return true;
  1319. }
  1320. module.exports = JitsiLocalTrack;
  1321. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1322. var JitsiTrack = require("./JitsiTrack");
  1323. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1324. /**
  1325. * Represents a single media track (either audio or video).
  1326. * @param RTC the rtc instance.
  1327. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1328. * @param sid sid for the Media Stream
  1329. * @param ssrc ssrc for the Media Stream
  1330. * @param eventEmitter the event emitter
  1331. * @constructor
  1332. */
  1333. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1334. JitsiTrack.call(this, RTC, data.stream,
  1335. function () {
  1336. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1337. }.bind(this));
  1338. this.rtc = RTC;
  1339. this.sid = sid;
  1340. this.stream = data.stream;
  1341. this.peerjid = data.peerjid;
  1342. this.videoType = data.videoType;
  1343. this.ssrc = ssrc;
  1344. this.muted = false;
  1345. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1346. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1347. this.muted = true;
  1348. }
  1349. }
  1350. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1351. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1352. /**
  1353. * Sets current muted status and fires an events for the change.
  1354. * @param value the muted status.
  1355. */
  1356. JitsiRemoteTrack.prototype.setMute = function (value) {
  1357. this.stream.muted = value;
  1358. this.muted = value;
  1359. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1360. };
  1361. /**
  1362. * Returns the current muted status of the track.
  1363. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1364. */
  1365. JitsiRemoteTrack.prototype.isMuted = function () {
  1366. return this.muted;
  1367. }
  1368. /**
  1369. * Returns the participant id which owns the track.
  1370. * @returns {string} the id of the participants.
  1371. */
  1372. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1373. return Strophe.getResourceFromJid(this.peerjid);
  1374. };
  1375. /**
  1376. * Return false;
  1377. */
  1378. JitsiRemoteTrack.prototype.isLocal = function () {
  1379. return false;
  1380. }
  1381. delete JitsiRemoteTrack.prototype.stop;
  1382. delete JitsiRemoteTrack.prototype.start;
  1383. module.exports = JitsiRemoteTrack;
  1384. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1385. var RTCBrowserType = require("./RTCBrowserType");
  1386. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1387. var EventEmitter = require("events");
  1388. /**
  1389. * This implements 'onended' callback normally fired by WebRTC after the stream
  1390. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1391. * @param jitsiTrack our track object holding the original WebRTC stream object
  1392. * to which 'onended' handling will be added.
  1393. */
  1394. function implementOnEndedHandling(jitsiTrack) {
  1395. var stream = jitsiTrack.getOriginalStream();
  1396. var originalStop = stream.stop;
  1397. stream.stop = function () {
  1398. originalStop.apply(stream);
  1399. if (jitsiTrack.isActive()) {
  1400. stream.onended();
  1401. }
  1402. };
  1403. }
  1404. /**
  1405. * Adds onended/oninactive handler to a MediaStream.
  1406. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1407. * @param handler the handler
  1408. */
  1409. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1410. if(RTCBrowserType.isTemasysPluginUsed()) {
  1411. // themasys
  1412. //FIXME: Seems that not working properly.
  1413. if(mediaStream.onended) {
  1414. mediaStream.onended = handler;
  1415. } else if(mediaStream.addEventListener) {
  1416. mediaStream.addEventListener('ended', function () {
  1417. handler(mediaStream);
  1418. });
  1419. } else if(mediaStream.attachEvent) {
  1420. mediaStream.attachEvent('ended', function () {
  1421. handler(mediaStream);
  1422. });
  1423. }
  1424. }
  1425. else {
  1426. if(typeof mediaStream.active !== "undefined")
  1427. mediaStream.oninactive = handler;
  1428. else
  1429. mediaStream.onended = handler;
  1430. }
  1431. }
  1432. /**
  1433. * Represents a single media track (either audio or video).
  1434. * @constructor
  1435. * @param rtc the rtc instance
  1436. * @param stream the stream
  1437. * @param streamInactiveHandler the function that will handle
  1438. * onended/oninactive events of the stream.
  1439. */
  1440. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1441. {
  1442. /**
  1443. * Array with the HTML elements that are displaying the streams.
  1444. * @type {Array}
  1445. */
  1446. this.containers = [];
  1447. this.rtc = rtc;
  1448. this.stream = stream;
  1449. this.eventEmitter = new EventEmitter();
  1450. this.audioLevel = -1;
  1451. this.type = (this.stream.getVideoTracks().length > 0)?
  1452. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1453. if(this.type == "audio") {
  1454. this._getTracks = function () {
  1455. return this.stream.getAudioTracks();
  1456. }.bind(this);
  1457. } else {
  1458. this._getTracks = function () {
  1459. return this.stream.getVideoTracks();
  1460. }.bind(this);
  1461. }
  1462. if (RTCBrowserType.isFirefox() && this.stream) {
  1463. implementOnEndedHandling(this);
  1464. }
  1465. if(stream)
  1466. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1467. }
  1468. /**
  1469. * JitsiTrack video type.
  1470. * @type {string}
  1471. */
  1472. JitsiTrack.VIDEO = "video";
  1473. /**
  1474. * JitsiTrack audio type.
  1475. * @type {string}
  1476. */
  1477. JitsiTrack.AUDIO = "audio";
  1478. /**
  1479. * Returns the type (audio or video) of this track.
  1480. */
  1481. JitsiTrack.prototype.getType = function() {
  1482. return this.type;
  1483. };
  1484. /**
  1485. * Check if this is audiotrack.
  1486. */
  1487. JitsiTrack.prototype.isAudioTrack = function () {
  1488. return this.getType() === JitsiTrack.AUDIO;
  1489. };
  1490. /**
  1491. * Check if this is videotrack.
  1492. */
  1493. JitsiTrack.prototype.isVideoTrack = function () {
  1494. return this.getType() === JitsiTrack.VIDEO;
  1495. };
  1496. /**
  1497. * Returns the RTCMediaStream from the browser (?).
  1498. */
  1499. JitsiTrack.prototype.getOriginalStream = function() {
  1500. return this.stream;
  1501. }
  1502. /**
  1503. * Mutes the track.
  1504. */
  1505. JitsiTrack.prototype.mute = function () {
  1506. this._setMute(true);
  1507. }
  1508. /**
  1509. * Unmutes the stream.
  1510. */
  1511. JitsiTrack.prototype.unmute = function () {
  1512. this._setMute(false);
  1513. }
  1514. /**
  1515. * Attaches the MediaStream of this track to an HTML container (?).
  1516. * Adds the container to the list of containers that are displaying the track.
  1517. * @param container the HTML container
  1518. */
  1519. JitsiTrack.prototype.attach = function (container) {
  1520. if(this.stream)
  1521. require("./RTCUtils").attachMediaStream(container, this.stream);
  1522. this.containers.push(container);
  1523. }
  1524. /**
  1525. * Removes the track from the passed HTML container.
  1526. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1527. */
  1528. JitsiTrack.prototype.detach = function (container) {
  1529. for(var i = 0; i < this.containers.length; i++)
  1530. {
  1531. if(this.containers[i].is(container))
  1532. {
  1533. this.containers.splice(i,1);
  1534. }
  1535. if(!container)
  1536. {
  1537. this.containers[i].find(">video").remove();
  1538. }
  1539. }
  1540. if(container)
  1541. $(container).find(">video").remove();
  1542. }
  1543. /**
  1544. * Stops sending the media track. And removes it from the HTML.
  1545. * NOTE: Works for local tracks only.
  1546. */
  1547. JitsiTrack.prototype.stop = function () {
  1548. }
  1549. /**
  1550. * Returns true if this is a video track and the source of the video is a
  1551. * screen capture as opposed to a camera.
  1552. */
  1553. JitsiTrack.prototype.isScreenSharing = function(){
  1554. }
  1555. /**
  1556. * Returns id of the track.
  1557. * @returns {string} id of the track or null if this is fake track.
  1558. */
  1559. JitsiTrack.prototype.getId = function () {
  1560. var tracks = this.stream.getTracks();
  1561. if(!tracks || tracks.length === 0)
  1562. return null;
  1563. return tracks[0].id;
  1564. };
  1565. /**
  1566. * Checks whether the MediaStream is avtive/not ended.
  1567. * When there is no check for active we don't have information and so
  1568. * will return that stream is active (in case of FF).
  1569. * @returns {boolean} whether MediaStream is active.
  1570. */
  1571. JitsiTrack.prototype.isActive = function () {
  1572. if((typeof this.stream.active !== "undefined"))
  1573. return this.stream.active;
  1574. else
  1575. return true;
  1576. };
  1577. /**
  1578. * Attaches a handler for events(For example - "audio level changed".).
  1579. * All possible event are defined in JitsiTrackEvents.
  1580. * @param eventId the event ID.
  1581. * @param handler handler for the event.
  1582. */
  1583. JitsiTrack.prototype.on = function (eventId, handler) {
  1584. if(this.eventEmitter)
  1585. this.eventEmitter.on(eventId, handler);
  1586. }
  1587. /**
  1588. * Removes event listener
  1589. * @param eventId the event ID.
  1590. * @param [handler] optional, the specific handler to unbind
  1591. */
  1592. JitsiTrack.prototype.off = function (eventId, handler) {
  1593. if(this.eventEmitter)
  1594. this.eventEmitter.removeListener(eventId, handler);
  1595. }
  1596. // Common aliases for event emitter
  1597. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  1598. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  1599. /**
  1600. * Sets the audio level for the stream
  1601. * @param audioLevel the new audio level
  1602. */
  1603. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  1604. if(this.audioLevel !== audioLevel) {
  1605. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1606. audioLevel);
  1607. this.audioLevel = audioLevel;
  1608. }
  1609. }
  1610. module.exports = JitsiTrack;
  1611. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":43}],16:[function(require,module,exports){
  1612. /* global APP */
  1613. var EventEmitter = require("events");
  1614. var RTCBrowserType = require("./RTCBrowserType");
  1615. var RTCUtils = require("./RTCUtils.js");
  1616. var JitsiTrack = require("./JitsiTrack");
  1617. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1618. var DataChannels = require("./DataChannels");
  1619. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1620. var DesktopSharingEventTypes
  1621. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1622. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1623. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1624. function createLocalTracks(streams) {
  1625. var newStreams = []
  1626. for (var i = 0; i < streams.length; i++) {
  1627. var localStream = new JitsiLocalTrack(streams[i].stream,
  1628. streams[i].videoType, streams[i].resolution);
  1629. newStreams.push(localStream);
  1630. if (streams[i].isMuted === true)
  1631. localStream.setMute(true);
  1632. }
  1633. return newStreams;
  1634. }
  1635. function RTC(room, options) {
  1636. this.room = room;
  1637. this.localStreams = [];
  1638. //FIXME: we should start removing those streams.
  1639. //FIXME: We should support multiple streams per jid.
  1640. this.remoteStreams = {};
  1641. this.localAudio = null;
  1642. this.localVideo = null;
  1643. this.eventEmitter = new EventEmitter();
  1644. var self = this;
  1645. this.options = options || {};
  1646. room.addPresenceListener("videomuted", function (values, from) {
  1647. if(self.remoteStreams[from]) {
  1648. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1649. }
  1650. });
  1651. room.addPresenceListener("audiomuted", function (values, from) {
  1652. if(self.remoteStreams[from]) {
  1653. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1654. }
  1655. });
  1656. }
  1657. /**
  1658. * Creates the local MediaStreams.
  1659. * @param {Object} [options] optional parameters
  1660. * @param {Array} options.devices the devices that will be requested
  1661. * @param {string} options.resolution resolution constraints
  1662. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1663. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1664. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1665. * @param {string} options.cameraDeviceId
  1666. * @param {string} options.micDeviceId
  1667. * @returns {*} Promise object that will receive the new JitsiTracks
  1668. */
  1669. RTC.obtainAudioAndVideoPermissions = function (options) {
  1670. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  1671. }
  1672. RTC.prototype.onIncommingCall = function(event) {
  1673. if(this.options.config.openSctp)
  1674. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1675. for(var i = 0; i < this.localStreams.length; i++)
  1676. if(this.localStreams[i])
  1677. {
  1678. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1679. }
  1680. }
  1681. RTC.prototype.selectedEndpoint = function (id) {
  1682. if(this.dataChannels)
  1683. this.dataChannels.handleSelectedEndpointEvent(id);
  1684. }
  1685. RTC.prototype.pinEndpoint = function (id) {
  1686. if(this.dataChannels)
  1687. this.dataChannels.handlePinnedEndpointEvent(id);
  1688. }
  1689. RTC.prototype.addListener = function (type, listener) {
  1690. this.eventEmitter.on(type, listener);
  1691. };
  1692. RTC.prototype.removeListener = function (eventType, listener) {
  1693. this.eventEmitter.removeListener(eventType, listener);
  1694. };
  1695. RTC.addListener = function (eventType, listener) {
  1696. RTCUtils.addListener(eventType, listener);
  1697. }
  1698. RTC.removeListener = function (eventType, listener) {
  1699. RTCUtils.removeListener(eventType, listener)
  1700. }
  1701. RTC.isRTCReady = function () {
  1702. return RTCUtils.isRTCReady();
  1703. }
  1704. RTC.init = function (options) {
  1705. this.options = options || {};
  1706. return RTCUtils.init(this.options);
  1707. }
  1708. RTC.getDeviceAvailability = function () {
  1709. return RTCUtils.getDeviceAvailability();
  1710. }
  1711. RTC.prototype.addLocalStream = function (stream) {
  1712. this.localStreams.push(stream);
  1713. stream._setRTC(this);
  1714. if (stream.type == "audio") {
  1715. this.localAudio = stream;
  1716. } else {
  1717. this.localVideo = stream;
  1718. }
  1719. };
  1720. RTC.prototype.removeLocalStream = function (stream) {
  1721. for(var i = 0; i < this.localStreams.length; i++) {
  1722. if(this.localStreams[i].getOriginalStream() === stream) {
  1723. delete this.localStreams[i];
  1724. return;
  1725. }
  1726. }
  1727. };
  1728. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1729. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  1730. if(!data.peerjid)
  1731. return;
  1732. var jid = data.peerjid;
  1733. if(!this.remoteStreams[jid]) {
  1734. this.remoteStreams[jid] = {};
  1735. }
  1736. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1737. return remoteStream;
  1738. };
  1739. RTC.getPCConstraints = function () {
  1740. return RTCUtils.pc_constraints;
  1741. };
  1742. RTC.attachMediaStream = function (elSelector, stream) {
  1743. RTCUtils.attachMediaStream(elSelector, stream);
  1744. };
  1745. RTC.getStreamID = function (stream) {
  1746. return RTCUtils.getStreamID(stream);
  1747. };
  1748. RTC.getVideoSrc = function (element) {
  1749. return RTCUtils.getVideoSrc(element);
  1750. };
  1751. RTC.isDeviceListAvailable = function () {
  1752. return RTCUtils.isDeviceListAvailable();
  1753. };
  1754. /**
  1755. * Allows to receive list of available cameras/microphones.
  1756. * @param {function} callback would receive array of devices as an argument
  1757. */
  1758. RTC.enumerateDevices = function (callback) {
  1759. RTCUtils.enumerateDevices(callback);
  1760. };
  1761. RTC.setVideoSrc = function (element, src) {
  1762. RTCUtils.setVideoSrc(element, src);
  1763. };
  1764. /**
  1765. * A method to handle stopping of the stream.
  1766. * One point to handle the differences in various implementations.
  1767. * @param mediaStream MediaStream object to stop.
  1768. */
  1769. RTC.stopMediaStream = function (mediaStream) {
  1770. RTCUtils.stopMediaStream(mediaStream);
  1771. };
  1772. RTC.prototype.getVideoElementName = function () {
  1773. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1774. };
  1775. RTC.prototype.dispose = function() {
  1776. };
  1777. RTC.prototype.switchVideoStreams = function (newStream) {
  1778. this.localVideo.stream = newStream;
  1779. this.localStreams = [];
  1780. //in firefox we have only one stream object
  1781. if (this.localAudio.getOriginalStream() != newStream)
  1782. this.localStreams.push(this.localAudio);
  1783. this.localStreams.push(this.localVideo);
  1784. };
  1785. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  1786. if(this.remoteStreams[jid] && this.remoteStreams[jid][JitsiTrack.AUDIO])
  1787. this.remoteStreams[jid][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  1788. }
  1789. module.exports = RTC;
  1790. },{"../../service/RTC/MediaStreamTypes":78,"../../service/RTC/RTCEvents.js":79,"../../service/desktopsharing/DesktopSharingEventTypes":82,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":43}],17:[function(require,module,exports){
  1791. var currentBrowser;
  1792. var browserVersion;
  1793. var isAndroid;
  1794. var RTCBrowserType = {
  1795. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1796. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1797. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1798. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1799. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1800. getBrowserType: function () {
  1801. return currentBrowser;
  1802. },
  1803. isChrome: function () {
  1804. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1805. },
  1806. isOpera: function () {
  1807. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1808. },
  1809. isFirefox: function () {
  1810. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1811. },
  1812. isIExplorer: function () {
  1813. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1814. },
  1815. isSafari: function () {
  1816. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1817. },
  1818. isTemasysPluginUsed: function () {
  1819. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1820. },
  1821. getFirefoxVersion: function () {
  1822. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1823. },
  1824. getChromeVersion: function () {
  1825. return RTCBrowserType.isChrome() ? browserVersion : null;
  1826. },
  1827. usesPlanB: function() {
  1828. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1829. RTCBrowserType.isTemasysPluginUsed();
  1830. },
  1831. usesUnifiedPlan: function() {
  1832. return RTCBrowserType.isFirefox();
  1833. },
  1834. /**
  1835. * Whether the browser is running on an android device.
  1836. */
  1837. isAndroid: function() {
  1838. return isAndroid;
  1839. }
  1840. // Add version getters for other browsers when needed
  1841. };
  1842. // detectOpera() must be called before detectChrome() !!!
  1843. // otherwise Opera wil be detected as Chrome
  1844. function detectChrome() {
  1845. if (navigator.webkitGetUserMedia) {
  1846. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1847. var userAgent = navigator.userAgent.toLowerCase();
  1848. // We can assume that user agent is chrome, because it's
  1849. // enforced when 'ext' streaming method is set
  1850. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1851. console.log("This appears to be Chrome, ver: " + ver);
  1852. return ver;
  1853. }
  1854. return null;
  1855. }
  1856. function detectOpera() {
  1857. var userAgent = navigator.userAgent;
  1858. if (userAgent.match(/Opera|OPR/)) {
  1859. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1860. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1861. console.info("This appears to be Opera, ver: " + version);
  1862. return version;
  1863. }
  1864. return null;
  1865. }
  1866. function detectFirefox() {
  1867. if (navigator.mozGetUserMedia) {
  1868. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1869. var version = parseInt(
  1870. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1871. console.log('This appears to be Firefox, ver: ' + version);
  1872. return version;
  1873. }
  1874. return null;
  1875. }
  1876. function detectSafari() {
  1877. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1878. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1879. console.info("This appears to be Safari");
  1880. // FIXME detect Safari version when needed
  1881. return 1;
  1882. }
  1883. return null;
  1884. }
  1885. function detectIE() {
  1886. var version;
  1887. var ua = window.navigator.userAgent;
  1888. var msie = ua.indexOf('MSIE ');
  1889. if (msie > 0) {
  1890. // IE 10 or older => return version number
  1891. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1892. }
  1893. var trident = ua.indexOf('Trident/');
  1894. if (!version && trident > 0) {
  1895. // IE 11 => return version number
  1896. var rv = ua.indexOf('rv:');
  1897. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1898. }
  1899. var edge = ua.indexOf('Edge/');
  1900. if (!version && edge > 0) {
  1901. // IE 12 => return version number
  1902. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1903. }
  1904. if (version) {
  1905. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1906. console.info("This appears to be IExplorer, ver: " + version);
  1907. }
  1908. return version;
  1909. }
  1910. function detectBrowser() {
  1911. var version;
  1912. var detectors = [
  1913. detectOpera,
  1914. detectChrome,
  1915. detectFirefox,
  1916. detectIE,
  1917. detectSafari
  1918. ];
  1919. // Try all browser detectors
  1920. for (var i = 0; i < detectors.length; i++) {
  1921. version = detectors[i]();
  1922. if (version)
  1923. return version;
  1924. }
  1925. console.error("Failed to detect browser type");
  1926. return undefined;
  1927. }
  1928. browserVersion = detectBrowser();
  1929. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1930. module.exports = RTCBrowserType;
  1931. },{}],18:[function(require,module,exports){
  1932. (function (__filename){
  1933. /* global config, require, attachMediaStream, getUserMedia,
  1934. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  1935. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  1936. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  1937. */
  1938. /* jshint -W101 */
  1939. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1940. var RTCBrowserType = require("./RTCBrowserType");
  1941. var Resolutions = require("../../service/RTC/Resolutions");
  1942. var RTCEvents = require("../../service/RTC/RTCEvents");
  1943. var AdapterJS = require("./adapter.screenshare");
  1944. var SDPUtil = require("../xmpp/SDPUtil");
  1945. var EventEmitter = require("events");
  1946. var screenObtainer = require("./ScreenObtainer");
  1947. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  1948. var eventEmitter = new EventEmitter();
  1949. var devices = {
  1950. audio: true,
  1951. video: true
  1952. };
  1953. var rtcReady = false;
  1954. function setResolutionConstraints(constraints, resolution) {
  1955. var isAndroid = RTCBrowserType.isAndroid();
  1956. if (Resolutions[resolution]) {
  1957. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1958. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1959. }
  1960. else if (isAndroid) {
  1961. // FIXME can't remember if the purpose of this was to always request
  1962. // low resolution on Android ? if yes it should be moved up front
  1963. constraints.video.mandatory.minWidth = 320;
  1964. constraints.video.mandatory.minHeight = 240;
  1965. constraints.video.mandatory.maxFrameRate = 15;
  1966. }
  1967. if (constraints.video.mandatory.minWidth)
  1968. constraints.video.mandatory.maxWidth =
  1969. constraints.video.mandatory.minWidth;
  1970. if (constraints.video.mandatory.minHeight)
  1971. constraints.video.mandatory.maxHeight =
  1972. constraints.video.mandatory.minHeight;
  1973. }
  1974. /**
  1975. * @param {string[]} um required user media types
  1976. *
  1977. * @param {Object} [options={}] optional parameters
  1978. * @param {string} options.resolution
  1979. * @param {number} options.bandwidth
  1980. * @param {number} options.fps
  1981. * @param {string} options.desktopStream
  1982. * @param {string} options.cameraDeviceId
  1983. * @param {string} options.micDeviceId
  1984. * @param {bool} firefox_fake_device
  1985. */
  1986. function getConstraints(um, options) {
  1987. var constraints = {audio: false, video: false};
  1988. if (um.indexOf('video') >= 0) {
  1989. // same behaviour as true
  1990. constraints.video = { mandatory: {}, optional: [] };
  1991. if (options.cameraDeviceId) {
  1992. constraints.video.optional.push({
  1993. sourceId: options.cameraDeviceId
  1994. });
  1995. }
  1996. constraints.video.optional.push({ googLeakyBucket: true });
  1997. setResolutionConstraints(constraints, options.resolution);
  1998. }
  1999. if (um.indexOf('audio') >= 0) {
  2000. if (!RTCBrowserType.isFirefox()) {
  2001. // same behaviour as true
  2002. constraints.audio = { mandatory: {}, optional: []};
  2003. if (options.micDeviceId) {
  2004. constraints.audio.optional.push({
  2005. sourceId: options.micDeviceId
  2006. });
  2007. }
  2008. // if it is good enough for hangouts...
  2009. constraints.audio.optional.push(
  2010. {googEchoCancellation: true},
  2011. {googAutoGainControl: true},
  2012. {googNoiseSupression: true},
  2013. {googHighpassFilter: true},
  2014. {googNoisesuppression2: true},
  2015. {googEchoCancellation2: true},
  2016. {googAutoGainControl2: true}
  2017. );
  2018. } else {
  2019. if (options.micDeviceId) {
  2020. constraints.audio = {
  2021. mandatory: {},
  2022. optional: [{
  2023. sourceId: options.micDeviceId
  2024. }]};
  2025. } else {
  2026. constraints.audio = true;
  2027. }
  2028. }
  2029. }
  2030. if (um.indexOf('screen') >= 0) {
  2031. if (RTCBrowserType.isChrome()) {
  2032. constraints.video = {
  2033. mandatory: {
  2034. chromeMediaSource: "screen",
  2035. googLeakyBucket: true,
  2036. maxWidth: window.screen.width,
  2037. maxHeight: window.screen.height,
  2038. maxFrameRate: 3
  2039. },
  2040. optional: []
  2041. };
  2042. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2043. constraints.video = {
  2044. optional: [
  2045. {
  2046. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2047. }
  2048. ]
  2049. };
  2050. } else if (RTCBrowserType.isFirefox()) {
  2051. constraints.video = {
  2052. mozMediaSource: "window",
  2053. mediaSource: "window"
  2054. };
  2055. } else {
  2056. logger.error(
  2057. "'screen' WebRTC media source is supported only in Chrome" +
  2058. " and with Temasys plugin");
  2059. }
  2060. }
  2061. if (um.indexOf('desktop') >= 0) {
  2062. constraints.video = {
  2063. mandatory: {
  2064. chromeMediaSource: "desktop",
  2065. chromeMediaSourceId: options.desktopStream,
  2066. googLeakyBucket: true,
  2067. maxWidth: window.screen.width,
  2068. maxHeight: window.screen.height,
  2069. maxFrameRate: 3
  2070. },
  2071. optional: []
  2072. };
  2073. }
  2074. if (options.bandwidth) {
  2075. if (!constraints.video) {
  2076. //same behaviour as true
  2077. constraints.video = {mandatory: {}, optional: []};
  2078. }
  2079. constraints.video.optional.push({bandwidth: options.bandwidth});
  2080. }
  2081. if (options.fps) {
  2082. // for some cameras it might be necessary to request 30fps
  2083. // so they choose 30fps mjpg over 10fps yuy2
  2084. if (!constraints.video) {
  2085. // same behaviour as true;
  2086. constraints.video = {mandatory: {}, optional: []};
  2087. }
  2088. constraints.video.mandatory.minFrameRate = options.fps;
  2089. }
  2090. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2091. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2092. // this later can be a problem with some of the tests
  2093. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2094. {
  2095. // seems to be fixed now, removing this experimental fix, as having
  2096. // multiple audio tracks brake the tests
  2097. //constraints.audio = true;
  2098. constraints.fake = true;
  2099. }
  2100. return constraints;
  2101. }
  2102. function setAvailableDevices(um, available) {
  2103. if (um.indexOf("video") != -1) {
  2104. devices.video = available;
  2105. }
  2106. if (um.indexOf("audio") != -1) {
  2107. devices.audio = available;
  2108. }
  2109. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2110. }
  2111. // In case of IE we continue from 'onReady' callback
  2112. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2113. // once it is initialized.
  2114. function onReady (options, GUM) {
  2115. rtcReady = true;
  2116. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2117. screenObtainer.init(eventEmitter, options, GUM);
  2118. }
  2119. /**
  2120. * Apply function with arguments if function exists.
  2121. * Do nothing if function not provided.
  2122. * @param {function} [fn] function to apply
  2123. * @param {Array} [args=[]] arguments for function
  2124. */
  2125. function maybeApply(fn, args) {
  2126. if (fn) {
  2127. fn.apply(null, args || []);
  2128. }
  2129. }
  2130. var getUserMediaStatus = {
  2131. initialized: false,
  2132. callbacks: []
  2133. };
  2134. /**
  2135. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2136. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2137. * @param {Function} getUserMedia native function
  2138. * @returns {Function} wrapped function
  2139. */
  2140. function wrapGetUserMedia(getUserMedia) {
  2141. return function (constraints, successCallback, errorCallback) {
  2142. getUserMedia(constraints, function (stream) {
  2143. maybeApply(successCallback, [stream]);
  2144. if (!getUserMediaStatus.initialized) {
  2145. getUserMediaStatus.initialized = true;
  2146. getUserMediaStatus.callbacks.forEach(function (callback) {
  2147. callback();
  2148. });
  2149. getUserMediaStatus.callbacks.length = 0;
  2150. }
  2151. }, function (error) {
  2152. maybeApply(errorCallback, [error]);
  2153. });
  2154. };
  2155. }
  2156. /**
  2157. * Create stub device which equals to auto selected device.
  2158. * @param {string} kind if that should be `audio` or `video` device
  2159. * @returns {Object} stub device description in `enumerateDevices` format
  2160. */
  2161. function createAutoDeviceInfo(kind) {
  2162. return {
  2163. facing: null,
  2164. label: 'Auto',
  2165. kind: kind,
  2166. deviceId: '',
  2167. groupId: null
  2168. };
  2169. }
  2170. /**
  2171. * Execute function after getUserMedia was executed at least once.
  2172. * @param {Function} callback function to execute after getUserMedia
  2173. */
  2174. function afterUserMediaInitialized(callback) {
  2175. if (getUserMediaStatus.initialized) {
  2176. callback();
  2177. } else {
  2178. getUserMediaStatus.callbacks.push(callback);
  2179. }
  2180. }
  2181. /**
  2182. * Wrapper function which makes enumerateDevices to wait
  2183. * until someone executes getUserMedia first time.
  2184. * @param {Function} enumerateDevices native function
  2185. * @returns {Funtion} wrapped function
  2186. */
  2187. function wrapEnumerateDevices(enumerateDevices) {
  2188. return function (callback) {
  2189. // enumerate devices only after initial getUserMedia
  2190. afterUserMediaInitialized(function () {
  2191. enumerateDevices().then(function (devices) {
  2192. //add auto devices
  2193. devices.unshift(
  2194. createAutoDeviceInfo('audioinput'),
  2195. createAutoDeviceInfo('videoinput')
  2196. );
  2197. callback(devices);
  2198. }, function (err) {
  2199. console.error('cannot enumerate devices: ', err);
  2200. // return only auto devices
  2201. callback([createAutoDeviceInfo('audioInput'),
  2202. createAutoDeviceInfo('videoinput')]);
  2203. });
  2204. });
  2205. };
  2206. }
  2207. /**
  2208. * Use old MediaStreamTrack to get devices list and
  2209. * convert it to enumerateDevices format.
  2210. * @param {Function} callback function to call when received devices list.
  2211. */
  2212. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2213. MediaStreamTrack.getSources(function (sources) {
  2214. var devices = sources.map(function (source) {
  2215. var kind = (source.kind || '').toLowerCase();
  2216. return {
  2217. facing: source.facing || null,
  2218. label: source.label,
  2219. kind: kind ? kind + 'input': null,
  2220. deviceId: source.id,
  2221. groupId: source.groupId || null
  2222. };
  2223. });
  2224. //add auto devices
  2225. devices.unshift(
  2226. createAutoDeviceInfo('audioinput'),
  2227. createAutoDeviceInfo('videoinput')
  2228. );
  2229. callback(devices);
  2230. });
  2231. }
  2232. function obtainDevices(options) {
  2233. if(!options.devices || options.devices.length === 0) {
  2234. return options.successCallback(options.streams || {});
  2235. }
  2236. var device = options.devices.splice(0, 1);
  2237. options.deviceGUM[device](function (stream) {
  2238. options.streams = options.streams || {};
  2239. options.streams[device] = stream;
  2240. obtainDevices(options);
  2241. },
  2242. function (error) {
  2243. logger.error(
  2244. "failed to obtain " + device + " stream - stop", error);
  2245. options.errorCallback(JitsiTrackErrors.parseError(error));
  2246. });
  2247. }
  2248. /**
  2249. * Handles the newly created Media Streams.
  2250. * @param streams the new Media Streams
  2251. * @param resolution the resolution of the video streams
  2252. * @returns {*[]} object that describes the new streams
  2253. */
  2254. function handleLocalStream(streams, resolution) {
  2255. var audioStream, videoStream, desktopStream, res = [];
  2256. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2257. // an object with two properties: audioStream, videoStream.
  2258. if (window.webkitMediaStream) {
  2259. var audioVideo = streams.audioVideo;
  2260. if (audioVideo) {
  2261. var audioTracks = audioVideo.getAudioTracks();
  2262. if(audioTracks.length) {
  2263. audioStream = new webkitMediaStream();
  2264. for (var i = 0; i < audioTracks.length; i++) {
  2265. audioStream.addTrack(audioTracks[i]);
  2266. }
  2267. }
  2268. var videoTracks = audioVideo.getVideoTracks();
  2269. if(videoTracks.length) {
  2270. videoStream = new webkitMediaStream();
  2271. for (var j = 0; j < videoTracks.length; j++) {
  2272. videoStream.addTrack(videoTracks[j]);
  2273. }
  2274. }
  2275. }
  2276. if (streams && streams.desktopStream)
  2277. desktopStream = streams.desktopStream;
  2278. }
  2279. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2280. if (streams && streams.audio)
  2281. audioStream = streams.audio;
  2282. if (streams && streams.video)
  2283. videoStream = streams.video;
  2284. if(streams && streams.desktop)
  2285. desktopStream = streams.desktop;
  2286. }
  2287. if (desktopStream)
  2288. res.push({stream: desktopStream,
  2289. type: "video", videoType: "desktop"});
  2290. if(audioStream)
  2291. res.push({stream: audioStream, type: "audio", videoType: null});
  2292. if(videoStream)
  2293. res.push({stream: videoStream, type: "video", videoType: "camera",
  2294. resolution: resolution});
  2295. return res;
  2296. }
  2297. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2298. var RTCUtils = {
  2299. init: function (options) {
  2300. return new Promise(function(resolve, reject) {
  2301. if (RTCBrowserType.isFirefox()) {
  2302. var FFversion = RTCBrowserType.getFirefoxVersion();
  2303. if (FFversion < 40) {
  2304. logger.error(
  2305. "Firefox version too old: " + FFversion +
  2306. ". Required >= 40.");
  2307. reject(new Error("Firefox version too old: " + FFversion +
  2308. ". Required >= 40."));
  2309. return;
  2310. }
  2311. this.peerconnection = mozRTCPeerConnection;
  2312. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2313. this.enumerateDevices = wrapEnumerateDevices(
  2314. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2315. );
  2316. this.pc_constraints = {};
  2317. this.attachMediaStream = function (element, stream) {
  2318. // srcObject is being standardized and FF will eventually
  2319. // support that unprefixed. FF also supports the
  2320. // "element.src = URL.createObjectURL(...)" combo, but that
  2321. // will be deprecated in favour of srcObject.
  2322. //
  2323. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2324. // https://github.com/webrtc/samples/issues/302
  2325. if (!element[0])
  2326. return;
  2327. element[0].mozSrcObject = stream;
  2328. element[0].play();
  2329. };
  2330. this.getStreamID = function (stream) {
  2331. var id = stream.id;
  2332. if (!id) {
  2333. var tracks = stream.getVideoTracks();
  2334. if (!tracks || tracks.length === 0) {
  2335. tracks = stream.getAudioTracks();
  2336. }
  2337. id = tracks[0].id;
  2338. }
  2339. return SDPUtil.filter_special_chars(id);
  2340. };
  2341. this.getVideoSrc = function (element) {
  2342. if (!element)
  2343. return null;
  2344. return element.mozSrcObject;
  2345. };
  2346. this.setVideoSrc = function (element, src) {
  2347. if (element)
  2348. element.mozSrcObject = src;
  2349. };
  2350. RTCSessionDescription = mozRTCSessionDescription;
  2351. RTCIceCandidate = mozRTCIceCandidate;
  2352. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2353. this.peerconnection = webkitRTCPeerConnection;
  2354. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2355. if (navigator.mediaDevices) {
  2356. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2357. this.enumerateDevices = wrapEnumerateDevices(
  2358. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2359. );
  2360. } else {
  2361. this.getUserMedia = getUserMedia;
  2362. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2363. }
  2364. this.attachMediaStream = function (element, stream) {
  2365. element.attr('src', webkitURL.createObjectURL(stream));
  2366. };
  2367. this.getStreamID = function (stream) {
  2368. // streams from FF endpoints have the characters '{' and '}'
  2369. // that make jQuery choke.
  2370. return SDPUtil.filter_special_chars(stream.id);
  2371. };
  2372. this.getVideoSrc = function (element) {
  2373. if (!element)
  2374. return null;
  2375. return element.getAttribute("src");
  2376. };
  2377. this.setVideoSrc = function (element, src) {
  2378. if (element)
  2379. element.setAttribute("src", src);
  2380. };
  2381. // DTLS should now be enabled by default but..
  2382. this.pc_constraints = {'optional': [
  2383. {'DtlsSrtpKeyAgreement': 'true'}
  2384. ]};
  2385. if (options.useIPv6) {
  2386. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2387. this.pc_constraints.optional.push({googIPv6: true});
  2388. }
  2389. if (RTCBrowserType.isAndroid()) {
  2390. this.pc_constraints = {}; // disable DTLS on Android
  2391. }
  2392. if (!webkitMediaStream.prototype.getVideoTracks) {
  2393. webkitMediaStream.prototype.getVideoTracks = function () {
  2394. return this.videoTracks;
  2395. };
  2396. }
  2397. if (!webkitMediaStream.prototype.getAudioTracks) {
  2398. webkitMediaStream.prototype.getAudioTracks = function () {
  2399. return this.audioTracks;
  2400. };
  2401. }
  2402. }
  2403. // Detect IE/Safari
  2404. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2405. //AdapterJS.WebRTCPlugin.setLogLevel(
  2406. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2407. var self = this;
  2408. AdapterJS.webRTCReady(function (isPlugin) {
  2409. self.peerconnection = RTCPeerConnection;
  2410. self.getUserMedia = window.getUserMedia;
  2411. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2412. self.attachMediaStream = function (elSel, stream) {
  2413. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2414. return;
  2415. }
  2416. attachMediaStream(elSel[0], stream);
  2417. };
  2418. self.getStreamID = function (stream) {
  2419. var id = SDPUtil.filter_special_chars(stream.label);
  2420. return id;
  2421. };
  2422. self.getVideoSrc = function (element) {
  2423. if (!element) {
  2424. logger.warn("Attempt to get video SRC of null element");
  2425. return null;
  2426. }
  2427. var children = element.children;
  2428. for (var i = 0; i !== children.length; ++i) {
  2429. if (children[i].name === 'streamId') {
  2430. return children[i].value;
  2431. }
  2432. }
  2433. //logger.info(element.id + " SRC: " + src);
  2434. return null;
  2435. };
  2436. self.setVideoSrc = function (element, src) {
  2437. //logger.info("Set video src: ", element, src);
  2438. if (!src) {
  2439. logger.warn("Not attaching video stream, 'src' is null");
  2440. return;
  2441. }
  2442. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2443. var stream = AdapterJS.WebRTCPlugin.plugin
  2444. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2445. attachMediaStream(element, stream);
  2446. };
  2447. onReady(options, self.getUserMediaWithConstraints);
  2448. resolve();
  2449. });
  2450. } else {
  2451. try {
  2452. logger.error('Browser does not appear to be WebRTC-capable');
  2453. } catch (e) {
  2454. }
  2455. reject('Browser does not appear to be WebRTC-capable');
  2456. return;
  2457. }
  2458. // Call onReady() if Temasys plugin is not used
  2459. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2460. onReady(options, this.getUserMediaWithConstraints);
  2461. resolve();
  2462. }
  2463. }.bind(this));
  2464. },
  2465. /**
  2466. * @param {string[]} um required user media types
  2467. * @param {function} success_callback
  2468. * @param {Function} failure_callback
  2469. * @param {Object} [options] optional parameters
  2470. * @param {string} options.resolution
  2471. * @param {number} options.bandwidth
  2472. * @param {number} options.fps
  2473. * @param {string} options.desktopStream
  2474. * @param {string} options.cameraDeviceId
  2475. * @param {string} options.micDeviceId
  2476. **/
  2477. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2478. options = options || {};
  2479. var resolution = options.resolution;
  2480. var constraints = getConstraints(um, options);
  2481. logger.info("Get media constraints", constraints);
  2482. try {
  2483. this.getUserMedia(constraints,
  2484. function (stream) {
  2485. logger.log('onUserMediaSuccess');
  2486. setAvailableDevices(um, true);
  2487. success_callback(stream);
  2488. },
  2489. function (error) {
  2490. setAvailableDevices(um, false);
  2491. logger.warn('Failed to get access to local media. Error ',
  2492. error, constraints);
  2493. if (failure_callback) {
  2494. failure_callback(error, resolution);
  2495. }
  2496. });
  2497. } catch (e) {
  2498. logger.error('GUM failed: ', e);
  2499. if (failure_callback) {
  2500. failure_callback(e);
  2501. }
  2502. }
  2503. },
  2504. /**
  2505. * Creates the local MediaStreams.
  2506. * @param {Object} [options] optional parameters
  2507. * @param {Array} options.devices the devices that will be requested
  2508. * @param {string} options.resolution resolution constraints
  2509. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2510. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2511. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2512. * @param {string} options.cameraDeviceId
  2513. * @param {string} options.micDeviceId
  2514. * @returns {*} Promise object that will receive the new JitsiTracks
  2515. */
  2516. obtainAudioAndVideoPermissions: function (options) {
  2517. var self = this;
  2518. options = options || {};
  2519. return new Promise(function (resolve, reject) {
  2520. var successCallback = function (stream) {
  2521. resolve(handleLocalStream(stream, options.resolution));
  2522. };
  2523. options.devices = options.devices || ['audio', 'video'];
  2524. if(!screenObtainer.isSupported()
  2525. && options.devices.indexOf("desktop") !== -1){
  2526. reject(new Error("Desktop sharing is not supported!"));
  2527. }
  2528. if (RTCBrowserType.isFirefox() ||
  2529. RTCBrowserType.isTemasysPluginUsed()) {
  2530. var GUM = function (device, s, e) {
  2531. this.getUserMediaWithConstraints(device, s, e, options);
  2532. };
  2533. var deviceGUM = {
  2534. "audio": GUM.bind(self, ["audio"]),
  2535. "video": GUM.bind(self, ["video"]),
  2536. "desktop": screenObtainer.obtainStream
  2537. };
  2538. // With FF/IE we can't split the stream into audio and video because FF
  2539. // doesn't support media stream constructors. So, we need to get the
  2540. // audio stream separately from the video stream using two distinct GUM
  2541. // calls. Not very user friendly :-( but we don't have many other
  2542. // options neither.
  2543. //
  2544. // Note that we pack those 2 streams in a single object and pass it to
  2545. // the successCallback method.
  2546. obtainDevices({
  2547. devices: options.devices,
  2548. streams: [],
  2549. successCallback: successCallback,
  2550. errorCallback: reject,
  2551. deviceGUM: deviceGUM
  2552. });
  2553. } else {
  2554. var hasDesktop = options.devices.indexOf('desktop') > -1;
  2555. if (hasDesktop) {
  2556. options.devices.splice(options.devices.indexOf("desktop"), 1);
  2557. }
  2558. options.resolution = options.resolution || '360';
  2559. if(options.devices.length) {
  2560. this.getUserMediaWithConstraints(
  2561. options.devices,
  2562. function (stream) {
  2563. if(hasDesktop) {
  2564. screenObtainer.obtainStream(
  2565. function (desktopStream) {
  2566. successCallback({audioVideo: stream,
  2567. desktopStream: desktopStream});
  2568. }, function (error) {
  2569. reject(
  2570. JitsiTrackErrors.parseError(error));
  2571. });
  2572. } else {
  2573. successCallback({audioVideo: stream});
  2574. }
  2575. },
  2576. function (error) {
  2577. reject(JitsiTrackErrors.parseError(error));
  2578. },
  2579. options);
  2580. } else if (hasDesktop) {
  2581. screenObtainer.obtainStream(
  2582. function (stream) {
  2583. successCallback({desktopStream: stream});
  2584. }, function (error) {
  2585. reject(
  2586. JitsiTrackErrors.parseError(error));
  2587. });
  2588. }
  2589. }
  2590. }.bind(this));
  2591. },
  2592. addListener: function (eventType, listener) {
  2593. eventEmitter.on(eventType, listener);
  2594. },
  2595. removeListener: function (eventType, listener) {
  2596. eventEmitter.removeListener(eventType, listener);
  2597. },
  2598. getDeviceAvailability: function () {
  2599. return devices;
  2600. },
  2601. isRTCReady: function () {
  2602. return rtcReady;
  2603. },
  2604. /**
  2605. * Checks if its possible to enumerate available cameras/micropones.
  2606. * @returns {boolean} true if available, false otherwise.
  2607. */
  2608. isDeviceListAvailable: function () {
  2609. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2610. if (isEnumerateDevicesAvailable) {
  2611. return true;
  2612. }
  2613. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2614. },
  2615. /**
  2616. * A method to handle stopping of the stream.
  2617. * One point to handle the differences in various implementations.
  2618. * @param mediaStream MediaStream object to stop.
  2619. */
  2620. stopMediaStream: function (mediaStream) {
  2621. mediaStream.getTracks().forEach(function (track) {
  2622. // stop() not supported with IE
  2623. if (track.stop) {
  2624. track.stop();
  2625. }
  2626. });
  2627. // leave stop for implementation still using it
  2628. if (mediaStream.stop) {
  2629. mediaStream.stop();
  2630. }
  2631. }
  2632. };
  2633. module.exports = RTCUtils;
  2634. }).call(this,"/modules/RTC/RTCUtils.js")
  2635. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":79,"../../service/RTC/Resolutions":80,"../xmpp/SDPUtil":32,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":43,"jitsi-meet-logger":47}],19:[function(require,module,exports){
  2636. (function (__filename){
  2637. /* global chrome, $, alert */
  2638. /* jshint -W003 */
  2639. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2640. var RTCBrowserType = require("./RTCBrowserType");
  2641. var AdapterJS = require("./adapter.screenshare");
  2642. var DesktopSharingEventTypes
  2643. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2644. /**
  2645. * Indicates whether the Chrome desktop sharing extension is installed.
  2646. * @type {boolean}
  2647. */
  2648. var chromeExtInstalled = false;
  2649. /**
  2650. * Indicates whether an update of the Chrome desktop sharing extension is
  2651. * required.
  2652. * @type {boolean}
  2653. */
  2654. var chromeExtUpdateRequired = false;
  2655. /**
  2656. * Whether the jidesha extension for firefox is installed for the domain on
  2657. * which we are running. Null designates an unknown value.
  2658. * @type {null}
  2659. */
  2660. var firefoxExtInstalled = null;
  2661. /**
  2662. * If set to true, detection of an installed firefox extension will be started
  2663. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  2664. * user tries to enable screen sharing).
  2665. */
  2666. var reDetectFirefoxExtension = false;
  2667. var GUM = null;
  2668. /**
  2669. * Handles obtaining a stream from a screen capture on different browsers.
  2670. */
  2671. var ScreenObtainer = {
  2672. /**
  2673. * The EventEmitter to use to emit events.
  2674. * @type {null}
  2675. */
  2676. eventEmitter: null,
  2677. obtainStream: null,
  2678. /**
  2679. * Initializes the function used to obtain a screen capture
  2680. * (this.obtainStream).
  2681. *
  2682. * If the browser is Chrome, it uses the value of
  2683. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  2684. * decide whether to use the a Chrome extension (if the value is 'ext'),
  2685. * use the "screen" media source (if the value is 'webrtc'),
  2686. * or disable screen capture (if the value is other).
  2687. * Note that for the "screen" media source to work the
  2688. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  2689. */
  2690. init: function(eventEmitter, options, gum) {
  2691. this.eventEmitter = eventEmitter;
  2692. var obtainDesktopStream = null;
  2693. this.options = options = options || {};
  2694. GUM = gum;
  2695. if (RTCBrowserType.isFirefox())
  2696. initFirefoxExtensionDetection(options);
  2697. // TODO remove this, options.desktopSharing is deprecated.
  2698. var chromeMethod =
  2699. (options.desktopSharingChromeMethod || options.desktopSharing);
  2700. if (RTCBrowserType.isTemasysPluginUsed()) {
  2701. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  2702. logger.info("Screensharing not supported by this plugin " +
  2703. "version");
  2704. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2705. logger.info(
  2706. "Screensharing not available with Temasys plugin on" +
  2707. " this site");
  2708. } else {
  2709. obtainDesktopStream = obtainWebRTCScreen;
  2710. logger.info("Using Temasys plugin for desktop sharing");
  2711. }
  2712. } else if (RTCBrowserType.isChrome()) {
  2713. if (chromeMethod == "ext") {
  2714. if (RTCBrowserType.getChromeVersion() >= 34) {
  2715. obtainDesktopStream =
  2716. this.obtainScreenFromExtension;
  2717. logger.info("Using Chrome extension for desktop sharing");
  2718. initChromeExtension(options);
  2719. } else {
  2720. logger.info("Chrome extension not supported until ver 34");
  2721. }
  2722. } else if (chromeMethod == "webrtc") {
  2723. obtainDesktopStream = obtainWebRTCScreen;
  2724. logger.info("Using Chrome WebRTC for desktop sharing");
  2725. }
  2726. } else if (RTCBrowserType.isFirefox()) {
  2727. if (options.desktopSharingFirefoxDisabled) {
  2728. obtainDesktopStream = null;
  2729. } else if (window.location.protocol === "http:"){
  2730. logger.log("Screen sharing is not supported over HTTP. " +
  2731. "Use of HTTPS is required.");
  2732. obtainDesktopStream = null;
  2733. } else {
  2734. obtainDesktopStream = this.obtainScreenOnFirefox;
  2735. }
  2736. }
  2737. if (!obtainDesktopStream) {
  2738. logger.info("Desktop sharing disabled");
  2739. }
  2740. this.obtainStream = obtainDesktopStream;
  2741. },
  2742. /**
  2743. * Checks whether obtaining a screen capture is supported in the current
  2744. * environment.
  2745. * @returns {boolean}
  2746. */
  2747. isSupported: function() {
  2748. return !!this.obtainStream;
  2749. },
  2750. /**
  2751. * Obtains a screen capture stream on Firefox.
  2752. * @param callback
  2753. * @param errorCallback
  2754. */
  2755. obtainScreenOnFirefox:
  2756. function (callback, errorCallback) {
  2757. var self = this;
  2758. var extensionRequired = false;
  2759. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  2760. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  2761. RTCBrowserType.getFirefoxVersion() <=
  2762. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  2763. extensionRequired = true;
  2764. logger.log("Jidesha extension required on firefox version " +
  2765. RTCBrowserType.getFirefoxVersion());
  2766. }
  2767. if (!extensionRequired || firefoxExtInstalled === true) {
  2768. obtainWebRTCScreen(callback, errorCallback);
  2769. return;
  2770. }
  2771. if (reDetectFirefoxExtension) {
  2772. reDetectFirefoxExtension = false;
  2773. initFirefoxExtensionDetection(this.options);
  2774. }
  2775. // Give it some (more) time to initialize, and assume lack of
  2776. // extension if it hasn't.
  2777. if (firefoxExtInstalled === null) {
  2778. window.setTimeout(
  2779. function() {
  2780. if (firefoxExtInstalled === null)
  2781. firefoxExtInstalled = false;
  2782. self.obtainScreenOnFirefox(callback, errorCallback);
  2783. },
  2784. 300
  2785. );
  2786. logger.log("Waiting for detection of jidesha on firefox to " +
  2787. "finish.");
  2788. return;
  2789. }
  2790. // We need an extension and it isn't installed.
  2791. // Make sure we check for the extension when the user clicks again.
  2792. firefoxExtInstalled = null;
  2793. reDetectFirefoxExtension = true;
  2794. // Prompt the user to install the extension
  2795. this.eventEmitter.emit(
  2796. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  2797. this.options.desktopSharingFirefoxExtensionURL);
  2798. // Make sure desktopsharing knows that we failed, so that it doesn't get
  2799. // stuck in 'switching' mode.
  2800. errorCallback('Firefox extension required.');
  2801. },
  2802. /**
  2803. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  2804. * 'desktop' stream for returned stream token.
  2805. */
  2806. obtainScreenFromExtension: function (streamCallback, failCallback) {
  2807. if (chromeExtInstalled) {
  2808. doGetStreamFromExtension(this.options, streamCallback,
  2809. failCallback);
  2810. } else {
  2811. if (chromeExtUpdateRequired) {
  2812. alert(
  2813. 'Jitsi Desktop Streamer requires update. ' +
  2814. 'Changes will take effect after next Chrome restart.');
  2815. }
  2816. chrome.webstore.install(
  2817. getWebStoreInstallUrl(this.options),
  2818. function (arg) {
  2819. logger.log("Extension installed successfully", arg);
  2820. chromeExtInstalled = true;
  2821. // We need to give a moment for the endpoint to become
  2822. // available
  2823. window.setTimeout(function () {
  2824. doGetStreamFromExtension(this.options, streamCallback,
  2825. failCallback);
  2826. }, 500);
  2827. },
  2828. function (arg) {
  2829. logger.log("Failed to install the extension", arg);
  2830. failCallback(arg);
  2831. }
  2832. );
  2833. }
  2834. }
  2835. };
  2836. /**
  2837. * Obtains a desktop stream using getUserMedia.
  2838. * For this to work on Chrome, the
  2839. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  2840. *
  2841. * On firefox, the document's domain must be white-listed in the
  2842. * 'media.getusermedia.screensharing.allowed_domains' preference in
  2843. * 'about:config'.
  2844. */
  2845. function obtainWebRTCScreen(streamCallback, failCallback) {
  2846. GUM(
  2847. ['screen'],
  2848. streamCallback,
  2849. failCallback
  2850. );
  2851. }
  2852. /**
  2853. * Constructs inline install URL for Chrome desktop streaming extension.
  2854. * The 'chromeExtensionId' must be defined in options parameter.
  2855. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  2856. * @returns {string}
  2857. */
  2858. function getWebStoreInstallUrl(options)
  2859. {
  2860. //TODO remove chromeExtensionId (deprecated)
  2861. return "https://chrome.google.com/webstore/detail/" +
  2862. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  2863. }
  2864. /**
  2865. * Checks whether an update of the Chrome extension is required.
  2866. * @param minVersion minimal required version
  2867. * @param extVersion current extension version
  2868. * @returns {boolean}
  2869. */
  2870. function isUpdateRequired(minVersion, extVersion) {
  2871. try {
  2872. var s1 = minVersion.split('.');
  2873. var s2 = extVersion.split('.');
  2874. var len = Math.max(s1.length, s2.length);
  2875. for (var i = 0; i < len; i++) {
  2876. var n1 = 0,
  2877. n2 = 0;
  2878. if (i < s1.length)
  2879. n1 = parseInt(s1[i]);
  2880. if (i < s2.length)
  2881. n2 = parseInt(s2[i]);
  2882. if (isNaN(n1) || isNaN(n2)) {
  2883. return true;
  2884. } else if (n1 !== n2) {
  2885. return n1 > n2;
  2886. }
  2887. }
  2888. // will happen if both versions have identical numbers in
  2889. // their components (even if one of them is longer, has more components)
  2890. return false;
  2891. }
  2892. catch (e) {
  2893. logger.error("Failed to parse extension version", e);
  2894. return true;
  2895. }
  2896. }
  2897. function checkChromeExtInstalled(callback, options) {
  2898. if (!chrome || !chrome.runtime) {
  2899. // No API, so no extension for sure
  2900. callback(false, false);
  2901. return;
  2902. }
  2903. chrome.runtime.sendMessage(
  2904. //TODO: remove chromeExtensionId (deprecated)
  2905. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  2906. { getVersion: true },
  2907. function (response) {
  2908. if (!response || !response.version) {
  2909. // Communication failure - assume that no endpoint exists
  2910. logger.warn(
  2911. "Extension not installed?: ", chrome.runtime.lastError);
  2912. callback(false, false);
  2913. return;
  2914. }
  2915. // Check installed extension version
  2916. var extVersion = response.version;
  2917. logger.log('Extension version is: ' + extVersion);
  2918. //TODO: remove minChromeExtVersion (deprecated)
  2919. var updateRequired
  2920. = isUpdateRequired(
  2921. (options.desktopSharingChromeMinExtVersion ||
  2922. options.minChromeExtVersion),
  2923. extVersion);
  2924. callback(!updateRequired, updateRequired);
  2925. }
  2926. );
  2927. }
  2928. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  2929. // Sends 'getStream' msg to the extension.
  2930. // Extension id must be defined in the config.
  2931. chrome.runtime.sendMessage(
  2932. //TODO: remove chromeExtensionId (deprecated)
  2933. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  2934. {
  2935. getStream: true,
  2936. //TODO: remove desktopSharingSources (deprecated).
  2937. sources: (options.desktopSharingChromeSources ||
  2938. options.desktopSharingSources)
  2939. },
  2940. function (response) {
  2941. if (!response) {
  2942. failCallback(chrome.runtime.lastError);
  2943. return;
  2944. }
  2945. logger.log("Response from extension: " + response);
  2946. if (response.streamId) {
  2947. GUM(
  2948. ['desktop'],
  2949. function (stream) {
  2950. streamCallback(stream);
  2951. },
  2952. failCallback,
  2953. {desktopStream: response.streamId});
  2954. } else {
  2955. failCallback("Extension failed to get the stream");
  2956. }
  2957. }
  2958. );
  2959. }
  2960. /**
  2961. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  2962. * config.js to support inline installs. Host site must be selected as main
  2963. * website of published extension.
  2964. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  2965. */
  2966. function initInlineInstalls(options)
  2967. {
  2968. $("link[rel=chrome-webstore-item]").attr("href",
  2969. getWebStoreInstallUrl(options));
  2970. }
  2971. function initChromeExtension(options) {
  2972. // Initialize Chrome extension inline installs
  2973. initInlineInstalls(options);
  2974. // Check if extension is installed
  2975. checkChromeExtInstalled(function (installed, updateRequired) {
  2976. chromeExtInstalled = installed;
  2977. chromeExtUpdateRequired = updateRequired;
  2978. logger.info(
  2979. "Chrome extension installed: " + chromeExtInstalled +
  2980. " updateRequired: " + chromeExtUpdateRequired);
  2981. }, options);
  2982. }
  2983. /**
  2984. * Starts the detection of an installed jidesha extension for firefox.
  2985. * @param options supports "desktopSharingFirefoxDisabled",
  2986. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  2987. */
  2988. function initFirefoxExtensionDetection(options) {
  2989. if (options.desktopSharingFirefoxDisabled) {
  2990. return;
  2991. }
  2992. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  2993. return;
  2994. if (!options.desktopSharingFirefoxExtId) {
  2995. firefoxExtInstalled = false;
  2996. return;
  2997. }
  2998. var img = document.createElement('img');
  2999. img.onload = function(){
  3000. logger.log("Detected firefox screen sharing extension.");
  3001. firefoxExtInstalled = true;
  3002. };
  3003. img.onerror = function(){
  3004. logger.log("Detected lack of firefox screen sharing extension.");
  3005. firefoxExtInstalled = false;
  3006. };
  3007. // The jidesha extension exposes an empty image file under the url:
  3008. // "chrome://EXT_ID/content/DOMAIN.png"
  3009. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3010. // DOMAIN is a domain whitelisted by the extension.
  3011. var src = "chrome://" +
  3012. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3013. "/content/" + document.location.hostname + ".png";
  3014. img.setAttribute('src', src);
  3015. }
  3016. module.exports = ScreenObtainer;
  3017. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3018. },{"../../service/desktopsharing/DesktopSharingEventTypes":82,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":47}],20:[function(require,module,exports){
  3019. (function (__filename){
  3020. /*! adapterjs - v0.12.0 - 2015-09-04 */
  3021. var console = require("jitsi-meet-logger").getLogger(__filename);
  3022. // Adapter's interface.
  3023. var AdapterJS = AdapterJS || {};
  3024. // Browserify compatibility
  3025. if(typeof exports !== 'undefined') {
  3026. module.exports = AdapterJS;
  3027. }
  3028. AdapterJS.options = AdapterJS.options || {};
  3029. // uncomment to get virtual webcams
  3030. // AdapterJS.options.getAllCams = true;
  3031. // uncomment to prevent the install prompt when the plugin in not yet installed
  3032. // AdapterJS.options.hidePluginInstallPrompt = true;
  3033. // AdapterJS version
  3034. AdapterJS.VERSION = '0.12.0';
  3035. // This function will be called when the WebRTC API is ready to be used
  3036. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3037. // the plugin
  3038. // You may Override this function to synchronise the start of your application
  3039. // with the WebRTC API being ready.
  3040. // If you decide not to override use this synchronisation, it may result in
  3041. // an extensive CPU usage on the plugin start (once per tab loaded)
  3042. // Params:
  3043. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3044. //
  3045. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3046. // The WebRTC API is ready.
  3047. // Override me and do whatever you want here
  3048. };
  3049. // Sets a callback function to be called when the WebRTC interface is ready.
  3050. // The first argument is the function to callback.\
  3051. // Throws an error if the first argument is not a function
  3052. AdapterJS.webRTCReady = function (callback) {
  3053. if (typeof callback !== 'function') {
  3054. throw new Error('Callback provided is not a function');
  3055. }
  3056. if (true === AdapterJS.onwebrtcreadyDone) {
  3057. // All WebRTC interfaces are ready, just call the callback
  3058. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3059. } else {
  3060. // will be triggered automatically when your browser/plugin is ready.
  3061. AdapterJS.onwebrtcready = callback;
  3062. }
  3063. };
  3064. // Plugin namespace
  3065. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3066. // The object to store plugin information
  3067. AdapterJS.WebRTCPlugin.pluginInfo = {
  3068. prefix : 'Tem',
  3069. plugName : 'TemWebRTCPlugin',
  3070. pluginId : 'plugin0',
  3071. type : 'application/x-temwebrtcplugin',
  3072. onload : '__TemWebRTCReady0',
  3073. portalLink : 'http://skylink.io/plugin/',
  3074. downloadLink : null, //set below
  3075. companyName: 'Temasys'
  3076. };
  3077. if(!!navigator.platform.match(/^Mac/i)) {
  3078. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3079. }
  3080. else if(!!navigator.platform.match(/^Win/i)) {
  3081. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3082. }
  3083. AdapterJS.WebRTCPlugin.TAGS = {
  3084. NONE : 'none',
  3085. AUDIO : 'audio',
  3086. VIDEO : 'video'
  3087. };
  3088. // Unique identifier of each opened page
  3089. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3090. // Use this whenever you want to call the plugin.
  3091. AdapterJS.WebRTCPlugin.plugin = null;
  3092. // Set log level for the plugin once it is ready.
  3093. // The different values are
  3094. // This is an asynchronous function that will run when the plugin is ready
  3095. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3096. // Defines webrtc's JS interface according to the plugin's implementation.
  3097. // Define plugin Browsers as WebRTC Interface.
  3098. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3099. // This function detects whether or not a plugin is installed.
  3100. // Checks if Not IE (firefox, for example), else if it's IE,
  3101. // we're running IE and do something. If not it is not supported.
  3102. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3103. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3104. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3105. // Inject the HTML DOM object element into the page.
  3106. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3107. // States of readiness that the plugin goes through when
  3108. // being injected and stated
  3109. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3110. NONE : 0, // no plugin use
  3111. INITIALIZING : 1, // Detected need for plugin
  3112. INJECTING : 2, // Injecting plugin
  3113. INJECTED: 3, // Plugin element injected but not usable yet
  3114. READY: 4 // Plugin ready to be used
  3115. };
  3116. // Current state of the plugin. You cannot use the plugin before this is
  3117. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3118. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3119. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3120. // Used to make sure AdapterJS.onwebrtcready is only called once
  3121. AdapterJS.onwebrtcreadyDone = false;
  3122. // Log levels for the plugin.
  3123. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3124. /*
  3125. Log outputs are prefixed in some cases.
  3126. INFO: Information reported by the plugin.
  3127. ERROR: Errors originating from within the plugin.
  3128. WEBRTC: Error originating from within the libWebRTC library
  3129. */
  3130. // From the least verbose to the most verbose
  3131. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3132. NONE : 'NONE',
  3133. ERROR : 'ERROR',
  3134. WARNING : 'WARNING',
  3135. INFO: 'INFO',
  3136. VERBOSE: 'VERBOSE',
  3137. SENSITIVE: 'SENSITIVE'
  3138. };
  3139. // Does a waiting check before proceeding to load the plugin.
  3140. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3141. // This methid will use an interval to wait for the plugin to be ready.
  3142. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3143. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3144. // This function will be called when plugin is ready. It sends necessary
  3145. // details to the plugin.
  3146. // The function will wait for the document to be ready and the set the
  3147. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3148. // indicating that it can start being requested.
  3149. // This function is not in the IE/Safari condition brackets so that
  3150. // TemPluginLoaded function might be called on Chrome/Firefox.
  3151. // This function is the only private function that is not encapsulated to
  3152. // allow the plugin method to be called.
  3153. __TemWebRTCReady0 = function () {
  3154. if (document.readyState === 'complete') {
  3155. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3156. AdapterJS.maybeThroughWebRTCReady();
  3157. } else {
  3158. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3159. if (document.readyState === 'complete') {
  3160. // TODO: update comments, we wait for the document to be ready
  3161. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3162. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3163. AdapterJS.maybeThroughWebRTCReady();
  3164. }
  3165. }, 100);
  3166. }
  3167. };
  3168. AdapterJS.maybeThroughWebRTCReady = function() {
  3169. if (!AdapterJS.onwebrtcreadyDone) {
  3170. AdapterJS.onwebrtcreadyDone = true;
  3171. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3172. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3173. }
  3174. }
  3175. };
  3176. // Text namespace
  3177. AdapterJS.TEXT = {
  3178. PLUGIN: {
  3179. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3180. 'to work on this browser.',
  3181. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3182. BUTTON: 'Install Now'
  3183. },
  3184. REFRESH: {
  3185. REQUIRE_REFRESH: 'Please refresh page',
  3186. BUTTON: 'Refresh Page'
  3187. }
  3188. };
  3189. // The result of ice connection states.
  3190. // - starting: Ice connection is starting.
  3191. // - checking: Ice connection is checking.
  3192. // - connected Ice connection is connected.
  3193. // - completed Ice connection is connected.
  3194. // - done Ice connection has been completed.
  3195. // - disconnected Ice connection has been disconnected.
  3196. // - failed Ice connection has failed.
  3197. // - closed Ice connection is closed.
  3198. AdapterJS._iceConnectionStates = {
  3199. starting : 'starting',
  3200. checking : 'checking',
  3201. connected : 'connected',
  3202. completed : 'connected',
  3203. done : 'completed',
  3204. disconnected : 'disconnected',
  3205. failed : 'failed',
  3206. closed : 'closed'
  3207. };
  3208. //The IceConnection states that has been fired for each peer.
  3209. AdapterJS._iceConnectionFiredStates = [];
  3210. // Check if WebRTC Interface is defined.
  3211. AdapterJS.isDefined = null;
  3212. // This function helps to retrieve the webrtc detected browser information.
  3213. // This sets:
  3214. // - webrtcDetectedBrowser: The browser agent name.
  3215. // - webrtcDetectedVersion: The browser version.
  3216. // - webrtcDetectedType: The types of webRTC support.
  3217. // - 'moz': Mozilla implementation of webRTC.
  3218. // - 'webkit': WebKit implementation of webRTC.
  3219. // - 'plugin': Using the plugin implementation.
  3220. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3221. var hasMatch, checkMatch = navigator.userAgent.match(
  3222. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3223. if (/trident/i.test(checkMatch[1])) {
  3224. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3225. webrtcDetectedBrowser = 'IE';
  3226. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3227. } else if (checkMatch[1] === 'Chrome') {
  3228. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3229. if (hasMatch !== null) {
  3230. webrtcDetectedBrowser = 'opera';
  3231. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3232. }
  3233. }
  3234. if (navigator.userAgent.indexOf('Safari')) {
  3235. if (typeof InstallTrigger !== 'undefined') {
  3236. webrtcDetectedBrowser = 'firefox';
  3237. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3238. webrtcDetectedBrowser = 'IE';
  3239. } else if (
  3240. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3241. webrtcDetectedBrowser = 'safari';
  3242. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3243. webrtcDetectedBrowser = 'opera';
  3244. } else if (!!window.chrome) {
  3245. webrtcDetectedBrowser = 'chrome';
  3246. }
  3247. }
  3248. if (!webrtcDetectedBrowser) {
  3249. webrtcDetectedVersion = checkMatch[1];
  3250. }
  3251. if (!webrtcDetectedVersion) {
  3252. try {
  3253. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3254. [navigator.appName, navigator.appVersion, '-?'];
  3255. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3256. checkMatch.splice(1, 1, hasMatch[1]);
  3257. }
  3258. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3259. } catch (error) { }
  3260. }
  3261. };
  3262. // To fix configuration as some browsers does not support
  3263. // the 'urls' attribute.
  3264. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3265. if (pcConfig === null) {
  3266. return;
  3267. }
  3268. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3269. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3270. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3271. delete pcConfig.iceServers[i].urls;
  3272. }
  3273. }
  3274. };
  3275. AdapterJS.addEvent = function(elem, evnt, func) {
  3276. if (elem.addEventListener) { // W3C DOM
  3277. elem.addEventListener(evnt, func, false);
  3278. } else if (elem.attachEvent) {// OLD IE DOM
  3279. elem.attachEvent('on'+evnt, func);
  3280. } else { // No much to do
  3281. elem[evnt] = func;
  3282. }
  3283. };
  3284. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3285. // only inject once the page is ready
  3286. if (document.readyState !== 'complete') {
  3287. return;
  3288. }
  3289. var w = window;
  3290. var i = document.createElement('iframe');
  3291. i.style.position = 'fixed';
  3292. i.style.top = '-41px';
  3293. i.style.left = 0;
  3294. i.style.right = 0;
  3295. i.style.width = '100%';
  3296. i.style.height = '40px';
  3297. i.style.backgroundColor = '#ffffe1';
  3298. i.style.border = 'none';
  3299. i.style.borderBottom = '1px solid #888888';
  3300. i.style.zIndex = '9999999';
  3301. if(typeof i.style.webkitTransition === 'string') {
  3302. i.style.webkitTransition = 'all .5s ease-out';
  3303. } else if(typeof i.style.transition === 'string') {
  3304. i.style.transition = 'all .5s ease-out';
  3305. }
  3306. document.body.appendChild(i);
  3307. c = (i.contentWindow) ? i.contentWindow :
  3308. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3309. c.document.open();
  3310. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3311. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3312. 'middle; cursor: default;">' + text + '</span>');
  3313. if(buttonText && buttonLink) {
  3314. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3315. c.document.close();
  3316. // On click on okay
  3317. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3318. if (!!displayRefreshBar) {
  3319. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3320. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3321. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3322. }
  3323. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3324. e.preventDefault();
  3325. try {
  3326. event.cancelBubble = true;
  3327. } catch(error) { }
  3328. var pluginInstallInterval = setInterval(function(){
  3329. if(! isIE) {
  3330. navigator.plugins.refresh(false);
  3331. }
  3332. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3333. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3334. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3335. function() { // plugin now installed
  3336. clearInterval(pluginInstallInterval);
  3337. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3338. },
  3339. function() {
  3340. // still no plugin detected, nothing to do
  3341. });
  3342. } , 500);
  3343. });
  3344. // On click on Cancel
  3345. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3346. w.document.body.removeChild(i);
  3347. });
  3348. } else {
  3349. c.document.close();
  3350. }
  3351. setTimeout(function() {
  3352. if(typeof i.style.webkitTransform === 'string') {
  3353. i.style.webkitTransform = 'translateY(40px)';
  3354. } else if(typeof i.style.transform === 'string') {
  3355. i.style.transform = 'translateY(40px)';
  3356. } else {
  3357. i.style.top = '0px';
  3358. }
  3359. }, 300);
  3360. };
  3361. // -----------------------------------------------------------
  3362. // Detected webrtc implementation. Types are:
  3363. // - 'moz': Mozilla implementation of webRTC.
  3364. // - 'webkit': WebKit implementation of webRTC.
  3365. // - 'plugin': Using the plugin implementation.
  3366. webrtcDetectedType = null;
  3367. // Detected webrtc datachannel support. Types are:
  3368. // - 'SCTP': SCTP datachannel support.
  3369. // - 'RTP': RTP datachannel support.
  3370. webrtcDetectedDCSupport = null;
  3371. // Set the settings for creating DataChannels, MediaStream for
  3372. // Cross-browser compability.
  3373. // - This is only for SCTP based support browsers.
  3374. // the 'urls' attribute.
  3375. checkMediaDataChannelSettings =
  3376. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3377. if (typeof callback !== 'function') {
  3378. return;
  3379. }
  3380. var beOfferer = true;
  3381. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3382. // Nightly version does not require MozDontOfferDataChannel for interop
  3383. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3384. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3385. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3386. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3387. // Resends an updated version of constraints for MozDataChannel to work
  3388. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3389. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3390. try {
  3391. delete constraints.mandatory.MozDontOfferDataChannel;
  3392. } catch (error) {
  3393. console.error('Failed deleting MozDontOfferDataChannel');
  3394. console.error(error);
  3395. }
  3396. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3397. constraints.mandatory.MozDontOfferDataChannel = true;
  3398. }
  3399. if (!isLocalFirefox) {
  3400. // temporary measure to remove Moz* constraints in non Firefox browsers
  3401. for (var prop in constraints.mandatory) {
  3402. if (constraints.mandatory.hasOwnProperty(prop)) {
  3403. if (prop.indexOf('Moz') !== -1) {
  3404. delete constraints.mandatory[prop];
  3405. }
  3406. }
  3407. }
  3408. }
  3409. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3410. // interopability of the media stream
  3411. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3412. beOfferer = false;
  3413. }
  3414. callback(beOfferer, constraints);
  3415. };
  3416. // Handles the differences for all browsers ice connection state output.
  3417. // - Tested outcomes are:
  3418. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3419. // - Chrome (answerer) : 'checking' > 'connected'
  3420. // - Firefox (offerer) : 'checking' > 'connected'
  3421. // - Firefox (answerer): 'checking' > 'connected'
  3422. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3423. if (typeof callback !== 'function') {
  3424. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3425. return;
  3426. }
  3427. peerId = (peerId) ? peerId : 'peer';
  3428. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3429. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3430. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3431. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3432. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3433. }
  3434. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3435. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3436. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3437. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3438. setTimeout(function () {
  3439. AdapterJS._iceConnectionFiredStates[peerId]
  3440. .push(AdapterJS._iceConnectionStates.done);
  3441. callback(AdapterJS._iceConnectionStates.done);
  3442. }, 1000);
  3443. }
  3444. callback(iceConnectionState);
  3445. }
  3446. return;
  3447. };
  3448. // Firefox:
  3449. // - Creates iceServer from the url for Firefox.
  3450. // - Create iceServer with stun url.
  3451. // - Create iceServer with turn url.
  3452. // - Ignore the transport parameter from TURN url for FF version <=27.
  3453. // - Return null for createIceServer if transport=tcp.
  3454. // - FF 27 and above supports transport parameters in TURN url,
  3455. // - So passing in the full url to create iceServer.
  3456. // Chrome:
  3457. // - Creates iceServer from the url for Chrome M33 and earlier.
  3458. // - Create iceServer with stun url.
  3459. // - Chrome M28 & above uses below TURN format.
  3460. // Plugin:
  3461. // - Creates Ice Server for Plugin Browsers
  3462. // - If Stun - Create iceServer with stun url.
  3463. // - Else - Create iceServer with turn url
  3464. // - This is a WebRTC Function
  3465. createIceServer = null;
  3466. // Firefox:
  3467. // - Creates IceServers for Firefox
  3468. // - Use .url for FireFox.
  3469. // - Multiple Urls support
  3470. // Chrome:
  3471. // - Creates iceServers from the urls for Chrome M34 and above.
  3472. // - .urls is supported since Chrome M34.
  3473. // - Multiple Urls support
  3474. // Plugin:
  3475. // - Creates Ice Servers for Plugin Browsers
  3476. // - Multiple Urls support
  3477. // - This is a WebRTC Function
  3478. createIceServers = null;
  3479. //------------------------------------------------------------
  3480. //The RTCPeerConnection object.
  3481. RTCPeerConnection = null;
  3482. // Creates RTCSessionDescription object for Plugin Browsers
  3483. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3484. RTCSessionDescription : null;
  3485. // Creates RTCIceCandidate object for Plugin Browsers
  3486. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3487. RTCIceCandidate : null;
  3488. // Get UserMedia (only difference is the prefix).
  3489. // Code from Adam Barth.
  3490. getUserMedia = null;
  3491. // Attach a media stream to an element.
  3492. attachMediaStream = null;
  3493. // Re-attach a media stream to an element.
  3494. reattachMediaStream = null;
  3495. // Detected browser agent name. Types are:
  3496. // - 'firefox': Firefox browser.
  3497. // - 'chrome': Chrome browser.
  3498. // - 'opera': Opera browser.
  3499. // - 'safari': Safari browser.
  3500. // - 'IE' - Internet Explorer browser.
  3501. webrtcDetectedBrowser = null;
  3502. // Detected browser version.
  3503. webrtcDetectedVersion = null;
  3504. // Check for browser types and react accordingly
  3505. if (navigator.mozGetUserMedia) {
  3506. webrtcDetectedBrowser = 'firefox';
  3507. webrtcDetectedVersion = parseInt(navigator
  3508. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3509. webrtcDetectedType = 'moz';
  3510. webrtcDetectedDCSupport = 'SCTP';
  3511. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3512. AdapterJS.maybeFixConfiguration(pcConfig);
  3513. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3514. };
  3515. // The RTCSessionDescription object.
  3516. RTCSessionDescription = mozRTCSessionDescription;
  3517. window.RTCSessionDescription = RTCSessionDescription;
  3518. // The RTCIceCandidate object.
  3519. RTCIceCandidate = mozRTCIceCandidate;
  3520. window.RTCIceCandidate = RTCIceCandidate;
  3521. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  3522. navigator.getUserMedia = window.getUserMedia;
  3523. // Shim for MediaStreamTrack.getSources.
  3524. MediaStreamTrack.getSources = function(successCb) {
  3525. setTimeout(function() {
  3526. var infos = [
  3527. { kind: 'audio', id: 'default', label:'', facing:'' },
  3528. { kind: 'video', id: 'default', label:'', facing:'' }
  3529. ];
  3530. successCb(infos);
  3531. }, 0);
  3532. };
  3533. createIceServer = function (url, username, password) {
  3534. var iceServer = null;
  3535. var url_parts = url.split(':');
  3536. if (url_parts[0].indexOf('stun') === 0) {
  3537. iceServer = { url : url };
  3538. } else if (url_parts[0].indexOf('turn') === 0) {
  3539. if (webrtcDetectedVersion < 27) {
  3540. var turn_url_parts = url.split('?');
  3541. if (turn_url_parts.length === 1 ||
  3542. turn_url_parts[1].indexOf('transport=udp') === 0) {
  3543. iceServer = {
  3544. url : turn_url_parts[0],
  3545. credential : password,
  3546. username : username
  3547. };
  3548. }
  3549. } else {
  3550. iceServer = {
  3551. url : url,
  3552. credential : password,
  3553. username : username
  3554. };
  3555. }
  3556. }
  3557. return iceServer;
  3558. };
  3559. createIceServers = function (urls, username, password) {
  3560. var iceServers = [];
  3561. for (i = 0; i < urls.length; i++) {
  3562. var iceServer = createIceServer(urls[i], username, password);
  3563. if (iceServer !== null) {
  3564. iceServers.push(iceServer);
  3565. }
  3566. }
  3567. return iceServers;
  3568. };
  3569. attachMediaStream = function (element, stream) {
  3570. element.mozSrcObject = stream;
  3571. if (stream !== null)
  3572. element.play();
  3573. return element;
  3574. };
  3575. reattachMediaStream = function (to, from) {
  3576. to.mozSrcObject = from.mozSrcObject;
  3577. to.play();
  3578. return to;
  3579. };
  3580. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  3581. if (!callback) {
  3582. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  3583. ': 1 argument required, but only 0 present.');
  3584. }
  3585. return callback([]);
  3586. };
  3587. // Fake get{Video,Audio}Tracks
  3588. if (!MediaStream.prototype.getVideoTracks) {
  3589. MediaStream.prototype.getVideoTracks = function () {
  3590. return [];
  3591. };
  3592. }
  3593. if (!MediaStream.prototype.getAudioTracks) {
  3594. MediaStream.prototype.getAudioTracks = function () {
  3595. return [];
  3596. };
  3597. }
  3598. AdapterJS.maybeThroughWebRTCReady();
  3599. } else if (navigator.webkitGetUserMedia) {
  3600. webrtcDetectedBrowser = 'chrome';
  3601. webrtcDetectedType = 'webkit';
  3602. webrtcDetectedVersion = parseInt(navigator
  3603. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  3604. // check if browser is opera 20+
  3605. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3606. if (checkIfOpera !== null) {
  3607. webrtcDetectedBrowser = 'opera';
  3608. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  3609. }
  3610. // check browser datachannel support
  3611. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  3612. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  3613. webrtcDetectedDCSupport = 'SCTP';
  3614. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  3615. webrtcDetectedVersion > 24) {
  3616. webrtcDetectedDCSupport = 'RTP';
  3617. } else {
  3618. webrtcDetectedDCSupport = '';
  3619. }
  3620. createIceServer = function (url, username, password) {
  3621. var iceServer = null;
  3622. var url_parts = url.split(':');
  3623. if (url_parts[0].indexOf('stun') === 0) {
  3624. iceServer = { 'url' : url };
  3625. } else if (url_parts[0].indexOf('turn') === 0) {
  3626. iceServer = {
  3627. 'url' : url,
  3628. 'credential' : password,
  3629. 'username' : username
  3630. };
  3631. }
  3632. return iceServer;
  3633. };
  3634. createIceServers = function (urls, username, password) {
  3635. var iceServers = [];
  3636. if (webrtcDetectedVersion >= 34) {
  3637. iceServers = {
  3638. 'urls' : urls,
  3639. 'credential' : password,
  3640. 'username' : username
  3641. };
  3642. } else {
  3643. for (i = 0; i < urls.length; i++) {
  3644. var iceServer = createIceServer(urls[i], username, password);
  3645. if (iceServer !== null) {
  3646. iceServers.push(iceServer);
  3647. }
  3648. }
  3649. }
  3650. return iceServers;
  3651. };
  3652. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3653. if (webrtcDetectedVersion < 34) {
  3654. AdapterJS.maybeFixConfiguration(pcConfig);
  3655. }
  3656. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3657. };
  3658. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3659. navigator.getUserMedia = window.getUserMedia;
  3660. attachMediaStream = function (element, stream) {
  3661. if (typeof element.srcObject !== 'undefined') {
  3662. element.srcObject = stream;
  3663. } else if (typeof element.mozSrcObject !== 'undefined') {
  3664. element.mozSrcObject = stream;
  3665. } else if (typeof element.src !== 'undefined') {
  3666. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  3667. } else {
  3668. console.log('Error attaching stream to element.');
  3669. }
  3670. return element;
  3671. };
  3672. reattachMediaStream = function (to, from) {
  3673. to.src = from.src;
  3674. return to;
  3675. };
  3676. AdapterJS.maybeThroughWebRTCReady();
  3677. } else if (navigator.mediaDevices && navigator.userAgent.match(
  3678. /Edge\/(\d+).(\d+)$/)) {
  3679. webrtcDetectedBrowser = 'edge';
  3680. webrtcDetectedVersion =
  3681. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  3682. // the minimum version still supported by adapter.
  3683. webrtcMinimumVersion = 12;
  3684. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3685. attachMediaStream = function(element, stream) {
  3686. element.srcObject = stream;
  3687. return element;
  3688. };
  3689. reattachMediaStream = function(to, from) {
  3690. to.srcObject = from.srcObject;
  3691. return to;
  3692. };
  3693. AdapterJS.maybeThroughWebRTCReady();
  3694. } else { // TRY TO USE PLUGIN
  3695. // IE 9 is not offering an implementation of console.log until you open a console
  3696. if (typeof console !== 'object' || typeof console.log !== 'function') {
  3697. /* jshint -W020 */
  3698. console = {} || console;
  3699. // Implemented based on console specs from MDN
  3700. // You may override these functions
  3701. console.log = function (arg) {};
  3702. console.info = function (arg) {};
  3703. console.error = function (arg) {};
  3704. console.dir = function (arg) {};
  3705. console.exception = function (arg) {};
  3706. console.trace = function (arg) {};
  3707. console.warn = function (arg) {};
  3708. console.count = function (arg) {};
  3709. console.debug = function (arg) {};
  3710. console.count = function (arg) {};
  3711. console.time = function (arg) {};
  3712. console.timeEnd = function (arg) {};
  3713. console.group = function (arg) {};
  3714. console.groupCollapsed = function (arg) {};
  3715. console.groupEnd = function (arg) {};
  3716. /* jshint +W020 */
  3717. }
  3718. webrtcDetectedType = 'plugin';
  3719. webrtcDetectedDCSupport = 'plugin';
  3720. AdapterJS.parseWebrtcDetectedBrowser();
  3721. isIE = webrtcDetectedBrowser === 'IE';
  3722. /* jshint -W035 */
  3723. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  3724. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3725. /* empty because it needs to prevent the function from running. */
  3726. }
  3727. };
  3728. /* jshint +W035 */
  3729. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  3730. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3731. // Call immediately if possible
  3732. // Once the plugin is set, the code will always take this path
  3733. callback();
  3734. } else {
  3735. // otherwise start a 100ms interval
  3736. var checkPluginReadyState = setInterval(function () {
  3737. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3738. clearInterval(checkPluginReadyState);
  3739. callback();
  3740. }
  3741. }, 100);
  3742. }
  3743. };
  3744. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  3745. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3746. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  3747. });
  3748. };
  3749. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  3750. // only inject once the page is ready
  3751. if (document.readyState !== 'complete') {
  3752. return;
  3753. }
  3754. // Prevent multiple injections
  3755. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  3756. return;
  3757. }
  3758. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  3759. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  3760. var frag = document.createDocumentFragment();
  3761. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  3762. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  3763. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  3764. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  3765. '<param name="pluginId" value="' +
  3766. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  3767. '<param name="windowless" value="false" /> ' +
  3768. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3769. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  3770. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  3771. // uncomment to be able to use virtual cams
  3772. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3773. '</object>';
  3774. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  3775. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  3776. }
  3777. document.body.appendChild(frag);
  3778. // Need to re-fetch the plugin
  3779. AdapterJS.WebRTCPlugin.plugin =
  3780. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  3781. } else {
  3782. // Load Plugin
  3783. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  3784. AdapterJS.WebRTCPlugin.plugin.id =
  3785. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  3786. // IE will only start the plugin if it's ACTUALLY visible
  3787. if (isIE) {
  3788. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  3789. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  3790. } else { // The size of the plugin on Safari should be 0x0px
  3791. // so that the autorisation prompt is at the top
  3792. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  3793. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  3794. }
  3795. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  3796. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  3797. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  3798. '<param name="pluginId" value="' +
  3799. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  3800. '<param name="windowless" value="false" /> ' +
  3801. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3802. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  3803. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  3804. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  3805. }
  3806. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  3807. };
  3808. AdapterJS.WebRTCPlugin.isPluginInstalled =
  3809. function (comName, plugName, installedCb, notInstalledCb) {
  3810. if (!isIE) {
  3811. var pluginArray = navigator.plugins;
  3812. for (var i = 0; i < pluginArray.length; i++) {
  3813. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  3814. installedCb();
  3815. return;
  3816. }
  3817. }
  3818. notInstalledCb();
  3819. } else {
  3820. try {
  3821. var axo = new ActiveXObject(comName + '.' + plugName);
  3822. } catch (e) {
  3823. notInstalledCb();
  3824. return;
  3825. }
  3826. installedCb();
  3827. }
  3828. };
  3829. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  3830. if (AdapterJS.WebRTCPlugin.pluginState ===
  3831. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3832. console.error("AdapterJS - WebRTC interface has already been defined");
  3833. return;
  3834. }
  3835. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  3836. AdapterJS.isDefined = function (variable) {
  3837. return variable !== null && variable !== undefined;
  3838. };
  3839. createIceServer = function (url, username, password) {
  3840. var iceServer = null;
  3841. var url_parts = url.split(':');
  3842. if (url_parts[0].indexOf('stun') === 0) {
  3843. iceServer = {
  3844. 'url' : url,
  3845. 'hasCredentials' : false
  3846. };
  3847. } else if (url_parts[0].indexOf('turn') === 0) {
  3848. iceServer = {
  3849. 'url' : url,
  3850. 'hasCredentials' : true,
  3851. 'credential' : password,
  3852. 'username' : username
  3853. };
  3854. }
  3855. return iceServer;
  3856. };
  3857. createIceServers = function (urls, username, password) {
  3858. var iceServers = [];
  3859. for (var i = 0; i < urls.length; ++i) {
  3860. iceServers.push(createIceServer(urls[i], username, password));
  3861. }
  3862. return iceServers;
  3863. };
  3864. RTCSessionDescription = function (info) {
  3865. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3866. return AdapterJS.WebRTCPlugin.plugin.
  3867. ConstructSessionDescription(info.type, info.sdp);
  3868. };
  3869. RTCPeerConnection = function (servers, constraints) {
  3870. var iceServers = null;
  3871. if (servers) {
  3872. iceServers = servers.iceServers;
  3873. for (var i = 0; i < iceServers.length; i++) {
  3874. if (iceServers[i].urls && !iceServers[i].url) {
  3875. iceServers[i].url = iceServers[i].urls;
  3876. }
  3877. iceServers[i].hasCredentials = AdapterJS.
  3878. isDefined(iceServers[i].username) &&
  3879. AdapterJS.isDefined(iceServers[i].credential);
  3880. }
  3881. }
  3882. var mandatory = (constraints && constraints.mandatory) ?
  3883. constraints.mandatory : null;
  3884. var optional = (constraints && constraints.optional) ?
  3885. constraints.optional : null;
  3886. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3887. return AdapterJS.WebRTCPlugin.plugin.
  3888. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  3889. iceServers, mandatory, optional);
  3890. };
  3891. MediaStreamTrack = {};
  3892. MediaStreamTrack.getSources = function (callback) {
  3893. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3894. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  3895. });
  3896. };
  3897. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  3898. constraints.audio = constraints.audio || false;
  3899. constraints.video = constraints.video || false;
  3900. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3901. AdapterJS.WebRTCPlugin.plugin.
  3902. getUserMedia(constraints, successCallback, failureCallback);
  3903. });
  3904. };
  3905. window.navigator.getUserMedia = window.getUserMedia;
  3906. attachMediaStream = function (element, stream) {
  3907. if (!element || !element.parentNode) {
  3908. return;
  3909. }
  3910. var streamId
  3911. if (stream === null) {
  3912. streamId = '';
  3913. }
  3914. else {
  3915. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  3916. streamId = stream.id;
  3917. }
  3918. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  3919. var nodeName = element.nodeName.toLowerCase();
  3920. if (nodeName !== 'object') { // not a plugin <object> tag yet
  3921. var tag;
  3922. switch(nodeName) {
  3923. case 'audio':
  3924. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  3925. break;
  3926. case 'video':
  3927. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  3928. break;
  3929. default:
  3930. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  3931. }
  3932. var frag = document.createDocumentFragment();
  3933. var temp = document.createElement('div');
  3934. var classHTML = '';
  3935. if (element.className) {
  3936. classHTML = 'class="' + element.className + '" ';
  3937. } else if (element.attributes && element.attributes['class']) {
  3938. classHTML = 'class="' + element.attributes['class'].value + '" ';
  3939. }
  3940. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  3941. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  3942. '<param name="pluginId" value="' + elementId + '" /> ' +
  3943. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3944. '<param name="windowless" value="true" /> ' +
  3945. '<param name="streamId" value="' + streamId + '" /> ' +
  3946. '<param name="tag" value="' + tag + '" /> ' +
  3947. '</object>';
  3948. while (temp.firstChild) {
  3949. frag.appendChild(temp.firstChild);
  3950. }
  3951. var height = '';
  3952. var width = '';
  3953. if (element.getBoundingClientRect) {
  3954. var rectObject = element.getBoundingClientRect();
  3955. width = rectObject.width + 'px';
  3956. height = rectObject.height + 'px';
  3957. }
  3958. else if (element.width) {
  3959. width = element.width;
  3960. height = element.height;
  3961. } else {
  3962. // TODO: What scenario could bring us here?
  3963. }
  3964. element.parentNode.insertBefore(frag, element);
  3965. frag = document.getElementById(elementId);
  3966. frag.width = width;
  3967. frag.height = height;
  3968. element.parentNode.removeChild(element);
  3969. } else { // already an <object> tag, just change the stream id
  3970. var children = element.children;
  3971. for (var i = 0; i !== children.length; ++i) {
  3972. if (children[i].name === 'streamId') {
  3973. children[i].value = streamId;
  3974. break;
  3975. }
  3976. }
  3977. element.setStreamId(streamId);
  3978. }
  3979. var newElement = document.getElementById(elementId);
  3980. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  3981. newElement.onplay = (element.onplay) ? element.onplay : function (arg) {};
  3982. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  3983. if (isIE) { // on IE the event needs to be plugged manually
  3984. newElement.attachEvent('onplaying', newElement.onplaying);
  3985. newElement.attachEvent('onplay', newElement.onplay);
  3986. newElement._TemOnClick = function (id) {
  3987. var arg = {
  3988. srcElement : document.getElementById(id)
  3989. };
  3990. newElement.onclick(arg);
  3991. };
  3992. }
  3993. return newElement;
  3994. };
  3995. reattachMediaStream = function (to, from) {
  3996. var stream = null;
  3997. var children = from.children;
  3998. for (var i = 0; i !== children.length; ++i) {
  3999. if (children[i].name === 'streamId') {
  4000. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4001. stream = AdapterJS.WebRTCPlugin.plugin
  4002. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4003. break;
  4004. }
  4005. }
  4006. if (stream !== null) {
  4007. return attachMediaStream(to, stream);
  4008. } else {
  4009. console.log('Could not find the stream associated with this element');
  4010. }
  4011. };
  4012. RTCIceCandidate = function (candidate) {
  4013. if (!candidate.sdpMid) {
  4014. candidate.sdpMid = '';
  4015. }
  4016. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4017. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4018. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4019. );
  4020. };
  4021. // inject plugin
  4022. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4023. AdapterJS.WebRTCPlugin.injectPlugin();
  4024. };
  4025. // This function will be called if the plugin is needed (browser different
  4026. // from Chrome or Firefox), but the plugin is not installed.
  4027. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4028. function() {
  4029. AdapterJS.addEvent(document,
  4030. 'readystatechange',
  4031. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4032. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4033. };
  4034. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4035. if (AdapterJS.options.hidePluginInstallPrompt) {
  4036. return;
  4037. }
  4038. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4039. if(downloadLink) { // if download link
  4040. var popupString;
  4041. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4042. popupString = 'This website requires you to install the ' +
  4043. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4044. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4045. ' WebRTC Plugin</a>' +
  4046. ' to work on this browser.';
  4047. } else { // no portal link, just print a generic explanation
  4048. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4049. }
  4050. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4051. } else { // no download link, just print a generic explanation
  4052. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4053. }
  4054. };
  4055. // Try to detect the plugin and act accordingly
  4056. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4057. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4058. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4059. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4060. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4061. }
  4062. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4063. },{"jitsi-meet-logger":47}],21:[function(require,module,exports){
  4064. (function (__filename){
  4065. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4066. function supportsLocalStorage() {
  4067. try {
  4068. return 'localStorage' in window && window.localStorage !== null;
  4069. } catch (e) {
  4070. logger.log("localstorage is not supported");
  4071. return false;
  4072. }
  4073. }
  4074. function generateUniqueId() {
  4075. function _p8() {
  4076. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4077. }
  4078. return _p8() + _p8() + _p8() + _p8();
  4079. }
  4080. function Settings(conferenceID) {
  4081. this.email = '';
  4082. this.displayName = '';
  4083. this.userId;
  4084. this.language = null;
  4085. this.confSettings = null;
  4086. this.conferenceID = conferenceID;
  4087. if (supportsLocalStorage()) {
  4088. if(!window.localStorage.getItem(conferenceID))
  4089. this.confSettings = {};
  4090. else
  4091. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4092. if(!this.confSettings.jitsiMeetId) {
  4093. this.confSettings.jitsiMeetId = generateUniqueId();
  4094. logger.log("generated id",
  4095. this.confSettings.jitsiMeetId);
  4096. this.save();
  4097. }
  4098. this.userId = this.confSettings.jitsiMeetId || '';
  4099. this.email = this.confSettings.email || '';
  4100. this.displayName = this.confSettings.displayname || '';
  4101. this.language = this.confSettings.language;
  4102. } else {
  4103. logger.log("local storage is not supported");
  4104. this.userId = generateUniqueId();
  4105. }
  4106. }
  4107. Settings.prototype.save = function () {
  4108. if(!supportsLocalStorage())
  4109. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4110. }
  4111. Settings.prototype.setDisplayName = function (newDisplayName) {
  4112. this.displayName = newDisplayName;
  4113. if(this.confSettings != null)
  4114. this.confSettings.displayname = displayName;
  4115. this.save();
  4116. return this.displayName;
  4117. },
  4118. Settings.prototype.setEmail = function (newEmail) {
  4119. this.email = newEmail;
  4120. if(this.confSettings != null)
  4121. this.confSettings.email = newEmail;
  4122. this.save();
  4123. return this.email;
  4124. },
  4125. Settings.prototype.getSettings = function () {
  4126. return {
  4127. email: this.email,
  4128. displayName: this.displayName,
  4129. uid: this.userId,
  4130. language: this.language
  4131. };
  4132. },
  4133. Settings.prototype.setLanguage = function (lang) {
  4134. this.language = lang;
  4135. if(this.confSettings != null)
  4136. this.confSettings.language = lang;
  4137. this.save();
  4138. }
  4139. module.exports = Settings;
  4140. }).call(this,"/modules/settings/Settings.js")
  4141. },{"jitsi-meet-logger":47}],22:[function(require,module,exports){
  4142. /* global config */
  4143. /**
  4144. * Provides statistics for the local stream.
  4145. */
  4146. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4147. /**
  4148. * Size of the webaudio analyzer buffer.
  4149. * @type {number}
  4150. */
  4151. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4152. /**
  4153. * Value of the webaudio analyzer smoothing time parameter.
  4154. * @type {number}
  4155. */
  4156. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4157. /**
  4158. * Converts time domain data array to audio level.
  4159. * @param samples the time domain data array.
  4160. * @returns {number} the audio level
  4161. */
  4162. function timeDomainDataToAudioLevel(samples) {
  4163. var maxVolume = 0;
  4164. var length = samples.length;
  4165. for (var i = 0; i < length; i++) {
  4166. if (maxVolume < samples[i])
  4167. maxVolume = samples[i];
  4168. }
  4169. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4170. }
  4171. /**
  4172. * Animates audio level change
  4173. * @param newLevel the new audio level
  4174. * @param lastLevel the last audio level
  4175. * @returns {Number} the audio level to be set
  4176. */
  4177. function animateLevel(newLevel, lastLevel) {
  4178. var value = 0;
  4179. var diff = lastLevel - newLevel;
  4180. if(diff > 0.2) {
  4181. value = lastLevel - 0.2;
  4182. }
  4183. else if(diff < -0.4) {
  4184. value = lastLevel + 0.4;
  4185. }
  4186. else {
  4187. value = newLevel;
  4188. }
  4189. return parseFloat(value.toFixed(3));
  4190. }
  4191. /**
  4192. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4193. *
  4194. * @param stream the local stream
  4195. * @param interval stats refresh interval given in ms.
  4196. * @param callback function that receives the audio levels.
  4197. * @constructor
  4198. */
  4199. function LocalStatsCollector(stream, interval, callback) {
  4200. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4201. this.stream = stream;
  4202. this.intervalId = null;
  4203. this.intervalMilis = interval;
  4204. this.audioLevel = 0;
  4205. this.callback = callback;
  4206. }
  4207. /**
  4208. * Starts the collecting the statistics.
  4209. */
  4210. LocalStatsCollector.prototype.start = function () {
  4211. if (!window.AudioContext ||
  4212. RTCBrowserType.isTemasysPluginUsed())
  4213. return;
  4214. var context = new AudioContext();
  4215. var analyser = context.createAnalyser();
  4216. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4217. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4218. var source = context.createMediaStreamSource(this.stream);
  4219. source.connect(analyser);
  4220. var self = this;
  4221. this.intervalId = setInterval(
  4222. function () {
  4223. var array = new Uint8Array(analyser.frequencyBinCount);
  4224. analyser.getByteTimeDomainData(array);
  4225. var audioLevel = timeDomainDataToAudioLevel(array);
  4226. if (audioLevel != self.audioLevel) {
  4227. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4228. self.callback(self.audioLevel);
  4229. }
  4230. },
  4231. this.intervalMilis
  4232. );
  4233. };
  4234. /**
  4235. * Stops collecting the statistics.
  4236. */
  4237. LocalStatsCollector.prototype.stop = function () {
  4238. if (this.intervalId) {
  4239. clearInterval(this.intervalId);
  4240. this.intervalId = null;
  4241. }
  4242. };
  4243. module.exports = LocalStatsCollector;
  4244. },{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4245. (function (__filename){
  4246. /* global require, ssrc2jid */
  4247. /* jshint -W117 */
  4248. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4249. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4250. var StatisticsEvents = require("../../service/statistics/Events");
  4251. /* Whether we support the browser we are running into for logging statistics */
  4252. var browserSupported = RTCBrowserType.isChrome() ||
  4253. RTCBrowserType.isOpera();
  4254. var keyMap = {};
  4255. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4256. "ssrc": "ssrc",
  4257. "packetsReceived": "packetsReceived",
  4258. "packetsLost": "packetsLost",
  4259. "packetsSent": "packetsSent",
  4260. "bytesReceived": "bytesReceived",
  4261. "bytesSent": "bytesSent"
  4262. };
  4263. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4264. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4265. "sendBandwidth": "googAvailableSendBandwidth",
  4266. "remoteAddress": "googRemoteAddress",
  4267. "transportType": "googTransportType",
  4268. "localAddress": "googLocalAddress",
  4269. "activeConnection": "googActiveConnection",
  4270. "ssrc": "ssrc",
  4271. "packetsReceived": "packetsReceived",
  4272. "packetsSent": "packetsSent",
  4273. "packetsLost": "packetsLost",
  4274. "bytesReceived": "bytesReceived",
  4275. "bytesSent": "bytesSent",
  4276. "googFrameHeightReceived": "googFrameHeightReceived",
  4277. "googFrameWidthReceived": "googFrameWidthReceived",
  4278. "googFrameHeightSent": "googFrameHeightSent",
  4279. "googFrameWidthSent": "googFrameWidthSent",
  4280. "audioInputLevel": "audioInputLevel",
  4281. "audioOutputLevel": "audioOutputLevel"
  4282. };
  4283. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4284. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4285. /**
  4286. * Calculates packet lost percent using the number of lost packets and the
  4287. * number of all packet.
  4288. * @param lostPackets the number of lost packets
  4289. * @param totalPackets the number of all packets.
  4290. * @returns {number} packet loss percent
  4291. */
  4292. function calculatePacketLoss(lostPackets, totalPackets) {
  4293. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4294. return 0;
  4295. return Math.round((lostPackets/totalPackets)*100);
  4296. }
  4297. function getStatValue(item, name) {
  4298. var browserType = RTCBrowserType.getBrowserType();
  4299. if (!keyMap[browserType][name])
  4300. throw "The property isn't supported!";
  4301. var key = keyMap[browserType][name];
  4302. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4303. item.stat(key) : item[key];
  4304. }
  4305. function formatAudioLevel(audioLevel) {
  4306. return Math.min(Math.max(audioLevel, 0), 1);
  4307. }
  4308. /**
  4309. * Checks whether a certain record should be included in the logged statistics.
  4310. */
  4311. function acceptStat(reportId, reportType, statName) {
  4312. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4313. return false;
  4314. if (reportType == "ssrc") {
  4315. if (statName == "googTrackId" ||
  4316. statName == "transportId" ||
  4317. statName == "ssrc")
  4318. return false;
  4319. }
  4320. return true;
  4321. }
  4322. /**
  4323. * Checks whether a certain record should be included in the logged statistics.
  4324. */
  4325. function acceptReport(id, type) {
  4326. if (id.substring(0, 15) == "googCertificate" ||
  4327. id.substring(0, 9) == "googTrack" ||
  4328. id.substring(0, 20) == "googLibjingleSession")
  4329. return false;
  4330. if (type == "googComponent")
  4331. return false;
  4332. return true;
  4333. }
  4334. /**
  4335. * Peer statistics data holder.
  4336. * @constructor
  4337. */
  4338. function PeerStats()
  4339. {
  4340. this.ssrc2Loss = {};
  4341. this.ssrc2AudioLevel = {};
  4342. this.ssrc2bitrate = {};
  4343. this.ssrc2resolution = {};
  4344. }
  4345. /**
  4346. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4347. * represented by this instance.
  4348. * @param lossRate new packet loss rate value to be set.
  4349. */
  4350. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4351. {
  4352. this.ssrc2Loss = lossRate;
  4353. };
  4354. /**
  4355. * Sets resolution that belong to the ssrc
  4356. * represented by this instance.
  4357. * @param resolution new resolution value to be set.
  4358. */
  4359. PeerStats.prototype.setSsrcResolution = function (resolution)
  4360. {
  4361. if(resolution === null && this.ssrc2resolution[ssrc])
  4362. {
  4363. delete this.ssrc2resolution[ssrc];
  4364. }
  4365. else if(resolution !== null)
  4366. this.ssrc2resolution[ssrc] = resolution;
  4367. };
  4368. /**
  4369. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4370. * represented by this instance.
  4371. * @param ssrc audio or video RTP stream SSRC.
  4372. * @param bitrate new bitrate value to be set.
  4373. */
  4374. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4375. {
  4376. if(this.ssrc2bitrate[ssrc])
  4377. {
  4378. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4379. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4380. }
  4381. else {
  4382. this.ssrc2bitrate[ssrc] = bitrate;
  4383. }
  4384. };
  4385. /**
  4386. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4387. * the stream which belongs to the peer represented by this instance.
  4388. * @param ssrc RTP stream SSRC for which current audio level value will be
  4389. * updated.
  4390. * @param audioLevel the new audio level value to be set. Value is truncated to
  4391. * fit the range from 0 to 1.
  4392. */
  4393. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4394. {
  4395. // Range limit 0 - 1
  4396. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4397. };
  4398. function ConferenceStats() {
  4399. /**
  4400. * The bandwidth
  4401. * @type {{}}
  4402. */
  4403. this.bandwidth = {};
  4404. /**
  4405. * The bit rate
  4406. * @type {{}}
  4407. */
  4408. this.bitrate = {};
  4409. /**
  4410. * The packet loss rate
  4411. * @type {{}}
  4412. */
  4413. this.packetLoss = null;
  4414. /**
  4415. * Array with the transport information.
  4416. * @type {Array}
  4417. */
  4418. this.transport = [];
  4419. }
  4420. /**
  4421. * <tt>StatsCollector</tt> registers for stats updates of given
  4422. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4423. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4424. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4425. * instance as an event source.
  4426. *
  4427. * @param peerconnection webRTC peer connection object.
  4428. * @param interval stats refresh interval given in ms.
  4429. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4430. * called on stats update.
  4431. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4432. * @constructor
  4433. */
  4434. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4435. {
  4436. this.peerconnection = peerconnection;
  4437. this.baselineAudioLevelsReport = null;
  4438. this.currentAudioLevelsReport = null;
  4439. this.currentStatsReport = null;
  4440. this.baselineStatsReport = null;
  4441. this.audioLevelsIntervalId = null;
  4442. this.eventEmitter = eventEmitter;
  4443. this.config = config || {};
  4444. this.conferenceStats = new ConferenceStats();
  4445. /**
  4446. * Gather PeerConnection stats once every this many milliseconds.
  4447. */
  4448. this.GATHER_INTERVAL = 15000;
  4449. /**
  4450. * Log stats via the focus once every this many milliseconds.
  4451. */
  4452. this.LOG_INTERVAL = 60000;
  4453. /**
  4454. * Gather stats and store them in this.statsToBeLogged.
  4455. */
  4456. this.gatherStatsIntervalId = null;
  4457. /**
  4458. * Send the stats already saved in this.statsToBeLogged to be logged via
  4459. * the focus.
  4460. */
  4461. this.logStatsIntervalId = null;
  4462. /**
  4463. * Stores the statistics which will be send to the focus to be logged.
  4464. */
  4465. this.statsToBeLogged =
  4466. {
  4467. timestamps: [],
  4468. stats: {}
  4469. };
  4470. // Updates stats interval
  4471. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4472. this.statsIntervalId = null;
  4473. this.statsIntervalMilis = statsInterval;
  4474. // Map of ssrcs to PeerStats
  4475. this.ssrc2stats = {};
  4476. }
  4477. module.exports = StatsCollector;
  4478. /**
  4479. * Stops stats updates.
  4480. */
  4481. StatsCollector.prototype.stop = function () {
  4482. if (this.audioLevelsIntervalId) {
  4483. clearInterval(this.audioLevelsIntervalId);
  4484. this.audioLevelsIntervalId = null;
  4485. }
  4486. if (this.statsIntervalId)
  4487. {
  4488. clearInterval(this.statsIntervalId);
  4489. this.statsIntervalId = null;
  4490. }
  4491. if(this.logStatsIntervalId)
  4492. {
  4493. clearInterval(this.logStatsIntervalId);
  4494. this.logStatsIntervalId = null;
  4495. }
  4496. if(this.gatherStatsIntervalId)
  4497. {
  4498. clearInterval(this.gatherStatsIntervalId);
  4499. this.gatherStatsIntervalId = null;
  4500. }
  4501. };
  4502. /**
  4503. * Callback passed to <tt>getStats</tt> method.
  4504. * @param error an error that occurred on <tt>getStats</tt> call.
  4505. */
  4506. StatsCollector.prototype.errorCallback = function (error)
  4507. {
  4508. logger.error("Get stats error", error);
  4509. this.stop();
  4510. };
  4511. /**
  4512. * Starts stats updates.
  4513. */
  4514. StatsCollector.prototype.start = function ()
  4515. {
  4516. var self = this;
  4517. this.audioLevelsIntervalId = setInterval(
  4518. function () {
  4519. // Interval updates
  4520. self.peerconnection.getStats(
  4521. function (report) {
  4522. var results = null;
  4523. if (!report || !report.result ||
  4524. typeof report.result != 'function') {
  4525. results = report;
  4526. }
  4527. else {
  4528. results = report.result();
  4529. }
  4530. //logger.error("Got interval report", results);
  4531. self.currentAudioLevelsReport = results;
  4532. self.processAudioLevelReport();
  4533. self.baselineAudioLevelsReport =
  4534. self.currentAudioLevelsReport;
  4535. },
  4536. self.errorCallback
  4537. );
  4538. },
  4539. self.audioLevelsIntervalMilis
  4540. );
  4541. // if (!this.config.disableStats && browserSupported) {
  4542. // this.statsIntervalId = setInterval(
  4543. // function () {
  4544. // // Interval updates
  4545. // self.peerconnection.getStats(
  4546. // function (report) {
  4547. // var results = null;
  4548. // if (!report || !report.result ||
  4549. // typeof report.result != 'function') {
  4550. // //firefox
  4551. // results = report;
  4552. // }
  4553. // else {
  4554. // //chrome
  4555. // results = report.result();
  4556. // }
  4557. // //logger.error("Got interval report", results);
  4558. // self.currentStatsReport = results;
  4559. // try {
  4560. // self.processStatsReport();
  4561. // }
  4562. // catch (e) {
  4563. // logger.error("Unsupported key:" + e, e);
  4564. // }
  4565. //
  4566. // self.baselineStatsReport = self.currentStatsReport;
  4567. // },
  4568. // self.errorCallback
  4569. // );
  4570. // },
  4571. // self.statsIntervalMilis
  4572. // );
  4573. // }
  4574. //
  4575. // if (this.config.logStats && browserSupported) {
  4576. // this.gatherStatsIntervalId = setInterval(
  4577. // function () {
  4578. // self.peerconnection.getStats(
  4579. // function (report) {
  4580. // self.addStatsToBeLogged(report.result());
  4581. // },
  4582. // function () {
  4583. // }
  4584. // );
  4585. // },
  4586. // this.GATHER_INTERVAL
  4587. // );
  4588. //
  4589. // this.logStatsIntervalId = setInterval(
  4590. // function() { self.logStats(); },
  4591. // this.LOG_INTERVAL);
  4592. // }
  4593. };
  4594. /**
  4595. * Converts the stats to the format used for logging, and saves the data in
  4596. * this.statsToBeLogged.
  4597. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4598. */
  4599. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4600. var self = this;
  4601. var num_records = this.statsToBeLogged.timestamps.length;
  4602. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4603. reports.map(function (report) {
  4604. if (!acceptReport(report.id, report.type))
  4605. return;
  4606. var stat = self.statsToBeLogged.stats[report.id];
  4607. if (!stat) {
  4608. stat = self.statsToBeLogged.stats[report.id] = {};
  4609. }
  4610. stat.type = report.type;
  4611. report.names().map(function (name) {
  4612. if (!acceptStat(report.id, report.type, name))
  4613. return;
  4614. var values = stat[name];
  4615. if (!values) {
  4616. values = stat[name] = [];
  4617. }
  4618. while (values.length < num_records) {
  4619. values.push(null);
  4620. }
  4621. values.push(report.stat(name));
  4622. });
  4623. });
  4624. };
  4625. //FIXME:
  4626. //StatsCollector.prototype.logStats = function () {
  4627. //
  4628. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4629. // return;
  4630. // // Reset the stats
  4631. // this.statsToBeLogged.stats = {};
  4632. // this.statsToBeLogged.timestamps = [];
  4633. //};
  4634. /**
  4635. * Stats processing logic.
  4636. */
  4637. StatsCollector.prototype.processStatsReport = function () {
  4638. if (!this.baselineStatsReport) {
  4639. return;
  4640. }
  4641. for (var idx in this.currentStatsReport) {
  4642. var now = this.currentStatsReport[idx];
  4643. try {
  4644. if (getStatValue(now, 'receiveBandwidth') ||
  4645. getStatValue(now, 'sendBandwidth')) {
  4646. this.conferenceStats.bandwidth = {
  4647. "download": Math.round(
  4648. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4649. "upload": Math.round(
  4650. (getStatValue(now, 'sendBandwidth')) / 1000)
  4651. };
  4652. }
  4653. }
  4654. catch(e){/*not supported*/}
  4655. if(now.type == 'googCandidatePair')
  4656. {
  4657. var ip, type, localIP, active;
  4658. try {
  4659. ip = getStatValue(now, 'remoteAddress');
  4660. type = getStatValue(now, "transportType");
  4661. localIP = getStatValue(now, "localAddress");
  4662. active = getStatValue(now, "activeConnection");
  4663. }
  4664. catch(e){/*not supported*/}
  4665. if(!ip || !type || !localIP || active != "true")
  4666. continue;
  4667. var addressSaved = false;
  4668. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4669. {
  4670. if(this.conferenceStats.transport[i].ip == ip &&
  4671. this.conferenceStats.transport[i].type == type &&
  4672. this.conferenceStats.transport[i].localip == localIP)
  4673. {
  4674. addressSaved = true;
  4675. }
  4676. }
  4677. if(addressSaved)
  4678. continue;
  4679. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4680. continue;
  4681. }
  4682. if(now.type == "candidatepair")
  4683. {
  4684. if(now.state == "succeeded")
  4685. continue;
  4686. var local = this.currentStatsReport[now.localCandidateId];
  4687. var remote = this.currentStatsReport[now.remoteCandidateId];
  4688. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4689. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4690. }
  4691. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4692. now.type != "inboundrtp") {
  4693. continue;
  4694. }
  4695. var before = this.baselineStatsReport[idx];
  4696. if (!before) {
  4697. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4698. continue;
  4699. }
  4700. var ssrc = getStatValue(now, 'ssrc');
  4701. if(!ssrc)
  4702. continue;
  4703. var ssrcStats = this.ssrc2stats[ssrc];
  4704. if (!ssrcStats) {
  4705. ssrcStats = new PeerStats();
  4706. this.ssrc2stats[ssrc] = ssrcStats;
  4707. }
  4708. var isDownloadStream = true;
  4709. var key = 'packetsReceived';
  4710. var packetsNow = getStatValue(now, key);
  4711. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4712. isDownloadStream = false;
  4713. key = 'packetsSent';
  4714. packetsNow = getStatValue(now, key);
  4715. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4716. console.warn("No packetsReceived nor packetsSent stat found");
  4717. continue;
  4718. }
  4719. }
  4720. if (!packetsNow || packetsNow < 0)
  4721. packetsNow = 0;
  4722. var packetsBefore = getStatValue(before, key);
  4723. if (!packetsBefore || packetsBefore < 0)
  4724. packetsBefore = 0;
  4725. var packetRate = packetsNow - packetsBefore;
  4726. if (!packetRate || packetRate < 0)
  4727. packetRate = 0;
  4728. var currentLoss = getStatValue(now, 'packetsLost');
  4729. if (!currentLoss || currentLoss < 0)
  4730. currentLoss = 0;
  4731. var previousLoss = getStatValue(before, 'packetsLost');
  4732. if (!previousLoss || previousLoss < 0)
  4733. previousLoss = 0;
  4734. var lossRate = currentLoss - previousLoss;
  4735. if (!lossRate || lossRate < 0)
  4736. lossRate = 0;
  4737. var packetsTotal = (packetRate + lossRate);
  4738. ssrcStats.setSsrcLoss(ssrc,
  4739. {"packetsTotal": packetsTotal,
  4740. "packetsLost": lossRate,
  4741. "isDownloadStream": isDownloadStream});
  4742. var bytesReceived = 0, bytesSent = 0;
  4743. if(getStatValue(now, "bytesReceived")) {
  4744. bytesReceived = getStatValue(now, "bytesReceived") -
  4745. getStatValue(before, "bytesReceived");
  4746. }
  4747. if (getStatValue(now, "bytesSent")) {
  4748. bytesSent = getStatValue(now, "bytesSent") -
  4749. getStatValue(before, "bytesSent");
  4750. }
  4751. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4752. if (bytesReceived <= 0 || time <= 0) {
  4753. bytesReceived = 0;
  4754. } else {
  4755. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4756. }
  4757. if (bytesSent <= 0 || time <= 0) {
  4758. bytesSent = 0;
  4759. } else {
  4760. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4761. }
  4762. ssrcStats.setSsrcBitrate(ssrc, {
  4763. "download": bytesReceived,
  4764. "upload": bytesSent});
  4765. var resolution = {height: null, width: null};
  4766. try {
  4767. if (getStatValue(now, "googFrameHeightReceived") &&
  4768. getStatValue(now, "googFrameWidthReceived")) {
  4769. resolution.height =
  4770. getStatValue(now, "googFrameHeightReceived");
  4771. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4772. }
  4773. else if (getStatValue(now, "googFrameHeightSent") &&
  4774. getStatValue(now, "googFrameWidthSent")) {
  4775. resolution.height = getStatValue(now, "googFrameHeightSent");
  4776. resolution.width = getStatValue(now, "googFrameWidthSent");
  4777. }
  4778. }
  4779. catch(e){/*not supported*/}
  4780. if (resolution.height && resolution.width) {
  4781. ssrcStats.setSsrcResolution(ssrc, resolution);
  4782. } else {
  4783. ssrcStats.setSsrcResolution(ssrc, null);
  4784. }
  4785. }
  4786. var self = this;
  4787. // Jid stats
  4788. var totalPackets = {download: 0, upload: 0};
  4789. var lostPackets = {download: 0, upload: 0};
  4790. var bitrateDownload = 0;
  4791. var bitrateUpload = 0;
  4792. var resolutions = {};
  4793. Object.keys(this.ssrc2stats).forEach(
  4794. function (jid) {
  4795. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4796. function (ssrc) {
  4797. var type = "upload";
  4798. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4799. type = "download";
  4800. totalPackets[type] +=
  4801. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4802. lostPackets[type] +=
  4803. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4804. }
  4805. );
  4806. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4807. function (ssrc) {
  4808. bitrateDownload +=
  4809. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4810. bitrateUpload +=
  4811. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4812. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4813. }
  4814. );
  4815. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4816. }
  4817. );
  4818. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4819. this.conferenceStats.packetLoss = {
  4820. total:
  4821. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4822. totalPackets.download + totalPackets.upload),
  4823. download:
  4824. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4825. upload:
  4826. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4827. };
  4828. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  4829. {
  4830. "bitrate": this.conferenceStats.bitrate,
  4831. "packetLoss": this.conferenceStats.packetLoss,
  4832. "bandwidth": this.conferenceStats.bandwidth,
  4833. "resolution": resolutions,
  4834. "transport": this.conferenceStats.transport
  4835. });
  4836. this.conferenceStats.transport = [];
  4837. };
  4838. /**
  4839. * Stats processing logic.
  4840. */
  4841. StatsCollector.prototype.processAudioLevelReport = function () {
  4842. if (!this.baselineAudioLevelsReport) {
  4843. return;
  4844. }
  4845. for (var idx in this.currentAudioLevelsReport) {
  4846. var now = this.currentAudioLevelsReport[idx];
  4847. //if we don't have "packetsReceived" this is local stream
  4848. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4849. continue;
  4850. }
  4851. var before = this.baselineAudioLevelsReport[idx];
  4852. if (!before) {
  4853. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4854. continue;
  4855. }
  4856. var ssrc = getStatValue(now, 'ssrc');
  4857. if (!ssrc) {
  4858. if((Date.now() - now.timestamp) < 3000)
  4859. logger.warn("No ssrc: ");
  4860. continue;
  4861. }
  4862. var ssrcStats = this.ssrc2stats[ssrc];
  4863. if (!ssrcStats) {
  4864. ssrcStats = new PeerStats();
  4865. this.ssrc2stats[ssrc] = ssrcStats;
  4866. }
  4867. // Audio level
  4868. var audioLevel = null;
  4869. try {
  4870. audioLevel = getStatValue(now, 'audioInputLevel');
  4871. if (!audioLevel)
  4872. audioLevel = getStatValue(now, 'audioOutputLevel');
  4873. }
  4874. catch(e) {/*not supported*/
  4875. logger.warn("Audio Levels are not available in the statistics.");
  4876. clearInterval(this.audioLevelsIntervalId);
  4877. return;
  4878. }
  4879. if (audioLevel) {
  4880. // TODO: can't find specs about what this value really is,
  4881. // but it seems to vary between 0 and around 32k.
  4882. audioLevel = audioLevel / 32767;
  4883. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4884. this.eventEmitter.emit(
  4885. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  4886. }
  4887. }
  4888. };
  4889. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  4890. },{"../../service/statistics/Events":83,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],24:[function(require,module,exports){
  4891. /* global require, APP */
  4892. var LocalStats = require("./LocalStatsCollector.js");
  4893. var RTPStats = require("./RTPStatsCollector.js");
  4894. var EventEmitter = require("events");
  4895. var StatisticsEvents = require("../../service/statistics/Events");
  4896. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  4897. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4898. //var CallStats = require("./CallStats");
  4899. //var RTCEvents = require("../../service/RTC/RTCEvents");
  4900. //
  4901. //function onDisposeConference(onUnload) {
  4902. // CallStats.sendTerminateEvent();
  4903. // stopRemote();
  4904. // if(onUnload) {
  4905. // stopLocal();
  4906. // eventEmitter.removeAllListeners();
  4907. // }
  4908. //}
  4909. var eventEmitter = new EventEmitter();
  4910. function Statistics() {
  4911. this.rtpStats = null;
  4912. this.eventEmitter = new EventEmitter();
  4913. }
  4914. Statistics.prototype.startRemoteStats = function (peerconnection) {
  4915. if (this.rtpStats) {
  4916. this.rtpStats.stop();
  4917. }
  4918. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  4919. this.rtpStats.start();
  4920. }
  4921. Statistics.localStats = [];
  4922. Statistics.startLocalStats = function (stream, callback) {
  4923. var localStats = new LocalStats(stream, 200, callback);
  4924. this.localStats.push(localStats);
  4925. localStats.start();
  4926. }
  4927. Statistics.prototype.addAudioLevelListener = function(listener)
  4928. {
  4929. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  4930. }
  4931. Statistics.prototype.removeAudioLevelListener = function(listener)
  4932. {
  4933. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  4934. }
  4935. Statistics.prototype.dispose = function () {
  4936. Statistics.stopAllLocalStats();
  4937. this.stopRemote();
  4938. if(this.eventEmitter)
  4939. this.eventEmitter.removeAllListeners();
  4940. if(eventEmitter)
  4941. eventEmitter.removeAllListeners();
  4942. }
  4943. Statistics.stopAllLocalStats = function () {
  4944. for(var i = 0; i < this.localStats.length; i++)
  4945. this.localStats[i].stop();
  4946. this.localStats = [];
  4947. }
  4948. Statistics.stopLocalStats = function (stream) {
  4949. for(var i = 0; i < Statistics.localStats.length; i++)
  4950. if(Statistics.localStats[i].stream === stream){
  4951. var localStats = Statistics.localStats.splice(i, 1);
  4952. localStats.stop();
  4953. break;
  4954. }
  4955. }
  4956. Statistics.prototype.stopRemote = function () {
  4957. if (this.rtpStats) {
  4958. this.rtpStats.stop();
  4959. this.eventEmitter.emit(StatisticsEvents.STOP);
  4960. this.rtpStats = null;
  4961. }
  4962. };
  4963. /**
  4964. * Obtains audio level reported in the stats for specified peer.
  4965. * @param peerJid full MUC jid of the user for whom we want to obtain last
  4966. * audio level.
  4967. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  4968. * level.
  4969. * @returns {*} a float form 0 to 1 that represents current audio level or
  4970. * <tt>null</tt> if for any reason the value is not available
  4971. * at this time.
  4972. */
  4973. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  4974. var peerStats = this.rtpStats.jid2stats[peerJid];
  4975. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  4976. };
  4977. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  4978. //
  4979. //var statistics = {
  4980. // /**
  4981. // * Indicates that this audio level is for local jid.
  4982. // * @type {string}
  4983. // */
  4984. // LOCAL_JID: 'local',
  4985. //
  4986. // addConnectionStatsListener: function(listener)
  4987. // {
  4988. // eventEmitter.on("statistics.connectionstats", listener);
  4989. // },
  4990. //
  4991. // removeConnectionStatsListener: function(listener)
  4992. // {
  4993. // eventEmitter.removeListener("statistics.connectionstats", listener);
  4994. // },
  4995. //
  4996. //
  4997. // addRemoteStatsStopListener: function(listener)
  4998. // {
  4999. // eventEmitter.on("statistics.stop", listener);
  5000. // },
  5001. //
  5002. // removeRemoteStatsStopListener: function(listener)
  5003. // {
  5004. // eventEmitter.removeListener("statistics.stop", listener);
  5005. // },
  5006. //
  5007. //
  5008. // stopRemoteStatistics: function()
  5009. // {
  5010. // stopRemote();
  5011. // },
  5012. //
  5013. //// Already implemented with the constructor
  5014. // start: function () {
  5015. // APP.RTC.addStreamListener(onStreamCreated,
  5016. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  5017. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  5018. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  5019. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  5020. // startRemoteStats(event.peerconnection);
  5021. //// CallStats.init(event);
  5022. // });
  5023. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  5024. //// CallStats.init(session);
  5025. //// });
  5026. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5027. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  5028. //// CallStats.sendMuteEvent(mute, "audio");
  5029. //// });
  5030. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  5031. //// CallStats.sendSetupFailedEvent();
  5032. //// });
  5033. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  5034. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  5035. //// CallStats.sendMuteEvent(mute, "video");
  5036. //// });
  5037. // }
  5038. //};
  5039. module.exports = Statistics;
  5040. },{"../../service/statistics/Events":83,"../../service/statistics/constants":84,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":43}],25:[function(require,module,exports){
  5041. /**
  5042. /**
  5043. * @const
  5044. */
  5045. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5046. /**
  5047. * Hexadecimal digits.
  5048. * @const
  5049. */
  5050. var HEX_DIGITS = '0123456789abcdef';
  5051. /**
  5052. * Generates random int within the range [min, max]
  5053. * @param min the minimum value for the generated number
  5054. * @param max the maximum value for the generated number
  5055. * @returns random int number
  5056. */
  5057. function randomInt(min, max) {
  5058. return Math.floor(Math.random() * (max - min + 1)) + min;
  5059. }
  5060. /**
  5061. * Get random element from array or string.
  5062. * @param {Array|string} arr source
  5063. * @returns array element or string character
  5064. */
  5065. function randomElement(arr) {
  5066. return arr[randomInt(0, arr.length - 1)];
  5067. }
  5068. /**
  5069. * Generate random alphanumeric string.
  5070. * @param {number} length expected string length
  5071. * @returns {string} random string of specified length
  5072. */
  5073. function randomAlphanumStr(length) {
  5074. var result = '';
  5075. for (var i = 0; i < length; i += 1) {
  5076. result += randomElement(ALPHANUM);
  5077. }
  5078. return result;
  5079. }
  5080. /**
  5081. * Exported interface.
  5082. */
  5083. var RandomUtil = {
  5084. /**
  5085. * Returns a random hex digit.
  5086. * @returns {*}
  5087. */
  5088. randomHexDigit: function() {
  5089. return randomElement(HEX_DIGITS);
  5090. },
  5091. /**
  5092. * Returns a random string of hex digits with length 'len'.
  5093. * @param len the length.
  5094. */
  5095. randomHexString: function (len) {
  5096. var ret = '';
  5097. while (len--) {
  5098. ret += this.randomHexDigit();
  5099. }
  5100. return ret;
  5101. },
  5102. randomElement: randomElement,
  5103. randomAlphanumStr: randomAlphanumStr
  5104. };
  5105. module.exports = RandomUtil;
  5106. },{}],26:[function(require,module,exports){
  5107. (function (__filename){
  5108. /* global Strophe, $, $pres, $iq, $msg */
  5109. /* jshint -W101,-W069 */
  5110. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5111. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5112. var Moderator = require("./moderator");
  5113. var EventEmitter = require("events");
  5114. var parser = {
  5115. packet2JSON: function (packet, nodes) {
  5116. var self = this;
  5117. $(packet).children().each(function (index) {
  5118. var tagName = $(this).prop("tagName");
  5119. var node = {
  5120. tagName: tagName
  5121. };
  5122. node.attributes = {};
  5123. $($(this)[0].attributes).each(function( index, attr ) {
  5124. node.attributes[ attr.name ] = attr.value;
  5125. });
  5126. var text = Strophe.getText($(this)[0]);
  5127. if (text) {
  5128. node.value = text;
  5129. }
  5130. node.children = [];
  5131. nodes.push(node);
  5132. self.packet2JSON($(this), node.children);
  5133. });
  5134. },
  5135. JSON2packet: function (nodes, packet) {
  5136. for(var i = 0; i < nodes.length; i++) {
  5137. var node = nodes[i];
  5138. if(!node || node === null){
  5139. continue;
  5140. }
  5141. packet.c(node.tagName, node.attributes);
  5142. if(node.value)
  5143. packet.t(node.value);
  5144. if(node.children)
  5145. this.JSON2packet(node.children, packet);
  5146. packet.up();
  5147. }
  5148. // packet.up();
  5149. }
  5150. };
  5151. /**
  5152. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  5153. * @param pres the presence JSON
  5154. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  5155. */
  5156. function filterNodeFromPresenceJSON(pres, nodeName){
  5157. var res = [];
  5158. for(var i = 0; i < pres.length; i++)
  5159. if(pres[i].tagName === nodeName)
  5160. res.push(pres[i]);
  5161. return res;
  5162. }
  5163. function ChatRoom(connection, jid, password, XMPP, options) {
  5164. this.eventEmitter = new EventEmitter();
  5165. this.xmpp = XMPP;
  5166. this.connection = connection;
  5167. this.roomjid = Strophe.getBareJidFromJid(jid);
  5168. this.myroomjid = jid;
  5169. this.password = password;
  5170. logger.info("Joined MUC as " + this.myroomjid);
  5171. this.members = {};
  5172. this.presMap = {};
  5173. this.presHandlers = {};
  5174. this.joined = false;
  5175. this.role = 'none';
  5176. this.focusMucJid = null;
  5177. this.bridgeIsDown = false;
  5178. this.options = options || {};
  5179. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5180. this.initPresenceMap();
  5181. this.session = null;
  5182. var self = this;
  5183. this.lastPresences = {};
  5184. }
  5185. ChatRoom.prototype.initPresenceMap = function () {
  5186. this.presMap['to'] = this.myroomjid;
  5187. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5188. this.presMap["nodes"] = [];
  5189. this.presMap["nodes"].push( {
  5190. "tagName": "user-agent",
  5191. "value": navigator.userAgent,
  5192. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5193. });
  5194. };
  5195. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5196. this.presMap["nodes"].push( {
  5197. "tagName": "devices",
  5198. "children": [
  5199. {
  5200. "tagName": "audio",
  5201. "value": devices.audio,
  5202. },
  5203. {
  5204. "tagName": "video",
  5205. "value": devices.video,
  5206. }
  5207. ]
  5208. });
  5209. };
  5210. ChatRoom.prototype.join = function (password, tokenPassword) {
  5211. if(password)
  5212. this.password = password;
  5213. var self = this;
  5214. this.moderator.allocateConferenceFocus(function()
  5215. {
  5216. self.sendPresence(tokenPassword);
  5217. }.bind(this));
  5218. };
  5219. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  5220. if (!this.presMap['to']) {
  5221. // Too early to send presence - not initialized
  5222. return;
  5223. }
  5224. var pres = $pres({to: this.presMap['to'] });
  5225. pres.c('x', {xmlns: this.presMap['xns']});
  5226. if (this.password) {
  5227. pres.c('password').t(this.password).up();
  5228. }
  5229. pres.up();
  5230. // Send XEP-0115 'c' stanza that contains our capabilities info
  5231. if (this.connection.caps) {
  5232. this.connection.caps.node = this.xmpp.options.clientNode;
  5233. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5234. }
  5235. if (tokenPassword) {
  5236. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  5237. .t(tokenPassword).up();
  5238. }
  5239. parser.JSON2packet(this.presMap.nodes, pres);
  5240. this.connection.send(pres);
  5241. };
  5242. ChatRoom.prototype.doLeave = function () {
  5243. logger.log("do leave", this.myroomjid);
  5244. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5245. this.presMap.length = 0;
  5246. this.connection.send(pres);
  5247. };
  5248. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5249. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5250. var getForm = $iq({type: 'get', to: this.roomjid})
  5251. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5252. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5253. var self = this;
  5254. this.connection.sendIQ(getForm, function (form) {
  5255. if (!$(form).find(
  5256. '>query>x[xmlns="jabber:x:data"]' +
  5257. '>field[var="muc#roomconfig_whois"]').length) {
  5258. logger.error('non-anonymous rooms not supported');
  5259. return;
  5260. }
  5261. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5262. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5263. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5264. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5265. .c('value')
  5266. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5267. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5268. .c('value').t('anyone').up().up();
  5269. self.connection.sendIQ(formSubmit);
  5270. }, function (error) {
  5271. logger.error("Error getting room configuration form");
  5272. });
  5273. };
  5274. ChatRoom.prototype.onPresence = function (pres) {
  5275. var from = pres.getAttribute('from');
  5276. // Parse roles.
  5277. var member = {};
  5278. member.show = $(pres).find('>show').text();
  5279. member.status = $(pres).find('>status').text();
  5280. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5281. member.affiliation = tmp.attr('affiliation');
  5282. member.role = tmp.attr('role');
  5283. // Focus recognition
  5284. member.jid = tmp.attr('jid');
  5285. member.isFocus = false;
  5286. if (member.jid
  5287. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  5288. member.isFocus = true;
  5289. }
  5290. $(pres).find(">x").remove();
  5291. var nodes = [];
  5292. parser.packet2JSON(pres, nodes);
  5293. this.lastPresences[from] = nodes;
  5294. for(var i = 0; i < nodes.length; i++)
  5295. {
  5296. var node = nodes[i];
  5297. switch(node.tagName)
  5298. {
  5299. case "nick":
  5300. member.nick = node.value;
  5301. if(!member.isFocus) {
  5302. var displayName = !this.xmpp.options.displayJids
  5303. ? member.nick : Strophe.getResourceFromJid(from);
  5304. if (displayName && displayName.length > 0) {
  5305. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5306. }
  5307. logger.info("Display name: " + displayName, pres);
  5308. }
  5309. break;
  5310. case "userId":
  5311. member.id = node.value;
  5312. break;
  5313. case "email":
  5314. member.email = node.value;
  5315. break;
  5316. case "bridgeIsDown":
  5317. if(!this.bridgeIsDown) {
  5318. this.bridgeIsDown = true;
  5319. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5320. }
  5321. break;
  5322. default :
  5323. this.processNode(node, from);
  5324. }
  5325. }
  5326. if (from == this.myroomjid) {
  5327. if (member.affiliation == 'owner')
  5328. if (this.role !== member.role) {
  5329. this.role = member.role;
  5330. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  5331. }
  5332. if (!this.joined) {
  5333. this.joined = true;
  5334. console.log("(TIME) MUC joined:\t", window.performance.now());
  5335. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  5336. }
  5337. } else if (this.members[from] === undefined) {
  5338. // new participant
  5339. this.members[from] = member;
  5340. logger.log('entered', from, member);
  5341. if (member.isFocus) {
  5342. this.focusMucJid = from;
  5343. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5344. }
  5345. else {
  5346. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  5347. }
  5348. } else {
  5349. // Presence update for existing participant
  5350. // Watch role change:
  5351. if (this.members[from].role != member.role) {
  5352. this.members[from].role = member.role;
  5353. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  5354. }
  5355. // store the new display name
  5356. if(member.displayName)
  5357. this.members[from].displayName = member.displayName;
  5358. }
  5359. if(!member.isFocus)
  5360. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  5361. // Trigger status message update
  5362. if (member.status) {
  5363. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5364. }
  5365. };
  5366. ChatRoom.prototype.processNode = function (node, from) {
  5367. if(this.presHandlers[node.tagName])
  5368. this.presHandlers[node.tagName](node, from);
  5369. };
  5370. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5371. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5372. msg.c('body', body).up();
  5373. if (nickname) {
  5374. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5375. }
  5376. this.connection.send(msg);
  5377. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5378. };
  5379. ChatRoom.prototype.setSubject = function (subject) {
  5380. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5381. msg.c('subject', subject);
  5382. this.connection.send(msg);
  5383. logger.log("topic changed to " + subject);
  5384. };
  5385. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5386. delete this.lastPresences[jid];
  5387. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5388. this.moderator.onMucMemberLeft(jid);
  5389. };
  5390. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5391. // room destroyed ?
  5392. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5393. '>destroy').length) {
  5394. var reason;
  5395. var reasonSelect = $(pres).find(
  5396. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5397. '>destroy>reason');
  5398. if (reasonSelect.length) {
  5399. reason = reasonSelect.text();
  5400. }
  5401. this.xmpp.disposeConference(false);
  5402. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5403. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  5404. return true;
  5405. }
  5406. // Status code 110 indicates that this notification is "self-presence".
  5407. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5408. delete this.members[from];
  5409. this.onParticipantLeft(from);
  5410. }
  5411. // If the status code is 110 this means we're leaving and we would like
  5412. // to remove everyone else from our view, so we trigger the event.
  5413. else if (Object.keys(this.members).length > 1) {
  5414. for (var i in this.members) {
  5415. var member = this.members[i];
  5416. delete this.members[i];
  5417. this.onParticipantLeft(member);
  5418. }
  5419. }
  5420. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5421. if (this.myroomjid === from) {
  5422. this.xmpp.disposeConference(false);
  5423. this.eventEmitter.emit(XMPPEvents.KICKED);
  5424. }
  5425. }
  5426. };
  5427. ChatRoom.prototype.onMessage = function (msg, from) {
  5428. var nick =
  5429. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5430. .text() ||
  5431. Strophe.getResourceFromJid(from);
  5432. var txt = $(msg).find('>body').text();
  5433. var type = msg.getAttribute("type");
  5434. if (type == "error") {
  5435. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5436. $(msg).find('>text').text(), txt);
  5437. return true;
  5438. }
  5439. var subject = $(msg).find('>subject');
  5440. if (subject.length) {
  5441. var subjectText = subject.text();
  5442. if (subjectText || subjectText === "") {
  5443. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5444. logger.log("Subject is changed to " + subjectText);
  5445. }
  5446. }
  5447. // xep-0203 delay
  5448. var stamp = $(msg).find('>delay').attr('stamp');
  5449. if (!stamp) {
  5450. // or xep-0091 delay, UTC timestamp
  5451. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5452. if (stamp) {
  5453. // the format is CCYYMMDDThh:mm:ss
  5454. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5455. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5456. }
  5457. }
  5458. if (txt) {
  5459. logger.log('chat', nick, txt);
  5460. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5461. from, nick, txt, this.myroomjid, stamp);
  5462. }
  5463. };
  5464. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5465. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5466. logger.log('on password required', from);
  5467. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5468. } else if ($(pres).find(
  5469. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5470. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5471. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5472. // enter the room by replying with 'not-authorized'. This would
  5473. // result in reconnection from authorized domain.
  5474. // We're either missing Jicofo/Prosody config for anonymous
  5475. // domains or something is wrong.
  5476. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5477. } else {
  5478. logger.warn('onPresError ', pres);
  5479. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5480. }
  5481. } else {
  5482. logger.warn('onPresError ', pres);
  5483. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5484. }
  5485. };
  5486. ChatRoom.prototype.kick = function (jid) {
  5487. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5488. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5489. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5490. .c('reason').t('You have been kicked.').up().up().up();
  5491. this.connection.sendIQ(
  5492. kickIQ,
  5493. function (result) {
  5494. logger.log('Kick participant with jid: ', jid, result);
  5495. },
  5496. function (error) {
  5497. logger.log('Kick participant error: ', error);
  5498. });
  5499. };
  5500. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5501. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5502. var ob = this;
  5503. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5504. function (res) {
  5505. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5506. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5507. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5508. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5509. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5510. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5511. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5512. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5513. ob.connection.sendIQ(formsubmit,
  5514. onSuccess,
  5515. onError);
  5516. } else {
  5517. onNotSupported();
  5518. }
  5519. }, onError);
  5520. };
  5521. ChatRoom.prototype.addToPresence = function (key, values) {
  5522. values.tagName = key;
  5523. this.presMap["nodes"].push(values);
  5524. };
  5525. ChatRoom.prototype.removeFromPresence = function (key) {
  5526. for(var i = 0; i < this.presMap.nodes.length; i++)
  5527. {
  5528. if(key === this.presMap.nodes[i].tagName)
  5529. this.presMap.nodes.splice(i, 1);
  5530. }
  5531. };
  5532. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5533. this.presHandlers[name] = handler;
  5534. };
  5535. ChatRoom.prototype.removePresenceListener = function (name) {
  5536. delete this.presHandlers[name];
  5537. };
  5538. ChatRoom.prototype.isModerator = function () {
  5539. return this.role === 'moderator';
  5540. };
  5541. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5542. if (this.members[peerJid]) {
  5543. return this.members[peerJid].role;
  5544. }
  5545. return null;
  5546. };
  5547. ChatRoom.prototype.setJingleSession = function(session){
  5548. this.session = session;
  5549. this.session.room = this;
  5550. };
  5551. ChatRoom.prototype.removeStream = function (stream, callback) {
  5552. if(!this.session)
  5553. return;
  5554. this.session.removeStream(stream, callback);
  5555. };
  5556. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5557. if(this.session) {
  5558. // FIXME: will block switchInProgress on true value in case of exception
  5559. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5560. } else {
  5561. // We are done immediately
  5562. logger.warn("No conference handler or conference not started yet");
  5563. callback();
  5564. }
  5565. };
  5566. ChatRoom.prototype.addStream = function (stream, callback) {
  5567. if(this.session) {
  5568. // FIXME: will block switchInProgress on true value in case of exception
  5569. this.session.addStream(stream, callback);
  5570. } else {
  5571. // We are done immediately
  5572. logger.warn("No conference handler or conference not started yet");
  5573. callback();
  5574. }
  5575. };
  5576. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5577. var self = this;
  5578. var localCallback = function (mute) {
  5579. self.sendVideoInfoPresence(mute);
  5580. if(callback)
  5581. callback(mute);
  5582. };
  5583. if(this.session)
  5584. {
  5585. this.session.setVideoMute(
  5586. mute, localCallback, options);
  5587. }
  5588. else {
  5589. localCallback(mute);
  5590. }
  5591. };
  5592. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5593. //This will be for remote streams only
  5594. // if (this.forceMuted && !mute) {
  5595. // logger.info("Asking focus for unmute");
  5596. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5597. // // FIXME: wait for result before resetting muted status
  5598. // this.forceMuted = false;
  5599. // }
  5600. return this.sendAudioInfoPresence(mute, callback);
  5601. };
  5602. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5603. this.removeFromPresence("audiomuted");
  5604. this.addToPresence("audiomuted",
  5605. {attributes:
  5606. {"audions": "http://jitsi.org/jitmeet/audio"},
  5607. value: mute.toString()});
  5608. };
  5609. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5610. this.addAudioInfoToPresence(mute);
  5611. if(this.connection) {
  5612. this.sendPresence();
  5613. }
  5614. if(callback)
  5615. callback();
  5616. };
  5617. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5618. this.removeFromPresence("videomuted");
  5619. this.addToPresence("videomuted",
  5620. {attributes:
  5621. {"videons": "http://jitsi.org/jitmeet/video"},
  5622. value: mute.toString()});
  5623. };
  5624. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5625. this.addVideoInfoToPresence(mute);
  5626. if(!this.connection)
  5627. return;
  5628. this.sendPresence();
  5629. };
  5630. ChatRoom.prototype.addListener = function(type, listener) {
  5631. this.eventEmitter.on(type, listener);
  5632. };
  5633. ChatRoom.prototype.removeListener = function (type, listener) {
  5634. this.eventEmitter.removeListener(type, listener);
  5635. };
  5636. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5637. if(this.lastPresences[data.peerjid])
  5638. {
  5639. var pres = this.lastPresences[data.peerjid];
  5640. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5641. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5642. data.videomuted = ((videomuted.length > 0
  5643. && videomuted[0]
  5644. && videomuted[0]["value"] === "true")? true : false);
  5645. data.audiomuted = ((audiomuted.length > 0
  5646. && audiomuted[0]
  5647. && audiomuted[0]["value"] === "true")? true : false);
  5648. }
  5649. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5650. };
  5651. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5652. if (!this.session)
  5653. return null;
  5654. return this.session.getSsrcOwner(ssrc);
  5655. };
  5656. module.exports = ChatRoom;
  5657. }).call(this,"/modules/xmpp/ChatRoom.js")
  5658. },{"../../service/xmpp/XMPPEvents":85,"./moderator":34,"events":43,"jitsi-meet-logger":47}],27:[function(require,module,exports){
  5659. (function (__filename){
  5660. /*
  5661. * JingleSession provides an API to manage a single Jingle session. We will
  5662. * have different implementations depending on the underlying interface used
  5663. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  5664. */
  5665. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5666. function JingleSession(me, sid, connection, service, eventEmitter) {
  5667. /**
  5668. * Our JID.
  5669. */
  5670. this.me = me;
  5671. /**
  5672. * The Jingle session identifier.
  5673. */
  5674. this.sid = sid;
  5675. /**
  5676. * The XMPP connection.
  5677. */
  5678. this.connection = connection;
  5679. /**
  5680. * The XMPP service.
  5681. */
  5682. this.service = service;
  5683. /**
  5684. * The event emitter.
  5685. */
  5686. this.eventEmitter = eventEmitter;
  5687. /**
  5688. * Whether to use dripping or not. Dripping is sending trickle candidates
  5689. * not one-by-one.
  5690. * Note: currently we do not support 'false'.
  5691. */
  5692. this.usedrip = true;
  5693. /**
  5694. * When dripping is used, stores ICE candidates which are to be sent.
  5695. */
  5696. this.drip_container = [];
  5697. // Media constraints. Is this WebRTC only?
  5698. this.media_constraints = null;
  5699. // ICE servers config (RTCConfiguration?).
  5700. this.ice_config = {};
  5701. // The chat room instance associated with the session.
  5702. this.room = null;
  5703. }
  5704. /**
  5705. * Prepares this object to initiate a session.
  5706. * @param peerjid the JID of the remote peer.
  5707. * @param isInitiator whether we will be the Jingle initiator.
  5708. * @param media_constraints
  5709. * @param ice_config
  5710. */
  5711. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5712. media_constraints, ice_config) {
  5713. this.media_constraints = media_constraints;
  5714. this.ice_config = ice_config;
  5715. if (this.state !== null) {
  5716. logger.error('attempt to initiate on session ' + this.sid +
  5717. 'in state ' + this.state);
  5718. return;
  5719. }
  5720. this.state = 'pending';
  5721. this.initiator = isInitiator ? this.me : peerjid;
  5722. this.responder = !isInitiator ? this.me : peerjid;
  5723. this.peerjid = peerjid;
  5724. this.doInitialize();
  5725. };
  5726. /**
  5727. * Finishes initialization.
  5728. */
  5729. JingleSession.prototype.doInitialize = function() {};
  5730. /**
  5731. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5732. * Note: currently only used on transport-info
  5733. */
  5734. JingleSession.prototype.addIceCandidates = function(contents) {};
  5735. /**
  5736. * Handles an 'add-source' event.
  5737. *
  5738. * @param contents an array of Jingle 'content' elements.
  5739. */
  5740. JingleSession.prototype.addSources = function(contents) {};
  5741. /**
  5742. * Handles a 'remove-source' event.
  5743. *
  5744. * @param contents an array of Jingle 'content' elements.
  5745. */
  5746. JingleSession.prototype.removeSources = function(contents) {};
  5747. /**
  5748. * Terminates this Jingle session (stops sending media and closes the streams?)
  5749. */
  5750. JingleSession.prototype.terminate = function() {};
  5751. /**
  5752. * Sends a Jingle session-terminate message to the peer and terminates the
  5753. * session.
  5754. * @param reason
  5755. * @param text
  5756. */
  5757. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5758. /**
  5759. * Handles an offer from the remote peer (prepares to accept a session).
  5760. * @param jingle the 'jingle' XML element.
  5761. */
  5762. JingleSession.prototype.setOffer = function(jingle) {};
  5763. /**
  5764. * Handles an answer from the remote peer (prepares to accept a session).
  5765. * @param jingle the 'jingle' XML element.
  5766. */
  5767. JingleSession.prototype.setAnswer = function(jingle) {};
  5768. module.exports = JingleSession;
  5769. }).call(this,"/modules/xmpp/JingleSession.js")
  5770. },{"jitsi-meet-logger":47}],28:[function(require,module,exports){
  5771. (function (__filename){
  5772. /* jshint -W117 */
  5773. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5774. var JingleSession = require("./JingleSession");
  5775. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5776. var SDPDiffer = require("./SDPDiffer");
  5777. var SDPUtil = require("./SDPUtil");
  5778. var SDP = require("./SDP");
  5779. var async = require("async");
  5780. var transform = require("sdp-transform");
  5781. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5782. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5783. var SSRCReplacement = require("./LocalSSRCReplacement");
  5784. var RTC = require("../RTC/RTC");
  5785. // Jingle stuff
  5786. function JingleSessionPC(me, sid, connection, service) {
  5787. JingleSession.call(this, me, sid, connection, service);
  5788. this.initiator = null;
  5789. this.responder = null;
  5790. this.peerjid = null;
  5791. this.state = null;
  5792. this.localSDP = null;
  5793. this.remoteSDP = null;
  5794. this.relayedStreams = [];
  5795. this.usetrickle = true;
  5796. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5797. this.hadstuncandidate = false;
  5798. this.hadturncandidate = false;
  5799. this.lasticecandidate = false;
  5800. this.statsinterval = null;
  5801. this.reason = null;
  5802. this.addssrc = [];
  5803. this.removessrc = [];
  5804. this.pendingop = null;
  5805. this.switchstreams = false;
  5806. this.addingStreams = false;
  5807. this.wait = true;
  5808. /**
  5809. * A map that stores SSRCs of local streams
  5810. * @type {{}} maps media type('audio' or 'video') to SSRC number
  5811. */
  5812. this.localStreamsSSRC = {};
  5813. this.ssrcOwners = {};
  5814. this.ssrcVideoTypes = {};
  5815. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  5816. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  5817. /**
  5818. * The indicator which determines whether the (local) video has been muted
  5819. * in response to a user command in contrast to an automatic decision made
  5820. * by the application logic.
  5821. */
  5822. this.videoMuteByUser = false;
  5823. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5824. // We start with the queue paused. We resume it when the signaling state is
  5825. // stable and the ice connection state is connected.
  5826. this.modifySourcesQueue.pause();
  5827. }
  5828. //XXX this is badly broken...
  5829. JingleSessionPC.prototype = JingleSession.prototype;
  5830. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5831. JingleSessionPC.prototype.setOffer = function(offer) {
  5832. this.setRemoteDescription(offer, 'offer');
  5833. };
  5834. JingleSessionPC.prototype.setAnswer = function(answer) {
  5835. this.setRemoteDescription(answer, 'answer');
  5836. };
  5837. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5838. var signalingState = this.peerconnection.signalingState;
  5839. var iceConnectionState = this.peerconnection.iceConnectionState;
  5840. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5841. this.modifySourcesQueue.resume();
  5842. } else {
  5843. this.modifySourcesQueue.pause();
  5844. }
  5845. };
  5846. JingleSessionPC.prototype.doInitialize = function () {
  5847. var self = this;
  5848. this.hadstuncandidate = false;
  5849. this.hadturncandidate = false;
  5850. this.lasticecandidate = false;
  5851. // True if reconnect is in progress
  5852. this.isreconnect = false;
  5853. // Set to true if the connection was ever stable
  5854. this.wasstable = false;
  5855. this.peerconnection = new TraceablePeerConnection(
  5856. this.connection.jingle.ice_config,
  5857. RTC.getPCConstraints(),
  5858. this);
  5859. this.peerconnection.onicecandidate = function (event) {
  5860. var protocol;
  5861. if (event && event.candidate) {
  5862. protocol = (typeof event.candidate.protocol === 'string')
  5863. ? event.candidate.protocol.toLowerCase() : '';
  5864. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  5865. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  5866. return;
  5867. }
  5868. }
  5869. self.sendIceCandidate(event.candidate);
  5870. };
  5871. this.peerconnection.onaddstream = function (event) {
  5872. if (event.stream.id !== 'default') {
  5873. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  5874. self.remoteStreamAdded(event);
  5875. } else {
  5876. // This is a recvonly stream. Clients that implement Unified Plan,
  5877. // such as Firefox use recvonly "streams/channels/tracks" for
  5878. // receiving remote stream/tracks, as opposed to Plan B where there
  5879. // are only 3 channels: audio, video and data.
  5880. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  5881. }
  5882. };
  5883. this.peerconnection.onremovestream = function (event) {
  5884. // Remove the stream from remoteStreams
  5885. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  5886. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  5887. };
  5888. this.peerconnection.onsignalingstatechange = function (event) {
  5889. if (!(self && self.peerconnection)) return;
  5890. if (self.peerconnection.signalingState === 'stable') {
  5891. self.wasstable = true;
  5892. }
  5893. self.updateModifySourcesQueue();
  5894. };
  5895. /**
  5896. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  5897. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  5898. * RTCPeerConnection.iceConnectionState changes.
  5899. *
  5900. * @param event the event containing information about the change
  5901. */
  5902. this.peerconnection.oniceconnectionstatechange = function (event) {
  5903. if (!(self && self.peerconnection)) return;
  5904. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  5905. ":\t", window.performance.now());
  5906. self.updateModifySourcesQueue();
  5907. switch (self.peerconnection.iceConnectionState) {
  5908. case 'connected':
  5909. // Informs interested parties that the connection has been restored.
  5910. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  5911. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  5912. self.isreconnect = false;
  5913. break;
  5914. case 'disconnected':
  5915. self.isreconnect = true;
  5916. // Informs interested parties that the connection has been interrupted.
  5917. if (self.wasstable)
  5918. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  5919. break;
  5920. case 'failed':
  5921. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5922. break;
  5923. }
  5924. onIceConnectionStateChange(self.sid, self);
  5925. };
  5926. this.peerconnection.onnegotiationneeded = function (event) {
  5927. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  5928. };
  5929. this.relayedStreams.forEach(function(stream) {
  5930. self.peerconnection.addStream(stream);
  5931. });
  5932. };
  5933. function onIceConnectionStateChange(sid, session) {
  5934. switch (session.peerconnection.iceConnectionState) {
  5935. case 'checking':
  5936. session.timeChecking = (new Date()).getTime();
  5937. session.firstconnect = true;
  5938. break;
  5939. case 'completed': // on caller side
  5940. case 'connected':
  5941. if (session.firstconnect) {
  5942. session.firstconnect = false;
  5943. var metadata = {};
  5944. metadata.setupTime
  5945. = (new Date()).getTime() - session.timeChecking;
  5946. session.peerconnection.getStats(function (res) {
  5947. if(res && res.result) {
  5948. res.result().forEach(function (report) {
  5949. if (report.type == 'googCandidatePair' &&
  5950. report.stat('googActiveConnection') == 'true') {
  5951. metadata.localCandidateType
  5952. = report.stat('googLocalCandidateType');
  5953. metadata.remoteCandidateType
  5954. = report.stat('googRemoteCandidateType');
  5955. // log pair as well so we can get nice pie
  5956. // charts
  5957. metadata.candidatePair
  5958. = report.stat('googLocalCandidateType') +
  5959. ';' +
  5960. report.stat('googRemoteCandidateType');
  5961. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  5962. {
  5963. metadata.ipv6 = true;
  5964. }
  5965. }
  5966. });
  5967. }
  5968. });
  5969. }
  5970. break;
  5971. }
  5972. }
  5973. JingleSessionPC.prototype.accept = function () {
  5974. this.state = 'active';
  5975. var pranswer = this.peerconnection.localDescription;
  5976. if (!pranswer || pranswer.type != 'pranswer') {
  5977. return;
  5978. }
  5979. logger.log('going from pranswer to answer');
  5980. if (this.usetrickle) {
  5981. // remove candidates already sent from session-accept
  5982. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  5983. for (var i = 0; i < lines.length; i++) {
  5984. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  5985. }
  5986. }
  5987. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  5988. // FIXME: change any inactive to sendrecv or whatever they were originally
  5989. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  5990. }
  5991. var prsdp = new SDP(pranswer.sdp);
  5992. if (self.webrtcIceTcpDisable) {
  5993. prsdp.removeTcpCandidates = true;
  5994. }
  5995. if (self.webrtcIceUdpDisable) {
  5996. prsdp.removeUdpCandidates = true;
  5997. }
  5998. var accept = $iq({to: this.peerjid,
  5999. type: 'set'})
  6000. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6001. action: 'session-accept',
  6002. initiator: this.initiator,
  6003. responder: this.responder,
  6004. sid: this.sid });
  6005. // FIXME why do we generate session-accept in 3 different places ?
  6006. prsdp.toJingle(
  6007. accept,
  6008. this.initiator == this.me ? 'initiator' : 'responder');
  6009. var sdp = this.peerconnection.localDescription.sdp;
  6010. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  6011. // FIXME: change any inactive to sendrecv or whatever they were originally
  6012. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  6013. }
  6014. var self = this;
  6015. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  6016. function () {
  6017. //logger.log('setLocalDescription success');
  6018. self.setLocalDescription();
  6019. SSRCReplacement.processSessionInit(accept);
  6020. self.connection.sendIQ(accept,
  6021. function () {
  6022. var ack = {};
  6023. ack.source = 'answer';
  6024. $(document).trigger('ack.jingle', [self.sid, ack]);
  6025. },
  6026. function (stanza) {
  6027. var error = ($(stanza).find('error').length) ? {
  6028. code: $(stanza).find('error').attr('code'),
  6029. reason: $(stanza).find('error :first')[0].tagName
  6030. }:{};
  6031. error.source = 'answer';
  6032. JingleSessionPC.onJingleError(self.sid, error);
  6033. },
  6034. 10000);
  6035. },
  6036. function (e) {
  6037. logger.error('setLocalDescription failed', e);
  6038. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6039. }
  6040. );
  6041. };
  6042. JingleSessionPC.prototype.terminate = function (reason) {
  6043. this.state = 'ended';
  6044. this.reason = reason;
  6045. this.peerconnection.close();
  6046. if (this.statsinterval !== null) {
  6047. window.clearInterval(this.statsinterval);
  6048. this.statsinterval = null;
  6049. }
  6050. };
  6051. JingleSessionPC.prototype.active = function () {
  6052. return this.state == 'active';
  6053. };
  6054. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  6055. var self = this;
  6056. if (candidate && !this.lasticecandidate) {
  6057. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  6058. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  6059. if (!(ice && jcand)) {
  6060. logger.error('failed to get ice && jcand');
  6061. return;
  6062. }
  6063. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6064. if (jcand.type === 'srflx') {
  6065. this.hadstuncandidate = true;
  6066. } else if (jcand.type === 'relay') {
  6067. this.hadturncandidate = true;
  6068. }
  6069. if (this.usetrickle) {
  6070. if (this.usedrip) {
  6071. if (this.drip_container.length === 0) {
  6072. // start 20ms callout
  6073. window.setTimeout(function () {
  6074. if (self.drip_container.length === 0) return;
  6075. self.sendIceCandidates(self.drip_container);
  6076. self.drip_container = [];
  6077. }, 20);
  6078. }
  6079. this.drip_container.push(candidate);
  6080. return;
  6081. } else {
  6082. self.sendIceCandidate([candidate]);
  6083. }
  6084. }
  6085. } else {
  6086. //logger.log('sendIceCandidate: last candidate.');
  6087. if (!this.usetrickle) {
  6088. //logger.log('should send full offer now...');
  6089. //FIXME why do we generate session-accept in 3 different places ?
  6090. var init = $iq({to: this.peerjid,
  6091. type: 'set'})
  6092. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6093. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  6094. initiator: this.initiator,
  6095. sid: this.sid});
  6096. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  6097. if (self.webrtcIceTcpDisable) {
  6098. this.localSDP.removeTcpCandidates = true;
  6099. }
  6100. if (self.webrtcIceUdpDisable) {
  6101. this.localSDP.removeUdpCandidates = true;
  6102. }
  6103. var sendJingle = function (ssrc) {
  6104. if(!ssrc)
  6105. ssrc = {};
  6106. self.localSDP.toJingle(
  6107. init,
  6108. self.initiator == self.me ? 'initiator' : 'responder',
  6109. ssrc);
  6110. SSRCReplacement.processSessionInit(init);
  6111. self.connection.sendIQ(init,
  6112. function () {
  6113. //logger.log('session initiate ack');
  6114. var ack = {};
  6115. ack.source = 'offer';
  6116. $(document).trigger('ack.jingle', [self.sid, ack]);
  6117. },
  6118. function (stanza) {
  6119. self.state = 'error';
  6120. self.peerconnection.close();
  6121. var error = ($(stanza).find('error').length) ? {
  6122. code: $(stanza).find('error').attr('code'),
  6123. reason: $(stanza).find('error :first')[0].tagName,
  6124. }:{};
  6125. error.source = 'offer';
  6126. JingleSessionPC.onJingleError(self.sid, error);
  6127. },
  6128. 10000);
  6129. };
  6130. sendJingle();
  6131. }
  6132. this.lasticecandidate = true;
  6133. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  6134. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  6135. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  6136. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  6137. }
  6138. }
  6139. };
  6140. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  6141. logger.log('sendIceCandidates', candidates);
  6142. var cand = $iq({to: this.peerjid, type: 'set'})
  6143. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6144. action: 'transport-info',
  6145. initiator: this.initiator,
  6146. sid: this.sid});
  6147. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  6148. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  6149. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  6150. if (cands.length > 0) {
  6151. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  6152. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6153. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  6154. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  6155. }).c('transport', ice);
  6156. for (var i = 0; i < cands.length; i++) {
  6157. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  6158. }
  6159. // add fingerprint
  6160. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  6161. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  6162. tmp.required = true;
  6163. cand.c(
  6164. 'fingerprint',
  6165. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  6166. .t(tmp.fingerprint);
  6167. delete tmp.fingerprint;
  6168. cand.attrs(tmp);
  6169. cand.up();
  6170. }
  6171. cand.up(); // transport
  6172. cand.up(); // content
  6173. }
  6174. }
  6175. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6176. //logger.log('was this the last candidate', this.lasticecandidate);
  6177. this.connection.sendIQ(cand,
  6178. function () {
  6179. var ack = {};
  6180. ack.source = 'transportinfo';
  6181. $(document).trigger('ack.jingle', [this.sid, ack]);
  6182. },
  6183. function (stanza) {
  6184. var error = ($(stanza).find('error').length) ? {
  6185. code: $(stanza).find('error').attr('code'),
  6186. reason: $(stanza).find('error :first')[0].tagName,
  6187. }:{};
  6188. error.source = 'transportinfo';
  6189. JingleSessionPC.onJingleError(this.sid, error);
  6190. },
  6191. 10000);
  6192. };
  6193. JingleSessionPC.prototype.sendOffer = function () {
  6194. //logger.log('sendOffer...');
  6195. var self = this;
  6196. this.peerconnection.createOffer(function (sdp) {
  6197. self.createdOffer(sdp);
  6198. },
  6199. function (e) {
  6200. logger.error('createOffer failed', e);
  6201. },
  6202. this.media_constraints
  6203. );
  6204. };
  6205. // FIXME createdOffer is never used in jitsi-meet
  6206. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6207. //logger.log('createdOffer', sdp);
  6208. var self = this;
  6209. this.localSDP = new SDP(sdp.sdp);
  6210. //this.localSDP.mangle();
  6211. var sendJingle = function () {
  6212. var init = $iq({to: this.peerjid,
  6213. type: 'set'})
  6214. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6215. action: 'session-initiate',
  6216. initiator: this.initiator,
  6217. sid: this.sid});
  6218. self.localSDP.toJingle(
  6219. init,
  6220. this.initiator == this.me ? 'initiator' : 'responder');
  6221. SSRCReplacement.processSessionInit(init);
  6222. self.connection.sendIQ(init,
  6223. function () {
  6224. var ack = {};
  6225. ack.source = 'offer';
  6226. $(document).trigger('ack.jingle', [self.sid, ack]);
  6227. },
  6228. function (stanza) {
  6229. self.state = 'error';
  6230. self.peerconnection.close();
  6231. var error = ($(stanza).find('error').length) ? {
  6232. code: $(stanza).find('error').attr('code'),
  6233. reason: $(stanza).find('error :first')[0].tagName,
  6234. }:{};
  6235. error.source = 'offer';
  6236. JingleSessionPC.onJingleError(self.sid, error);
  6237. },
  6238. 10000);
  6239. }
  6240. sdp.sdp = this.localSDP.raw;
  6241. this.peerconnection.setLocalDescription(sdp,
  6242. function () {
  6243. if(self.usetrickle)
  6244. {
  6245. sendJingle();
  6246. }
  6247. self.setLocalDescription();
  6248. //logger.log('setLocalDescription success');
  6249. },
  6250. function (e) {
  6251. logger.error('setLocalDescription failed', e);
  6252. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6253. }
  6254. );
  6255. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6256. for (var i = 0; i < cands.length; i++) {
  6257. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6258. if (cand.type == 'srflx') {
  6259. this.hadstuncandidate = true;
  6260. } else if (cand.type == 'relay') {
  6261. this.hadturncandidate = true;
  6262. }
  6263. }
  6264. };
  6265. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6266. var self = this;
  6267. $(contents).each(function (idx, content) {
  6268. var name = $(content).attr('name');
  6269. var mediaType = this.getAttribute('name');
  6270. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6271. ssrcs.each(function () {
  6272. var ssrc = this.getAttribute('ssrc');
  6273. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6274. function () {
  6275. var owner = this.getAttribute('owner');
  6276. self.ssrcOwners[ssrc] = owner;
  6277. }
  6278. );
  6279. });
  6280. });
  6281. };
  6282. /**
  6283. * Returns the SSRC of local audio stream.
  6284. * @param mediaType 'audio' or 'video' media type
  6285. * @returns {*} the SSRC number of local audio or video stream.
  6286. */
  6287. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  6288. return this.localStreamsSSRC[mediaType];
  6289. };
  6290. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6291. return this.ssrcOwners[ssrc];
  6292. };
  6293. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6294. //logger.log('setting remote description... ', desctype);
  6295. this.remoteSDP = new SDP('');
  6296. if (self.webrtcIceTcpDisable) {
  6297. this.remoteSDP.removeTcpCandidates = true;
  6298. }
  6299. if (self.webrtcIceUdpDisable) {
  6300. this.remoteSDP.removeUdpCandidates = true;
  6301. }
  6302. this.remoteSDP.fromJingle(elem);
  6303. this.readSsrcInfo($(elem).find(">content"));
  6304. if (this.peerconnection.remoteDescription) {
  6305. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6306. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6307. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6308. for (var i = 0; i < pranswer.media.length; i++) {
  6309. // make sure we have ice ufrag and pwd
  6310. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6311. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6312. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6313. } else {
  6314. logger.warn('no ice ufrag?');
  6315. }
  6316. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6317. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6318. } else {
  6319. logger.warn('no ice pwd?');
  6320. }
  6321. }
  6322. // copy over candidates
  6323. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6324. for (var j = 0; j < lines.length; j++) {
  6325. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6326. }
  6327. }
  6328. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6329. }
  6330. }
  6331. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6332. this.peerconnection.setRemoteDescription(remotedesc,
  6333. function () {
  6334. //logger.log('setRemoteDescription success');
  6335. },
  6336. function (e) {
  6337. logger.error('setRemoteDescription error', e);
  6338. JingleSessionPC.onJingleFatalError(self, e);
  6339. }
  6340. );
  6341. };
  6342. /**
  6343. * Adds remote ICE candidates to this Jingle session.
  6344. * @param elem An array of Jingle "content" elements?
  6345. */
  6346. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6347. var self = this;
  6348. if (this.peerconnection.signalingState == 'closed') {
  6349. return;
  6350. }
  6351. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6352. logger.log('trickle ice candidate arriving before session accept...');
  6353. // create a PRANSWER for setRemoteDescription
  6354. if (!this.remoteSDP) {
  6355. var cobbled = 'v=0\r\n' +
  6356. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6357. 's=-\r\n' +
  6358. 't=0 0\r\n';
  6359. // first, take some things from the local description
  6360. for (var i = 0; i < this.localSDP.media.length; i++) {
  6361. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6362. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6363. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6364. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6365. }
  6366. cobbled += 'a=inactive\r\n';
  6367. }
  6368. this.remoteSDP = new SDP(cobbled);
  6369. }
  6370. // then add things like ice and dtls from remote candidate
  6371. elem.each(function () {
  6372. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6373. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6374. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6375. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6376. var tmp = $(this).find('transport');
  6377. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6378. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6379. tmp = $(this).find('transport>fingerprint');
  6380. if (tmp.length) {
  6381. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6382. } else {
  6383. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6384. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6385. }
  6386. break;
  6387. }
  6388. }
  6389. }
  6390. });
  6391. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6392. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6393. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6394. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6395. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6396. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6397. }).length == this.remoteSDP.media.length;
  6398. if (iscomplete) {
  6399. logger.log('setting pranswer');
  6400. try {
  6401. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6402. function() {
  6403. },
  6404. function(e) {
  6405. logger.log('setRemoteDescription pranswer failed', e.toString());
  6406. });
  6407. } catch (e) {
  6408. logger.error('setting pranswer failed', e);
  6409. }
  6410. } else {
  6411. //logger.log('not yet setting pranswer');
  6412. }
  6413. }
  6414. // operate on each content element
  6415. elem.each(function () {
  6416. // would love to deactivate this, but firefox still requires it
  6417. var idx = -1;
  6418. var i;
  6419. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6420. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6421. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6422. idx = i;
  6423. break;
  6424. }
  6425. }
  6426. if (idx == -1) { // fall back to localdescription
  6427. for (i = 0; i < self.localSDP.media.length; i++) {
  6428. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6429. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6430. idx = i;
  6431. break;
  6432. }
  6433. }
  6434. }
  6435. var name = $(this).attr('name');
  6436. // TODO: check ice-pwd and ice-ufrag?
  6437. $(this).find('transport>candidate').each(function () {
  6438. var line, candidate;
  6439. var protocol = this.getAttribute('protocol');
  6440. protocol =
  6441. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6442. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6443. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6444. return;
  6445. }
  6446. line = SDPUtil.candidateFromJingle(this);
  6447. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6448. sdpMid: name,
  6449. candidate: line});
  6450. try {
  6451. self.peerconnection.addIceCandidate(candidate);
  6452. } catch (e) {
  6453. logger.error('addIceCandidate failed', e.toString(), line);
  6454. }
  6455. });
  6456. });
  6457. };
  6458. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6459. //logger.log('createAnswer', provisional);
  6460. var self = this;
  6461. this.peerconnection.createAnswer(
  6462. function (sdp) {
  6463. self.createdAnswer(sdp, provisional);
  6464. },
  6465. function (e) {
  6466. logger.error('createAnswer failed', e);
  6467. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6468. },
  6469. this.media_constraints
  6470. );
  6471. };
  6472. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6473. //logger.log('createAnswer callback');
  6474. var self = this;
  6475. this.localSDP = new SDP(sdp.sdp);
  6476. //this.localSDP.mangle();
  6477. this.usepranswer = provisional === true;
  6478. if (this.usetrickle) {
  6479. if (this.usepranswer) {
  6480. sdp.type = 'pranswer';
  6481. for (var i = 0; i < this.localSDP.media.length; i++) {
  6482. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6483. }
  6484. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6485. }
  6486. }
  6487. var self = this;
  6488. var sendJingle = function (ssrcs) {
  6489. // FIXME why do we generate session-accept in 3 different places ?
  6490. var accept = $iq({to: self.peerjid,
  6491. type: 'set'})
  6492. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6493. action: 'session-accept',
  6494. initiator: self.initiator,
  6495. responder: self.responder,
  6496. sid: self.sid });
  6497. if (self.webrtcIceTcpDisable) {
  6498. self.localSDP.removeTcpCandidates = true;
  6499. }
  6500. if (self.webrtcIceUdpDisable) {
  6501. self.localSDP.removeUdpCandidates = true;
  6502. }
  6503. self.localSDP.toJingle(
  6504. accept,
  6505. self.initiator == self.me ? 'initiator' : 'responder',
  6506. ssrcs);
  6507. SSRCReplacement.processSessionInit(accept);
  6508. self.connection.sendIQ(accept,
  6509. function () {
  6510. var ack = {};
  6511. ack.source = 'answer';
  6512. $(document).trigger('ack.jingle', [self.sid, ack]);
  6513. },
  6514. function (stanza) {
  6515. var error = ($(stanza).find('error').length) ? {
  6516. code: $(stanza).find('error').attr('code'),
  6517. reason: $(stanza).find('error :first')[0].tagName,
  6518. }:{};
  6519. error.source = 'answer';
  6520. JingleSessionPC.onJingleError(self.sid, error);
  6521. },
  6522. 10000);
  6523. }
  6524. sdp.sdp = this.localSDP.raw;
  6525. this.peerconnection.setLocalDescription(sdp,
  6526. function () {
  6527. //logger.log('setLocalDescription success');
  6528. if (self.usetrickle && !self.usepranswer) {
  6529. sendJingle();
  6530. }
  6531. self.setLocalDescription();
  6532. },
  6533. function (e) {
  6534. logger.error('setLocalDescription failed', e);
  6535. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6536. }
  6537. );
  6538. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6539. for (var j = 0; j < cands.length; j++) {
  6540. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6541. if (cand.type == 'srflx') {
  6542. this.hadstuncandidate = true;
  6543. } else if (cand.type == 'relay') {
  6544. this.hadturncandidate = true;
  6545. }
  6546. }
  6547. };
  6548. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  6549. var self = this,
  6550. term = $iq({to: this.peerjid,
  6551. type: 'set'})
  6552. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6553. action: 'session-terminate',
  6554. initiator: this.initiator,
  6555. sid: this.sid})
  6556. .c('reason')
  6557. .c(reason || 'success');
  6558. if (text) {
  6559. term.up().c('text').t(text);
  6560. }
  6561. this.connection.sendIQ(term,
  6562. function () {
  6563. self.peerconnection.close();
  6564. self.peerconnection = null;
  6565. self.terminate();
  6566. var ack = {};
  6567. ack.source = 'terminate';
  6568. $(document).trigger('ack.jingle', [self.sid, ack]);
  6569. },
  6570. function (stanza) {
  6571. var error = ($(stanza).find('error').length) ? {
  6572. code: $(stanza).find('error').attr('code'),
  6573. reason: $(stanza).find('error :first')[0].tagName,
  6574. }:{};
  6575. $(document).trigger('ack.jingle', [self.sid, error]);
  6576. },
  6577. 10000);
  6578. if (this.statsinterval !== null) {
  6579. window.clearInterval(this.statsinterval);
  6580. this.statsinterval = null;
  6581. }
  6582. };
  6583. /**
  6584. * Handles a Jingle source-add message for this Jingle session.
  6585. * @param elem An array of Jingle "content" elements.
  6586. */
  6587. JingleSessionPC.prototype.addSource = function (elem) {
  6588. var self = this;
  6589. // FIXME: dirty waiting
  6590. if (!this.peerconnection.localDescription)
  6591. {
  6592. logger.warn("addSource - localDescription not ready yet")
  6593. setTimeout(function()
  6594. {
  6595. self.addSource(elem);
  6596. },
  6597. 200
  6598. );
  6599. return;
  6600. }
  6601. logger.log('addssrc', new Date().getTime());
  6602. logger.log('ice', this.peerconnection.iceConnectionState);
  6603. this.readSsrcInfo(elem);
  6604. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6605. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6606. $(elem).each(function (idx, content) {
  6607. var name = $(content).attr('name');
  6608. var lines = '';
  6609. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6610. var semantics = this.getAttribute('semantics');
  6611. var ssrcs = $(this).find('>source').map(function () {
  6612. return this.getAttribute('ssrc');
  6613. }).get();
  6614. if (ssrcs.length) {
  6615. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6616. }
  6617. });
  6618. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6619. tmp.each(function () {
  6620. var ssrc = $(this).attr('ssrc');
  6621. if(mySdp.containsSSRC(ssrc)){
  6622. /**
  6623. * This happens when multiple participants change their streams at the same time and
  6624. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  6625. * addssrc are scheduled for update IQ. See
  6626. */
  6627. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  6628. return;
  6629. }
  6630. if (sdp.containsSSRC(ssrc)) {
  6631. logger.warn("Source-add request for existing SSRC: " + ssrc);
  6632. return;
  6633. }
  6634. $(this).find('>parameter').each(function () {
  6635. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6636. if ($(this).attr('value') && $(this).attr('value').length)
  6637. lines += ':' + $(this).attr('value');
  6638. lines += '\r\n';
  6639. });
  6640. });
  6641. sdp.media.forEach(function(media, idx) {
  6642. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6643. return;
  6644. sdp.media[idx] += lines;
  6645. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  6646. self.addssrc[idx] += lines;
  6647. });
  6648. sdp.raw = sdp.session + sdp.media.join('');
  6649. });
  6650. this.modifySourcesQueue.push(function() {
  6651. // When a source is added and if this is FF, a new channel is allocated
  6652. // for receiving the added source. We need to diffuse the SSRC of this
  6653. // new recvonly channel to the rest of the peers.
  6654. logger.log('modify sources done');
  6655. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6656. logger.log("SDPs", mySdp, newSdp);
  6657. self.notifyMySSRCUpdate(mySdp, newSdp);
  6658. });
  6659. };
  6660. /**
  6661. * Handles a Jingle source-remove message for this Jingle session.
  6662. * @param elem An array of Jingle "content" elements.
  6663. */
  6664. JingleSessionPC.prototype.removeSource = function (elem) {
  6665. var self = this;
  6666. // FIXME: dirty waiting
  6667. if (!this.peerconnection.localDescription) {
  6668. logger.warn("removeSource - localDescription not ready yet");
  6669. setTimeout(function() {
  6670. self.removeSource(elem);
  6671. },
  6672. 200
  6673. );
  6674. return;
  6675. }
  6676. logger.log('removessrc', new Date().getTime());
  6677. logger.log('ice', this.peerconnection.iceConnectionState);
  6678. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6679. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6680. $(elem).each(function (idx, content) {
  6681. var name = $(content).attr('name');
  6682. var lines = '';
  6683. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6684. var semantics = this.getAttribute('semantics');
  6685. var ssrcs = $(this).find('>source').map(function () {
  6686. return this.getAttribute('ssrc');
  6687. }).get();
  6688. if (ssrcs.length) {
  6689. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6690. }
  6691. });
  6692. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6693. tmp.each(function () {
  6694. var ssrc = $(this).attr('ssrc');
  6695. // This should never happen, but can be useful for bug detection
  6696. if(mySdp.containsSSRC(ssrc)){
  6697. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  6698. return;
  6699. }
  6700. $(this).find('>parameter').each(function () {
  6701. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6702. if ($(this).attr('value') && $(this).attr('value').length)
  6703. lines += ':' + $(this).attr('value');
  6704. lines += '\r\n';
  6705. });
  6706. });
  6707. sdp.media.forEach(function(media, idx) {
  6708. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6709. return;
  6710. sdp.media[idx] += lines;
  6711. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  6712. self.removessrc[idx] += lines;
  6713. });
  6714. sdp.raw = sdp.session + sdp.media.join('');
  6715. });
  6716. this.modifySourcesQueue.push(function() {
  6717. // When a source is removed and if this is FF, the recvonly channel that
  6718. // receives the remote stream is deactivated . We need to diffuse the
  6719. // recvonly SSRC removal to the rest of the peers.
  6720. logger.log('modify sources done');
  6721. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6722. logger.log("SDPs", mySdp, newSdp);
  6723. self.notifyMySSRCUpdate(mySdp, newSdp);
  6724. });
  6725. };
  6726. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  6727. var self = this;
  6728. if (this.peerconnection.signalingState == 'closed') return;
  6729. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  6730. || this.switchstreams || this.addingStreams)){
  6731. // There is nothing to do since scheduled job might have been executed by another succeeding call
  6732. this.setLocalDescription();
  6733. if(successCallback){
  6734. successCallback();
  6735. }
  6736. queueCallback();
  6737. return;
  6738. }
  6739. // Reset switch streams flags
  6740. this.switchstreams = false;
  6741. this.addingStreams = false;
  6742. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6743. // add sources
  6744. this.addssrc.forEach(function(lines, idx) {
  6745. sdp.media[idx] += lines;
  6746. });
  6747. this.addssrc = [];
  6748. // remove sources
  6749. this.removessrc.forEach(function(lines, idx) {
  6750. lines = lines.split('\r\n');
  6751. lines.pop(); // remove empty last element;
  6752. lines.forEach(function(line) {
  6753. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6754. });
  6755. });
  6756. this.removessrc = [];
  6757. sdp.raw = sdp.session + sdp.media.join('');
  6758. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6759. function() {
  6760. if(self.signalingState == 'closed') {
  6761. logger.error("createAnswer attempt on closed state");
  6762. queueCallback("createAnswer attempt on closed state");
  6763. return;
  6764. }
  6765. self.peerconnection.createAnswer(
  6766. function(modifiedAnswer) {
  6767. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6768. if (self.pendingop !== null) {
  6769. var sdp = new SDP(modifiedAnswer.sdp);
  6770. if (sdp.media.length > 1) {
  6771. switch(self.pendingop) {
  6772. case 'mute':
  6773. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6774. break;
  6775. case 'unmute':
  6776. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6777. break;
  6778. }
  6779. sdp.raw = sdp.session + sdp.media.join('');
  6780. modifiedAnswer.sdp = sdp.raw;
  6781. }
  6782. self.pendingop = null;
  6783. }
  6784. // FIXME: pushing down an answer while ice connection state
  6785. // is still checking is bad...
  6786. //logger.log(self.peerconnection.iceConnectionState);
  6787. // trying to work around another chrome bug
  6788. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6789. self.peerconnection.setLocalDescription(modifiedAnswer,
  6790. function() {
  6791. //logger.log('modified setLocalDescription ok');
  6792. self.setLocalDescription();
  6793. if(successCallback){
  6794. successCallback();
  6795. }
  6796. queueCallback();
  6797. },
  6798. function(error) {
  6799. logger.error('modified setLocalDescription failed', error);
  6800. queueCallback(error);
  6801. }
  6802. );
  6803. },
  6804. function(error) {
  6805. logger.error('modified answer failed', error);
  6806. queueCallback(error);
  6807. }
  6808. );
  6809. },
  6810. function(error) {
  6811. logger.error('modify failed', error);
  6812. queueCallback(error);
  6813. }
  6814. );
  6815. };
  6816. /**
  6817. * Switches video streams.
  6818. * @param newStream new stream that will be used as video of this session.
  6819. * @param oldStream old video stream of this session.
  6820. * @param successCallback callback executed after successful stream switch.
  6821. * @param isAudio whether the streams are audio (if true) or video (if false).
  6822. */
  6823. JingleSessionPC.prototype.switchStreams =
  6824. function (newStream, oldStream, successCallback, isAudio) {
  6825. var self = this;
  6826. var sender, newTrack;
  6827. var senderKind = isAudio ? 'audio' : 'video';
  6828. // Remember SDP to figure out added/removed SSRCs
  6829. var oldSdp = null;
  6830. if (self.peerconnection) {
  6831. if (self.peerconnection.localDescription) {
  6832. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6833. }
  6834. if (RTCBrowserType.getBrowserType() ===
  6835. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  6836. // On Firefox we don't replace MediaStreams as this messes up the
  6837. // m-lines (which can't be removed in Plan Unified) and brings a lot
  6838. // of complications. Instead, we use the RTPSender and replace just
  6839. // the track.
  6840. // Find the right sender (for audio or video)
  6841. self.peerconnection.peerconnection.getSenders().some(function (s) {
  6842. if (s.track && s.track.kind === senderKind) {
  6843. sender = s;
  6844. return true;
  6845. }
  6846. });
  6847. if (sender) {
  6848. // We assume that our streams have a single track, either audio
  6849. // or video.
  6850. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  6851. newStream.getVideoTracks()[0];
  6852. sender.replaceTrack(newTrack)
  6853. .then(function() {
  6854. console.log("Replaced a track, isAudio=" + isAudio);
  6855. })
  6856. .catch(function(err) {
  6857. console.log("Failed to replace a track: " + err);
  6858. });
  6859. } else {
  6860. console.log("Cannot switch tracks: no RTPSender.");
  6861. }
  6862. } else {
  6863. self.peerconnection.removeStream(oldStream, true);
  6864. if (newStream) {
  6865. self.peerconnection.addStream(newStream);
  6866. }
  6867. }
  6868. }
  6869. // Conference is not active
  6870. if (!oldSdp) {
  6871. successCallback();
  6872. return;
  6873. }
  6874. self.switchstreams = true;
  6875. self.modifySourcesQueue.push(function() {
  6876. logger.log('modify sources done');
  6877. successCallback();
  6878. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6879. logger.log("SDPs", oldSdp, newSdp);
  6880. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6881. });
  6882. };
  6883. /**
  6884. * Adds streams.
  6885. * @param stream new stream that will be added.
  6886. * @param success_callback callback executed after successful stream addition.
  6887. */
  6888. JingleSessionPC.prototype.addStream = function (stream, callback) {
  6889. var self = this;
  6890. // Remember SDP to figure out added/removed SSRCs
  6891. var oldSdp = null;
  6892. if(this.peerconnection) {
  6893. if(this.peerconnection.localDescription) {
  6894. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  6895. }
  6896. if(stream)
  6897. this.peerconnection.addStream(stream);
  6898. }
  6899. // Conference is not active
  6900. if(!oldSdp || !this.peerconnection) {
  6901. callback();
  6902. return;
  6903. }
  6904. this.addingStreams = true;
  6905. this.modifySourcesQueue.push(function() {
  6906. logger.log('modify sources done');
  6907. callback();
  6908. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6909. logger.log("SDPs", oldSdp, newSdp);
  6910. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6911. });
  6912. }
  6913. /**
  6914. * Remove streams.
  6915. * @param stream stream that will be removed.
  6916. * @param success_callback callback executed after successful stream addition.
  6917. */
  6918. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  6919. var self = this;
  6920. // Remember SDP to figure out added/removed SSRCs
  6921. var oldSdp = null;
  6922. if(this.peerconnection) {
  6923. if(this.peerconnection.localDescription) {
  6924. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  6925. }
  6926. if(stream)
  6927. this.peerconnection.removeStream(stream);
  6928. }
  6929. // Conference is not active
  6930. if(!oldSdp || !this.peerconnection) {
  6931. callback();
  6932. return;
  6933. }
  6934. this.addingStreams = true;
  6935. this.modifySourcesQueue.push(function() {
  6936. logger.log('modify sources done');
  6937. callback();
  6938. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6939. logger.log("SDPs", oldSdp, newSdp);
  6940. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6941. });
  6942. }
  6943. /**
  6944. * Figures out added/removed ssrcs and send update IQs.
  6945. * @param old_sdp SDP object for old description.
  6946. * @param new_sdp SDP object for new description.
  6947. */
  6948. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  6949. if (!(this.peerconnection.signalingState == 'stable' &&
  6950. this.peerconnection.iceConnectionState == 'connected')){
  6951. logger.log("Too early to send updates");
  6952. return;
  6953. }
  6954. // send source-remove IQ.
  6955. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  6956. var remove = $iq({to: this.peerjid, type: 'set'})
  6957. .c('jingle', {
  6958. xmlns: 'urn:xmpp:jingle:1',
  6959. action: 'source-remove',
  6960. initiator: this.initiator,
  6961. sid: this.sid
  6962. }
  6963. );
  6964. var removed = sdpDiffer.toJingle(remove);
  6965. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  6966. // it in the current form
  6967. if (removed)
  6968. remove = SSRCReplacement.processSourceRemove(remove);
  6969. if (removed && remove) {
  6970. logger.info("Sending source-remove", remove);
  6971. this.connection.sendIQ(remove,
  6972. function (res) {
  6973. logger.info('got remove result', res);
  6974. },
  6975. function (err) {
  6976. logger.error('got remove error', err);
  6977. }
  6978. );
  6979. } else {
  6980. logger.log('removal not necessary');
  6981. }
  6982. // send source-add IQ.
  6983. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  6984. var add = $iq({to: this.peerjid, type: 'set'})
  6985. .c('jingle', {
  6986. xmlns: 'urn:xmpp:jingle:1',
  6987. action: 'source-add',
  6988. initiator: this.initiator,
  6989. sid: this.sid
  6990. }
  6991. );
  6992. var added = sdpDiffer.toJingle(add);
  6993. // Let 'source-add' IQ through the hack and see if we're allowed to send
  6994. // it in the current form
  6995. if (added)
  6996. add = SSRCReplacement.processSourceAdd(add);
  6997. if (added && add) {
  6998. logger.info("Sending source-add", add);
  6999. this.connection.sendIQ(add,
  7000. function (res) {
  7001. logger.info('got add result', res);
  7002. },
  7003. function (err) {
  7004. logger.error('got add error', err);
  7005. }
  7006. );
  7007. } else {
  7008. logger.log('addition not necessary');
  7009. }
  7010. };
  7011. /**
  7012. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  7013. *
  7014. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  7015. * tracks; otherwise, <tt>false</tt>
  7016. * @param callback a function to be invoked with <tt>mute</tt> after all video
  7017. * tracks have been enabled/disabled. The function may, optionally, return
  7018. * another function which is to be invoked after the whole mute/unmute operation
  7019. * has completed successfully.
  7020. * @param options an object which specifies optional arguments such as the
  7021. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  7022. * specifies whether the method was initiated in response to a user command (in
  7023. * contrast to an automatic decision made by the application logic)
  7024. */
  7025. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  7026. var byUser;
  7027. if (options) {
  7028. byUser = options.byUser;
  7029. if (typeof byUser === 'undefined') {
  7030. byUser = true;
  7031. }
  7032. } else {
  7033. byUser = true;
  7034. }
  7035. // The user's command to mute the (local) video takes precedence over any
  7036. // automatic decision made by the application logic.
  7037. if (byUser) {
  7038. this.videoMuteByUser = mute;
  7039. } else if (this.videoMuteByUser) {
  7040. return;
  7041. }
  7042. this.hardMuteVideo(mute);
  7043. var self = this;
  7044. var oldSdp = null;
  7045. if(self.peerconnection) {
  7046. if(self.peerconnection.localDescription) {
  7047. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  7048. }
  7049. }
  7050. this.modifySourcesQueue.push(function() {
  7051. logger.log('modify sources done');
  7052. callback(mute);
  7053. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  7054. logger.log("SDPs", oldSdp, newSdp);
  7055. self.notifyMySSRCUpdate(oldSdp, newSdp);
  7056. });
  7057. };
  7058. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  7059. this.pendingop = muted ? 'mute' : 'unmute';
  7060. };
  7061. JingleSessionPC.prototype.sendMute = function (muted, content) {
  7062. var info = $iq({to: this.peerjid,
  7063. type: 'set'})
  7064. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7065. action: 'session-info',
  7066. initiator: this.initiator,
  7067. sid: this.sid });
  7068. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7069. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  7070. if (content) {
  7071. info.attrs({'name': content});
  7072. }
  7073. this.connection.send(info);
  7074. };
  7075. JingleSessionPC.prototype.sendRinging = function () {
  7076. var info = $iq({to: this.peerjid,
  7077. type: 'set'})
  7078. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7079. action: 'session-info',
  7080. initiator: this.initiator,
  7081. sid: this.sid });
  7082. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  7083. this.connection.send(info);
  7084. };
  7085. JingleSessionPC.prototype.getStats = function (interval) {
  7086. var self = this;
  7087. var recv = {audio: 0, video: 0};
  7088. var lost = {audio: 0, video: 0};
  7089. var lastrecv = {audio: 0, video: 0};
  7090. var lastlost = {audio: 0, video: 0};
  7091. var loss = {audio: 0, video: 0};
  7092. var delta = {audio: 0, video: 0};
  7093. this.statsinterval = window.setInterval(function () {
  7094. if (self && self.peerconnection && self.peerconnection.getStats) {
  7095. self.peerconnection.getStats(function (stats) {
  7096. var results = stats.result();
  7097. // TODO: there are so much statistics you can get from this..
  7098. for (var i = 0; i < results.length; ++i) {
  7099. if (results[i].type == 'ssrc') {
  7100. var packetsrecv = results[i].stat('packetsReceived');
  7101. var packetslost = results[i].stat('packetsLost');
  7102. if (packetsrecv && packetslost) {
  7103. packetsrecv = parseInt(packetsrecv, 10);
  7104. packetslost = parseInt(packetslost, 10);
  7105. if (results[i].stat('googFrameRateReceived')) {
  7106. lastlost.video = lost.video;
  7107. lastrecv.video = recv.video;
  7108. recv.video = packetsrecv;
  7109. lost.video = packetslost;
  7110. } else {
  7111. lastlost.audio = lost.audio;
  7112. lastrecv.audio = recv.audio;
  7113. recv.audio = packetsrecv;
  7114. lost.audio = packetslost;
  7115. }
  7116. }
  7117. }
  7118. }
  7119. delta.audio = recv.audio - lastrecv.audio;
  7120. delta.video = recv.video - lastrecv.video;
  7121. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  7122. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  7123. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  7124. });
  7125. }
  7126. }, interval || 3000);
  7127. return this.statsinterval;
  7128. };
  7129. JingleSessionPC.onJingleError = function (session, error)
  7130. {
  7131. logger.error("Jingle error", error);
  7132. }
  7133. JingleSessionPC.onJingleFatalError = function (session, error)
  7134. {
  7135. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7136. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  7137. }
  7138. JingleSessionPC.prototype.setLocalDescription = function () {
  7139. var self = this;
  7140. var newssrcs = [];
  7141. if(!this.peerconnection.localDescription)
  7142. return;
  7143. var session = transform.parse(this.peerconnection.localDescription.sdp);
  7144. var i;
  7145. session.media.forEach(function (media) {
  7146. if (media.ssrcs && media.ssrcs.length > 0) {
  7147. // TODO(gp) maybe exclude FID streams?
  7148. media.ssrcs.forEach(function (ssrc) {
  7149. if (ssrc.attribute !== 'cname') {
  7150. return;
  7151. }
  7152. newssrcs.push({
  7153. 'ssrc': ssrc.id,
  7154. 'type': media.type
  7155. });
  7156. // FIXME allows for only one SSRC per media type
  7157. self.localStreamsSSRC[media.type] = ssrc.id;
  7158. });
  7159. }
  7160. });
  7161. logger.log('new ssrcs', newssrcs);
  7162. // Bind us as local SSRCs owner
  7163. if (newssrcs.length > 0) {
  7164. for (i = 0; i < newssrcs.length; i++) {
  7165. var ssrc = newssrcs[i].ssrc;
  7166. var myJid = self.connection.emuc.myroomjid;
  7167. self.ssrcOwners[ssrc] = myJid;
  7168. }
  7169. }
  7170. }
  7171. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7172. JingleSessionPC.prototype.sendKeyframe = function () {
  7173. var pc = this.peerconnection;
  7174. logger.log('sendkeyframe', pc.iceConnectionState);
  7175. if (pc.iceConnectionState !== 'connected') return; // safe...
  7176. var self = this;
  7177. pc.setRemoteDescription(
  7178. pc.remoteDescription,
  7179. function () {
  7180. pc.createAnswer(
  7181. function (modifiedAnswer) {
  7182. pc.setLocalDescription(
  7183. modifiedAnswer,
  7184. function () {
  7185. // noop
  7186. },
  7187. function (error) {
  7188. logger.log('triggerKeyframe setLocalDescription failed', error);
  7189. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  7190. }
  7191. );
  7192. },
  7193. function (error) {
  7194. logger.log('triggerKeyframe createAnswer failed', error);
  7195. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  7196. }
  7197. );
  7198. },
  7199. function (error) {
  7200. logger.log('triggerKeyframe setRemoteDescription failed', error);
  7201. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  7202. }
  7203. );
  7204. }
  7205. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7206. var self = this;
  7207. var thessrc;
  7208. var streamId = RTC.getStreamID(data.stream);
  7209. // look up an associated JID for a stream id
  7210. if (!streamId) {
  7211. logger.error("No stream ID for", data.stream);
  7212. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7213. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7214. var ssrclines = this.peerconnection.remoteDescription?
  7215. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7216. ssrclines = ssrclines.filter(function (line) {
  7217. // NOTE(gp) previously we filtered on the mslabel, but that property
  7218. // is not always present.
  7219. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7220. if (RTCBrowserType.isTemasysPluginUsed()) {
  7221. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7222. } else {
  7223. return ((line.indexOf('msid:' + streamId) !== -1));
  7224. }
  7225. });
  7226. if (ssrclines.length) {
  7227. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7228. if (!self.ssrcOwners[thessrc]) {
  7229. logger.error("No SSRC owner known for: " + thessrc);
  7230. return;
  7231. }
  7232. data.peerjid = self.ssrcOwners[thessrc];
  7233. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7234. } else {
  7235. logger.error("No SSRC lines for ", streamId);
  7236. }
  7237. }
  7238. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7239. var isVideo = data.stream.getVideoTracks().length > 0;
  7240. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7241. if (isVideo &&
  7242. data.peerjid && this.peerjid === data.peerjid &&
  7243. data.stream.getVideoTracks().length === 0 &&
  7244. RTC.localVideo.getTracks().length > 0) {
  7245. window.setTimeout(function () {
  7246. self.sendKeyframe();
  7247. }, 3000);
  7248. }
  7249. }
  7250. module.exports = JingleSessionPC;
  7251. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7252. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./LocalSSRCReplacement":29,"./SDP":30,"./SDPDiffer":31,"./SDPUtil":32,"./TraceablePeerConnection":33,"async":42,"jitsi-meet-logger":47,"sdp-transform":75}],29:[function(require,module,exports){
  7253. (function (__filename){
  7254. /* global $ */
  7255. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7256. /*
  7257. Here we do modifications of local video SSRCs. There are 2 situations we have
  7258. to handle:
  7259. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7260. have no local camera and it is not generated automatically, but SSRC=1 is
  7261. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7262. and we won't be able to request video key frames correctly.
  7263. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7264. in future. It turned out that Chrome may keep on using the SSRC of removed
  7265. video stream in RTCP even though a new one has been created. So we just
  7266. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7267. notifications are blocked once first video SSRC is advertised to the focus.
  7268. What this hack does:
  7269. 1. Stores the SSRC of the first video stream created by
  7270. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7271. b) watching for 'source-add' for new video stream if it has not been
  7272. created in step a)
  7273. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7274. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7275. returned to the other parts of the application.
  7276. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7277. blocks those notifications. This makes Jicofo and all participants think
  7278. that it exists all the time even if the video stream has been removed or
  7279. replaced locally. Thanks to that there is no additional signaling activity
  7280. on video mute or when switching to the desktop stream.
  7281. */
  7282. var SDP = require('./SDP');
  7283. var RandomUtil = require('../util/RandomUtil');
  7284. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7285. /**
  7286. * The hack is enabled on all browsers except FF by default
  7287. * FIXME finish the hack once removeStream method is implemented in FF
  7288. * @type {boolean}
  7289. */
  7290. var isEnabled = !RTCBrowserType.isFirefox();
  7291. /**
  7292. * Stored SSRC of local video stream.
  7293. */
  7294. var localVideoSSRC;
  7295. /**
  7296. * SSRC used for recvonly video stream when we have no local camera.
  7297. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7298. * instead of 1.
  7299. */
  7300. var localRecvOnlySSRC;
  7301. /**
  7302. * cname for <tt>localRecvOnlySSRC</tt>
  7303. */
  7304. var localRecvOnlyCName;
  7305. /**
  7306. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7307. * from given Jingle IQ.
  7308. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7309. * @param actionName display name of the action which will be printed in log
  7310. * messages.
  7311. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7312. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7313. * other SSRCs left to be signaled after removing it.
  7314. */
  7315. var filterOutSource = function (modifyIq, actionName) {
  7316. var modifyIqTree = $(modifyIq.tree());
  7317. if (!localVideoSSRC)
  7318. return modifyIqTree[0];
  7319. var videoSSRC = modifyIqTree.find(
  7320. '>jingle>content[name="video"]' +
  7321. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7322. if (!videoSSRC.length) {
  7323. return modifyIqTree[0];
  7324. }
  7325. logger.info(
  7326. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7327. videoSSRC.remove();
  7328. // Check if any sources still left to be added/removed
  7329. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7330. return modifyIqTree[0];
  7331. } else {
  7332. return null;
  7333. }
  7334. };
  7335. /**
  7336. * Scans given Jingle IQ for video SSRC and stores it.
  7337. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7338. */
  7339. var storeLocalVideoSSRC = function (jingleIq) {
  7340. var videoSSRCs =
  7341. $(jingleIq.tree())
  7342. .find('>jingle>content[name="video"]>description>source');
  7343. videoSSRCs.each(function (idx, ssrcElem) {
  7344. if (localVideoSSRC)
  7345. return;
  7346. // We consider SSRC real only if it has msid attribute
  7347. // recvonly streams in FF do not have it as well as local SSRCs
  7348. // we generate for recvonly streams in Chrome
  7349. var ssrSel = $(ssrcElem);
  7350. var msid = ssrSel.find('>parameter[name="msid"]');
  7351. if (msid.length) {
  7352. var ssrcVal = ssrSel.attr('ssrc');
  7353. if (ssrcVal) {
  7354. localVideoSSRC = ssrcVal;
  7355. logger.info('Stored local video SSRC' +
  7356. ' for future re-use: ' + localVideoSSRC);
  7357. }
  7358. }
  7359. });
  7360. };
  7361. /**
  7362. * Generates new SSRC for local video recvonly stream.
  7363. * FIXME what about eventual SSRC collision ?
  7364. */
  7365. function generateRecvonlySSRC() {
  7366. localRecvOnlySSRC =
  7367. localVideoSSRC ?
  7368. localVideoSSRC : Math.random().toString(10).substring(2, 11);
  7369. localRecvOnlyCName =
  7370. Math.random().toString(36).substring(2);
  7371. logger.info(
  7372. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7373. ", cname: " + localRecvOnlyCName);
  7374. }
  7375. var LocalSSRCReplacement = {
  7376. /**
  7377. * Method must be called before 'session-initiate' or 'session-invite' is
  7378. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7379. *
  7380. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7381. * which will be scanned for local video SSRC.
  7382. */
  7383. processSessionInit: function (sessionInit) {
  7384. if (!isEnabled)
  7385. return;
  7386. if (localVideoSSRC) {
  7387. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7388. return;
  7389. }
  7390. storeLocalVideoSSRC(sessionInit);
  7391. },
  7392. /**
  7393. * If we have local video SSRC stored searched given
  7394. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7395. * with the stored one.
  7396. * @param localDescription local description object that will have local
  7397. * video SSRC replaced with the stored one
  7398. * @returns modified <tt>localDescription</tt> object.
  7399. */
  7400. mungeLocalVideoSSRC: function (localDescription) {
  7401. if (!isEnabled)
  7402. return localDescription;
  7403. if (!localDescription) {
  7404. logger.warn("localDescription is null or undefined");
  7405. return localDescription;
  7406. }
  7407. // IF we have local video SSRC stored make sure it is replaced
  7408. // with old SSRC
  7409. var sdp = new SDP(localDescription.sdp);
  7410. if (sdp.media.length < 2)
  7411. return;
  7412. if (localVideoSSRC && sdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7413. !sdp.containsSSRC(localVideoSSRC)) {
  7414. // Get new video SSRC
  7415. var map = sdp.getMediaSsrcMap();
  7416. var videoPart = map[1];
  7417. var videoSSRCs = videoPart.ssrcs;
  7418. var newSSRC = Object.keys(videoSSRCs)[0];
  7419. logger.info(
  7420. "Replacing new video SSRC: " + newSSRC +
  7421. " with " + localVideoSSRC);
  7422. localDescription.sdp =
  7423. sdp.raw.replace(
  7424. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7425. 'a=ssrc:' + localVideoSSRC);
  7426. }
  7427. else if (sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7428. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7429. // Make sure we have any SSRC for recvonly video stream
  7430. if (!localRecvOnlySSRC) {
  7431. generateRecvonlySSRC();
  7432. }
  7433. logger.info('No SSRC in video recvonly stream' +
  7434. ' - adding SSRC: ' + localRecvOnlySSRC);
  7435. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7436. ' cname:' + localRecvOnlyCName + '\r\n';
  7437. localDescription.sdp = sdp.session + sdp.media.join('');
  7438. }
  7439. return localDescription;
  7440. },
  7441. /**
  7442. * Method must be called before 'source-add' notification is sent. In case
  7443. * we have local video SSRC advertised already it will be removed from the
  7444. * notification. If no other SSRCs are described by given IQ null will be
  7445. * returned which means that there is no point in sending the notification.
  7446. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7447. * @returns modified 'source-add' IQ which can be sent to the focus or
  7448. * <tt>null</tt> if no notification shall be sent. It is no longer
  7449. * a Strophe IQ Builder instance, but DOM element tree.
  7450. */
  7451. processSourceAdd: function (sourceAdd) {
  7452. if (!isEnabled)
  7453. return sourceAdd;
  7454. if (!localVideoSSRC) {
  7455. // Store local SSRC if available
  7456. storeLocalVideoSSRC(sourceAdd);
  7457. return sourceAdd;
  7458. } else {
  7459. return filterOutSource(sourceAdd, 'source-add');
  7460. }
  7461. },
  7462. /**
  7463. * Method must be called before 'source-remove' notification is sent.
  7464. * Removes local video SSRC from the notification. If there are no other
  7465. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  7466. * means that there is no point in sending the notification.
  7467. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  7468. * @returns modified 'source-remove' IQ which can be sent to the focus or
  7469. * <tt>null</tt> if no notification shall be sent. It is no longer
  7470. * a Strophe IQ Builder instance, but DOM element tree.
  7471. */
  7472. processSourceRemove: function (sourceRemove) {
  7473. if (!isEnabled)
  7474. return sourceRemove;
  7475. return filterOutSource(sourceRemove, 'source-remove');
  7476. },
  7477. /**
  7478. * Turns the hack on or off
  7479. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  7480. * to disable it
  7481. */
  7482. setEnabled: function (enabled) {
  7483. isEnabled = enabled;
  7484. }
  7485. };
  7486. module.exports = LocalSSRCReplacement;
  7487. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7488. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":47}],30:[function(require,module,exports){
  7489. (function (__filename){
  7490. /* jshint -W117 */
  7491. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7492. var SDPUtil = require("./SDPUtil");
  7493. // SDP STUFF
  7494. function SDP(sdp) {
  7495. /**
  7496. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7497. * @type {boolean}
  7498. */
  7499. this.removeTcpCandidates = false;
  7500. /**
  7501. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7502. * @type {boolean}
  7503. */
  7504. this.removeUdpCandidates = false;
  7505. this.media = sdp.split('\r\nm=');
  7506. for (var i = 1; i < this.media.length; i++) {
  7507. this.media[i] = 'm=' + this.media[i];
  7508. if (i != this.media.length - 1) {
  7509. this.media[i] += '\r\n';
  7510. }
  7511. }
  7512. this.session = this.media.shift() + '\r\n';
  7513. this.raw = this.session + this.media.join('');
  7514. }
  7515. /**
  7516. * Returns map of MediaChannel mapped per channel idx.
  7517. */
  7518. SDP.prototype.getMediaSsrcMap = function() {
  7519. var self = this;
  7520. var media_ssrcs = {};
  7521. var tmp;
  7522. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7523. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7524. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7525. var media = {
  7526. mediaindex: mediaindex,
  7527. mid: mid,
  7528. ssrcs: {},
  7529. ssrcGroups: []
  7530. };
  7531. media_ssrcs[mediaindex] = media;
  7532. tmp.forEach(function (line) {
  7533. var linessrc = line.substring(7).split(' ')[0];
  7534. // allocate new ChannelSsrc
  7535. if(!media.ssrcs[linessrc]) {
  7536. media.ssrcs[linessrc] = {
  7537. ssrc: linessrc,
  7538. lines: []
  7539. };
  7540. }
  7541. media.ssrcs[linessrc].lines.push(line);
  7542. });
  7543. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7544. tmp.forEach(function(line){
  7545. var idx = line.indexOf(' ');
  7546. var semantics = line.substr(0, idx).substr(13);
  7547. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7548. if (ssrcs.length) {
  7549. media.ssrcGroups.push({
  7550. semantics: semantics,
  7551. ssrcs: ssrcs
  7552. });
  7553. }
  7554. });
  7555. }
  7556. return media_ssrcs;
  7557. };
  7558. /**
  7559. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7560. * @param ssrc the ssrc to check.
  7561. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7562. */
  7563. SDP.prototype.containsSSRC = function (ssrc) {
  7564. // FIXME this code is really strange - improve it if you can
  7565. var medias = this.getMediaSsrcMap();
  7566. var result = false;
  7567. Object.keys(medias).forEach(function (mediaindex) {
  7568. if (result)
  7569. return;
  7570. if (medias[mediaindex].ssrcs[ssrc]) {
  7571. result = true;
  7572. }
  7573. });
  7574. return result;
  7575. };
  7576. // remove iSAC and CN from SDP
  7577. SDP.prototype.mangle = function () {
  7578. var i, j, mline, lines, rtpmap, newdesc;
  7579. for (i = 0; i < this.media.length; i++) {
  7580. lines = this.media[i].split('\r\n');
  7581. lines.pop(); // remove empty last element
  7582. mline = SDPUtil.parse_mline(lines.shift());
  7583. if (mline.media != 'audio')
  7584. continue;
  7585. newdesc = '';
  7586. mline.fmt.length = 0;
  7587. for (j = 0; j < lines.length; j++) {
  7588. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  7589. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  7590. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  7591. continue;
  7592. mline.fmt.push(rtpmap.id);
  7593. newdesc += lines[j] + '\r\n';
  7594. } else {
  7595. newdesc += lines[j] + '\r\n';
  7596. }
  7597. }
  7598. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  7599. this.media[i] += newdesc;
  7600. }
  7601. this.raw = this.session + this.media.join('');
  7602. };
  7603. // remove lines matching prefix from session section
  7604. SDP.prototype.removeSessionLines = function(prefix) {
  7605. var self = this;
  7606. var lines = SDPUtil.find_lines(this.session, prefix);
  7607. lines.forEach(function(line) {
  7608. self.session = self.session.replace(line + '\r\n', '');
  7609. });
  7610. this.raw = this.session + this.media.join('');
  7611. return lines;
  7612. }
  7613. // remove lines matching prefix from a media section specified by mediaindex
  7614. // TODO: non-numeric mediaindex could match mid
  7615. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  7616. var self = this;
  7617. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  7618. lines.forEach(function(line) {
  7619. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  7620. });
  7621. this.raw = this.session + this.media.join('');
  7622. return lines;
  7623. }
  7624. // add content's to a jingle element
  7625. SDP.prototype.toJingle = function (elem, thecreator) {
  7626. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  7627. var self = this;
  7628. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  7629. // new bundle plan
  7630. if (SDPUtil.find_line(this.session, 'a=group:')) {
  7631. lines = SDPUtil.find_lines(this.session, 'a=group:');
  7632. for (i = 0; i < lines.length; i++) {
  7633. tmp = lines[i].split(' ');
  7634. var semantics = tmp.shift().substr(8);
  7635. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  7636. for (j = 0; j < tmp.length; j++) {
  7637. elem.c('content', {name: tmp[j]}).up();
  7638. }
  7639. elem.up();
  7640. }
  7641. }
  7642. for (i = 0; i < this.media.length; i++) {
  7643. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  7644. if (!(mline.media === 'audio' ||
  7645. mline.media === 'video' ||
  7646. mline.media === 'application'))
  7647. {
  7648. continue;
  7649. }
  7650. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  7651. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  7652. } else {
  7653. ssrc = false;
  7654. }
  7655. elem.c('content', {creator: thecreator, name: mline.media});
  7656. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  7657. // prefer identifier from a=mid if present
  7658. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  7659. elem.attrs({ name: mid });
  7660. }
  7661. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  7662. elem.c('description',
  7663. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  7664. media: mline.media });
  7665. if (ssrc) {
  7666. elem.attrs({ssrc: ssrc});
  7667. }
  7668. for (j = 0; j < mline.fmt.length; j++) {
  7669. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  7670. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  7671. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  7672. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  7673. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  7674. for (k = 0; k < tmp.length; k++) {
  7675. elem.c('parameter', tmp[k]).up();
  7676. }
  7677. }
  7678. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  7679. elem.up();
  7680. }
  7681. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  7682. elem.c('encryption', {required: 1});
  7683. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  7684. crypto.forEach(function(line) {
  7685. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  7686. });
  7687. elem.up(); // end of encryption
  7688. }
  7689. if (ssrc) {
  7690. // new style mapping
  7691. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7692. // FIXME: group by ssrc and support multiple different ssrcs
  7693. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  7694. if(ssrclines.length > 0) {
  7695. ssrclines.forEach(function (line) {
  7696. var idx = line.indexOf(' ');
  7697. var linessrc = line.substr(0, idx).substr(7);
  7698. if (linessrc != ssrc) {
  7699. elem.up();
  7700. ssrc = linessrc;
  7701. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7702. }
  7703. var kv = line.substr(idx + 1);
  7704. elem.c('parameter');
  7705. if (kv.indexOf(':') == -1) {
  7706. elem.attrs({ name: kv });
  7707. } else {
  7708. var k = kv.split(':', 2)[0];
  7709. elem.attrs({ name: k });
  7710. var v = kv.split(':', 2)[1];
  7711. v = SDPUtil.filter_special_chars(v);
  7712. elem.attrs({ value: v });
  7713. }
  7714. elem.up();
  7715. });
  7716. } else {
  7717. elem.up();
  7718. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7719. elem.c('parameter');
  7720. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  7721. elem.up();
  7722. var msid = null;
  7723. if(mline.media == "audio")
  7724. {
  7725. msid = APP.RTC.localAudio.getId();
  7726. }
  7727. else
  7728. {
  7729. msid = APP.RTC.localVideo.getId();
  7730. }
  7731. if(msid != null)
  7732. {
  7733. msid = SDPUtil.filter_special_chars(msid);
  7734. elem.c('parameter');
  7735. elem.attrs({name: "msid", value:msid});
  7736. elem.up();
  7737. elem.c('parameter');
  7738. elem.attrs({name: "mslabel", value:msid});
  7739. elem.up();
  7740. elem.c('parameter');
  7741. elem.attrs({name: "label", value:msid});
  7742. elem.up();
  7743. }
  7744. }
  7745. elem.up();
  7746. // XEP-0339 handle ssrc-group attributes
  7747. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  7748. ssrc_group_lines.forEach(function(line) {
  7749. var idx = line.indexOf(' ');
  7750. var semantics = line.substr(0, idx).substr(13);
  7751. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7752. if (ssrcs.length) {
  7753. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7754. ssrcs.forEach(function(ssrc) {
  7755. elem.c('source', { ssrc: ssrc })
  7756. .up();
  7757. });
  7758. elem.up();
  7759. }
  7760. });
  7761. }
  7762. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  7763. elem.c('rtcp-mux').up();
  7764. }
  7765. // XEP-0293 -- map a=rtcp-fb:*
  7766. this.rtcpFbToJingle(i, elem, '*');
  7767. // XEP-0294
  7768. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  7769. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  7770. for (j = 0; j < lines.length; j++) {
  7771. tmp = SDPUtil.parse_extmap(lines[j]);
  7772. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  7773. uri: tmp.uri,
  7774. id: tmp.value });
  7775. if (tmp.hasOwnProperty('direction')) {
  7776. switch (tmp.direction) {
  7777. case 'sendonly':
  7778. elem.attrs({senders: 'responder'});
  7779. break;
  7780. case 'recvonly':
  7781. elem.attrs({senders: 'initiator'});
  7782. break;
  7783. case 'sendrecv':
  7784. elem.attrs({senders: 'both'});
  7785. break;
  7786. case 'inactive':
  7787. elem.attrs({senders: 'none'});
  7788. break;
  7789. }
  7790. }
  7791. // TODO: handle params
  7792. elem.up();
  7793. }
  7794. }
  7795. elem.up(); // end of description
  7796. }
  7797. // map ice-ufrag/pwd, dtls fingerprint, candidates
  7798. this.transportToJingle(i, elem);
  7799. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7800. elem.attrs({senders: 'both'});
  7801. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7802. elem.attrs({senders: 'initiator'});
  7803. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7804. elem.attrs({senders: 'responder'});
  7805. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7806. elem.attrs({senders: 'none'});
  7807. }
  7808. if (mline.port == '0') {
  7809. // estos hack to reject an m-line
  7810. elem.attrs({senders: 'rejected'});
  7811. }
  7812. elem.up(); // end of content
  7813. }
  7814. elem.up();
  7815. return elem;
  7816. };
  7817. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  7818. var tmp, sctpmap, sctpAttrs, fingerprints;
  7819. var self = this;
  7820. elem.c('transport');
  7821. // XEP-0343 DTLS/SCTP
  7822. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  7823. {
  7824. sctpmap = SDPUtil.find_line(
  7825. this.media[mediaindex], 'a=sctpmap:', self.session);
  7826. if (sctpmap)
  7827. {
  7828. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  7829. elem.c('sctpmap',
  7830. {
  7831. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  7832. number: sctpAttrs[0], /* SCTP port */
  7833. protocol: sctpAttrs[1] /* protocol */
  7834. });
  7835. // Optional stream count attribute
  7836. if (sctpAttrs.length > 2)
  7837. elem.attrs({ streams: sctpAttrs[2]});
  7838. elem.up();
  7839. }
  7840. }
  7841. // XEP-0320
  7842. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  7843. fingerprints.forEach(function(line) {
  7844. tmp = SDPUtil.parse_fingerprint(line);
  7845. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  7846. elem.c('fingerprint').t(tmp.fingerprint);
  7847. delete tmp.fingerprint;
  7848. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  7849. if (line) {
  7850. tmp.setup = line.substr(8);
  7851. }
  7852. elem.attrs(tmp);
  7853. elem.up(); // end of fingerprint
  7854. });
  7855. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  7856. if (tmp) {
  7857. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7858. elem.attrs(tmp);
  7859. // XEP-0176
  7860. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  7861. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  7862. lines.forEach(function (line) {
  7863. var candidate = SDPUtil.candidateToJingle(line);
  7864. var protocol = (candidate &&
  7865. typeof candidate.protocol === 'string')
  7866. ? candidate.protocol.toLowerCase() : '';
  7867. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  7868. (self.removeUdpCandidates && protocol === 'udp')) {
  7869. return;
  7870. }
  7871. elem.c('candidate', candidate).up();
  7872. });
  7873. }
  7874. }
  7875. elem.up(); // end of transport
  7876. }
  7877. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  7878. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  7879. lines.forEach(function (line) {
  7880. var tmp = SDPUtil.parse_rtcpfb(line);
  7881. if (tmp.type == 'trr-int') {
  7882. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  7883. elem.up();
  7884. } else {
  7885. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  7886. if (tmp.params.length > 0) {
  7887. elem.attrs({'subtype': tmp.params[0]});
  7888. }
  7889. elem.up();
  7890. }
  7891. });
  7892. };
  7893. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  7894. var media = '';
  7895. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7896. if (tmp.length) {
  7897. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  7898. if (tmp.attr('value')) {
  7899. media += tmp.attr('value');
  7900. } else {
  7901. media += '0';
  7902. }
  7903. media += '\r\n';
  7904. }
  7905. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7906. tmp.each(function () {
  7907. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  7908. if ($(this).attr('subtype')) {
  7909. media += ' ' + $(this).attr('subtype');
  7910. }
  7911. media += '\r\n';
  7912. });
  7913. return media;
  7914. };
  7915. // construct an SDP from a jingle stanza
  7916. SDP.prototype.fromJingle = function (jingle) {
  7917. var self = this;
  7918. this.raw = 'v=0\r\n' +
  7919. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  7920. 's=-\r\n' +
  7921. 't=0 0\r\n';
  7922. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  7923. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  7924. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  7925. var contents = $(group).find('>content').map(function (idx, content) {
  7926. return content.getAttribute('name');
  7927. }).get();
  7928. if (contents.length > 0) {
  7929. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  7930. }
  7931. });
  7932. }
  7933. this.session = this.raw;
  7934. jingle.find('>content').each(function () {
  7935. var m = self.jingle2media($(this));
  7936. self.media.push(m);
  7937. });
  7938. // reconstruct msid-semantic -- apparently not necessary
  7939. /*
  7940. var msid = SDPUtil.parse_ssrc(this.raw);
  7941. if (msid.hasOwnProperty('mslabel')) {
  7942. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  7943. }
  7944. */
  7945. this.raw = this.session + this.media.join('');
  7946. };
  7947. // translate a jingle content element into an an SDP media part
  7948. SDP.prototype.jingle2media = function (content) {
  7949. var media = '',
  7950. desc = content.find('description'),
  7951. ssrc = desc.attr('ssrc'),
  7952. self = this,
  7953. tmp;
  7954. var sctp = content.find(
  7955. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  7956. tmp = { media: desc.attr('media') };
  7957. tmp.port = '1';
  7958. if (content.attr('senders') == 'rejected') {
  7959. // estos hack to reject an m-line.
  7960. tmp.port = '0';
  7961. }
  7962. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  7963. if (sctp.length)
  7964. tmp.proto = 'DTLS/SCTP';
  7965. else
  7966. tmp.proto = 'RTP/SAVPF';
  7967. } else {
  7968. tmp.proto = 'RTP/AVPF';
  7969. }
  7970. if (!sctp.length) {
  7971. tmp.fmt = desc.find('payload-type').map(
  7972. function () { return this.getAttribute('id'); }).get();
  7973. media += SDPUtil.build_mline(tmp) + '\r\n';
  7974. } else {
  7975. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  7976. media += 'a=sctpmap:' + sctp.attr('number') +
  7977. ' ' + sctp.attr('protocol');
  7978. var streamCount = sctp.attr('streams');
  7979. if (streamCount)
  7980. media += ' ' + streamCount + '\r\n';
  7981. else
  7982. media += '\r\n';
  7983. }
  7984. media += 'c=IN IP4 0.0.0.0\r\n';
  7985. if (!sctp.length)
  7986. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  7987. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  7988. if (tmp.length) {
  7989. if (tmp.attr('ufrag')) {
  7990. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  7991. }
  7992. if (tmp.attr('pwd')) {
  7993. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  7994. }
  7995. tmp.find('>fingerprint').each(function () {
  7996. // FIXME: check namespace at some point
  7997. media += 'a=fingerprint:' + this.getAttribute('hash');
  7998. media += ' ' + $(this).text();
  7999. media += '\r\n';
  8000. if (this.getAttribute('setup')) {
  8001. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  8002. }
  8003. });
  8004. }
  8005. switch (content.attr('senders')) {
  8006. case 'initiator':
  8007. media += 'a=sendonly\r\n';
  8008. break;
  8009. case 'responder':
  8010. media += 'a=recvonly\r\n';
  8011. break;
  8012. case 'none':
  8013. media += 'a=inactive\r\n';
  8014. break;
  8015. case 'both':
  8016. media += 'a=sendrecv\r\n';
  8017. break;
  8018. }
  8019. media += 'a=mid:' + content.attr('name') + '\r\n';
  8020. // <description><rtcp-mux/></description>
  8021. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  8022. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  8023. if (desc.find('rtcp-mux').length) {
  8024. media += 'a=rtcp-mux\r\n';
  8025. }
  8026. if (desc.find('encryption').length) {
  8027. desc.find('encryption>crypto').each(function () {
  8028. media += 'a=crypto:' + this.getAttribute('tag');
  8029. media += ' ' + this.getAttribute('crypto-suite');
  8030. media += ' ' + this.getAttribute('key-params');
  8031. if (this.getAttribute('session-params')) {
  8032. media += ' ' + this.getAttribute('session-params');
  8033. }
  8034. media += '\r\n';
  8035. });
  8036. }
  8037. desc.find('payload-type').each(function () {
  8038. media += SDPUtil.build_rtpmap(this) + '\r\n';
  8039. if ($(this).find('>parameter').length) {
  8040. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  8041. media += $(this).find('parameter').map(function () {
  8042. return (this.getAttribute('name')
  8043. ? (this.getAttribute('name') + '=') : '') +
  8044. this.getAttribute('value');
  8045. }).get().join('; ');
  8046. media += '\r\n';
  8047. }
  8048. // xep-0293
  8049. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  8050. });
  8051. // xep-0293
  8052. media += self.rtcpFbFromJingle(desc, '*');
  8053. // xep-0294
  8054. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  8055. tmp.each(function () {
  8056. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  8057. });
  8058. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  8059. var protocol = this.getAttribute('protocol');
  8060. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  8061. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  8062. (self.removeUdpCandidates && protocol === 'udp')) {
  8063. return;
  8064. }
  8065. media += SDPUtil.candidateFromJingle(this);
  8066. });
  8067. // XEP-0339 handle ssrc-group attributes
  8068. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8069. var semantics = this.getAttribute('semantics');
  8070. var ssrcs = $(this).find('>source').map(function() {
  8071. return this.getAttribute('ssrc');
  8072. }).get();
  8073. if (ssrcs.length) {
  8074. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8075. }
  8076. });
  8077. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8078. tmp.each(function () {
  8079. var ssrc = this.getAttribute('ssrc');
  8080. $(this).find('>parameter').each(function () {
  8081. var name = this.getAttribute('name');
  8082. var value = this.getAttribute('value');
  8083. value = SDPUtil.filter_special_chars(value);
  8084. media += 'a=ssrc:' + ssrc + ' ' + name;
  8085. if (value && value.length)
  8086. media += ':' + value;
  8087. media += '\r\n';
  8088. });
  8089. });
  8090. return media;
  8091. };
  8092. module.exports = SDP;
  8093. }).call(this,"/modules/xmpp/SDP.js")
  8094. },{"./SDPUtil":32,"jitsi-meet-logger":47}],31:[function(require,module,exports){
  8095. var SDPUtil = require("./SDPUtil");
  8096. function SDPDiffer(mySDP, otherSDP)
  8097. {
  8098. this.mySDP = mySDP;
  8099. this.otherSDP = otherSDP;
  8100. }
  8101. /**
  8102. * Returns map of MediaChannel that contains media contained in
  8103. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  8104. */
  8105. SDPDiffer.prototype.getNewMedia = function() {
  8106. // this could be useful in Array.prototype.
  8107. function arrayEquals(array) {
  8108. // if the other array is a falsy value, return
  8109. if (!array)
  8110. return false;
  8111. // compare lengths - can save a lot of time
  8112. if (this.length != array.length)
  8113. return false;
  8114. for (var i = 0, l=this.length; i < l; i++) {
  8115. // Check if we have nested arrays
  8116. if (this[i] instanceof Array && array[i] instanceof Array) {
  8117. // recurse into the nested arrays
  8118. if (!this[i].equals(array[i]))
  8119. return false;
  8120. }
  8121. else if (this[i] != array[i]) {
  8122. // Warning - two different object instances will never be
  8123. // equal: {x:20} != {x:20}
  8124. return false;
  8125. }
  8126. }
  8127. return true;
  8128. }
  8129. var myMedias = this.mySDP.getMediaSsrcMap();
  8130. var othersMedias = this.otherSDP.getMediaSsrcMap();
  8131. var newMedia = {};
  8132. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  8133. var myMedia = myMedias[othersMediaIdx];
  8134. var othersMedia = othersMedias[othersMediaIdx];
  8135. if(!myMedia && othersMedia) {
  8136. // Add whole channel
  8137. newMedia[othersMediaIdx] = othersMedia;
  8138. return;
  8139. }
  8140. // Look for new ssrcs across the channel
  8141. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  8142. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  8143. // Allocate channel if we've found ssrc that doesn't exist in
  8144. // our channel
  8145. if(!newMedia[othersMediaIdx]){
  8146. newMedia[othersMediaIdx] = {
  8147. mediaindex: othersMedia.mediaindex,
  8148. mid: othersMedia.mid,
  8149. ssrcs: {},
  8150. ssrcGroups: []
  8151. };
  8152. }
  8153. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  8154. }
  8155. });
  8156. // Look for new ssrc groups across the channels
  8157. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  8158. // try to match the other ssrc-group with an ssrc-group of ours
  8159. var matched = false;
  8160. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  8161. var mySsrcGroup = myMedia.ssrcGroups[i];
  8162. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  8163. arrayEquals.apply(otherSsrcGroup.ssrcs,
  8164. [mySsrcGroup.ssrcs])) {
  8165. matched = true;
  8166. break;
  8167. }
  8168. }
  8169. if (!matched) {
  8170. // Allocate channel if we've found an ssrc-group that doesn't
  8171. // exist in our channel
  8172. if(!newMedia[othersMediaIdx]){
  8173. newMedia[othersMediaIdx] = {
  8174. mediaindex: othersMedia.mediaindex,
  8175. mid: othersMedia.mid,
  8176. ssrcs: {},
  8177. ssrcGroups: []
  8178. };
  8179. }
  8180. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8181. }
  8182. });
  8183. });
  8184. return newMedia;
  8185. };
  8186. /**
  8187. * TODO: document!
  8188. */
  8189. SDPDiffer.prototype.toJingle = function(modify) {
  8190. var sdpMediaSsrcs = this.getNewMedia();
  8191. var modified = false;
  8192. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8193. modified = true;
  8194. var media = sdpMediaSsrcs[mediaindex];
  8195. modify.c('content', {name: media.mid});
  8196. modify.c('description',
  8197. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8198. // FIXME: not completely sure this operates on blocks and / or handles
  8199. // different ssrcs correctly
  8200. // generate sources from lines
  8201. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8202. var mediaSsrc = media.ssrcs[ssrcNum];
  8203. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8204. modify.attrs({ssrc: mediaSsrc.ssrc});
  8205. // iterate over ssrc lines
  8206. mediaSsrc.lines.forEach(function (line) {
  8207. var idx = line.indexOf(' ');
  8208. var kv = line.substr(idx + 1);
  8209. modify.c('parameter');
  8210. if (kv.indexOf(':') == -1) {
  8211. modify.attrs({ name: kv });
  8212. } else {
  8213. var nv = kv.split(':', 2);
  8214. var name = nv[0];
  8215. var value = SDPUtil.filter_special_chars(nv[1]);
  8216. modify.attrs({ name: name });
  8217. modify.attrs({ value: value });
  8218. }
  8219. modify.up(); // end of parameter
  8220. });
  8221. modify.up(); // end of source
  8222. });
  8223. // generate source groups from lines
  8224. media.ssrcGroups.forEach(function(ssrcGroup) {
  8225. if (ssrcGroup.ssrcs.length) {
  8226. modify.c('ssrc-group', {
  8227. semantics: ssrcGroup.semantics,
  8228. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8229. });
  8230. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8231. modify.c('source', { ssrc: ssrc })
  8232. .up(); // end of source
  8233. });
  8234. modify.up(); // end of ssrc-group
  8235. }
  8236. });
  8237. modify.up(); // end of description
  8238. modify.up(); // end of content
  8239. });
  8240. return modified;
  8241. };
  8242. module.exports = SDPDiffer;
  8243. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8244. (function (__filename){
  8245. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8246. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8247. SDPUtil = {
  8248. filter_special_chars: function (text) {
  8249. return text.replace(/[\\\/\{,\}\+]/g, "");
  8250. },
  8251. iceparams: function (mediadesc, sessiondesc) {
  8252. var data = null;
  8253. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8254. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8255. data = {
  8256. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8257. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8258. };
  8259. }
  8260. return data;
  8261. },
  8262. parse_iceufrag: function (line) {
  8263. return line.substring(12);
  8264. },
  8265. build_iceufrag: function (frag) {
  8266. return 'a=ice-ufrag:' + frag;
  8267. },
  8268. parse_icepwd: function (line) {
  8269. return line.substring(10);
  8270. },
  8271. build_icepwd: function (pwd) {
  8272. return 'a=ice-pwd:' + pwd;
  8273. },
  8274. parse_mid: function (line) {
  8275. return line.substring(6);
  8276. },
  8277. parse_mline: function (line) {
  8278. var parts = line.substring(2).split(' '),
  8279. data = {};
  8280. data.media = parts.shift();
  8281. data.port = parts.shift();
  8282. data.proto = parts.shift();
  8283. if (parts[parts.length - 1] === '') { // trailing whitespace
  8284. parts.pop();
  8285. }
  8286. data.fmt = parts;
  8287. return data;
  8288. },
  8289. build_mline: function (mline) {
  8290. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8291. },
  8292. parse_rtpmap: function (line) {
  8293. var parts = line.substring(9).split(' '),
  8294. data = {};
  8295. data.id = parts.shift();
  8296. parts = parts[0].split('/');
  8297. data.name = parts.shift();
  8298. data.clockrate = parts.shift();
  8299. data.channels = parts.length ? parts.shift() : '1';
  8300. return data;
  8301. },
  8302. /**
  8303. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8304. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8305. * @returns [SCTP port number, protocol, streams]
  8306. */
  8307. parse_sctpmap: function (line)
  8308. {
  8309. var parts = line.substring(10).split(' ');
  8310. var sctpPort = parts[0];
  8311. var protocol = parts[1];
  8312. // Stream count is optional
  8313. var streamCount = parts.length > 2 ? parts[2] : null;
  8314. return [sctpPort, protocol, streamCount];// SCTP port
  8315. },
  8316. build_rtpmap: function (el) {
  8317. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8318. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8319. line += '/' + el.getAttribute('channels');
  8320. }
  8321. return line;
  8322. },
  8323. parse_crypto: function (line) {
  8324. var parts = line.substring(9).split(' '),
  8325. data = {};
  8326. data.tag = parts.shift();
  8327. data['crypto-suite'] = parts.shift();
  8328. data['key-params'] = parts.shift();
  8329. if (parts.length) {
  8330. data['session-params'] = parts.join(' ');
  8331. }
  8332. return data;
  8333. },
  8334. parse_fingerprint: function (line) { // RFC 4572
  8335. var parts = line.substring(14).split(' '),
  8336. data = {};
  8337. data.hash = parts.shift();
  8338. data.fingerprint = parts.shift();
  8339. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8340. return data;
  8341. },
  8342. parse_fmtp: function (line) {
  8343. var parts = line.split(' '),
  8344. i, key, value,
  8345. data = [];
  8346. parts.shift();
  8347. parts = parts.join(' ').split(';');
  8348. for (i = 0; i < parts.length; i++) {
  8349. key = parts[i].split('=')[0];
  8350. while (key.length && key[0] == ' ') {
  8351. key = key.substring(1);
  8352. }
  8353. value = parts[i].split('=')[1];
  8354. if (key && value) {
  8355. data.push({name: key, value: value});
  8356. } else if (key) {
  8357. // rfc 4733 (DTMF) style stuff
  8358. data.push({name: '', value: key});
  8359. }
  8360. }
  8361. return data;
  8362. },
  8363. parse_icecandidate: function (line) {
  8364. var candidate = {},
  8365. elems = line.split(' ');
  8366. candidate.foundation = elems[0].substring(12);
  8367. candidate.component = elems[1];
  8368. candidate.protocol = elems[2].toLowerCase();
  8369. candidate.priority = elems[3];
  8370. candidate.ip = elems[4];
  8371. candidate.port = elems[5];
  8372. // elems[6] => "typ"
  8373. candidate.type = elems[7];
  8374. candidate.generation = 0; // default value, may be overwritten below
  8375. for (var i = 8; i < elems.length; i += 2) {
  8376. switch (elems[i]) {
  8377. case 'raddr':
  8378. candidate['rel-addr'] = elems[i + 1];
  8379. break;
  8380. case 'rport':
  8381. candidate['rel-port'] = elems[i + 1];
  8382. break;
  8383. case 'generation':
  8384. candidate.generation = elems[i + 1];
  8385. break;
  8386. case 'tcptype':
  8387. candidate.tcptype = elems[i + 1];
  8388. break;
  8389. default: // TODO
  8390. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8391. }
  8392. }
  8393. candidate.network = '1';
  8394. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8395. return candidate;
  8396. },
  8397. build_icecandidate: function (cand) {
  8398. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8399. line += ' ';
  8400. switch (cand.type) {
  8401. case 'srflx':
  8402. case 'prflx':
  8403. case 'relay':
  8404. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8405. line += 'raddr';
  8406. line += ' ';
  8407. line += cand['rel-addr'];
  8408. line += ' ';
  8409. line += 'rport';
  8410. line += ' ';
  8411. line += cand['rel-port'];
  8412. line += ' ';
  8413. }
  8414. break;
  8415. }
  8416. if (cand.hasOwnAttribute('tcptype')) {
  8417. line += 'tcptype';
  8418. line += ' ';
  8419. line += cand.tcptype;
  8420. line += ' ';
  8421. }
  8422. line += 'generation';
  8423. line += ' ';
  8424. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8425. return line;
  8426. },
  8427. parse_ssrc: function (desc) {
  8428. // proprietary mapping of a=ssrc lines
  8429. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8430. // and parse according to that
  8431. var lines = desc.split('\r\n'),
  8432. data = {};
  8433. for (var i = 0; i < lines.length; i++) {
  8434. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8435. var idx = lines[i].indexOf(' ');
  8436. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8437. }
  8438. }
  8439. return data;
  8440. },
  8441. parse_rtcpfb: function (line) {
  8442. var parts = line.substr(10).split(' ');
  8443. var data = {};
  8444. data.pt = parts.shift();
  8445. data.type = parts.shift();
  8446. data.params = parts;
  8447. return data;
  8448. },
  8449. parse_extmap: function (line) {
  8450. var parts = line.substr(9).split(' ');
  8451. var data = {};
  8452. data.value = parts.shift();
  8453. if (data.value.indexOf('/') != -1) {
  8454. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8455. data.value = data.value.substr(0, data.value.indexOf('/'));
  8456. } else {
  8457. data.direction = 'both';
  8458. }
  8459. data.uri = parts.shift();
  8460. data.params = parts;
  8461. return data;
  8462. },
  8463. find_line: function (haystack, needle, sessionpart) {
  8464. var lines = haystack.split('\r\n');
  8465. for (var i = 0; i < lines.length; i++) {
  8466. if (lines[i].substring(0, needle.length) == needle) {
  8467. return lines[i];
  8468. }
  8469. }
  8470. if (!sessionpart) {
  8471. return false;
  8472. }
  8473. // search session part
  8474. lines = sessionpart.split('\r\n');
  8475. for (var j = 0; j < lines.length; j++) {
  8476. if (lines[j].substring(0, needle.length) == needle) {
  8477. return lines[j];
  8478. }
  8479. }
  8480. return false;
  8481. },
  8482. find_lines: function (haystack, needle, sessionpart) {
  8483. var lines = haystack.split('\r\n'),
  8484. needles = [];
  8485. for (var i = 0; i < lines.length; i++) {
  8486. if (lines[i].substring(0, needle.length) == needle)
  8487. needles.push(lines[i]);
  8488. }
  8489. if (needles.length || !sessionpart) {
  8490. return needles;
  8491. }
  8492. // search session part
  8493. lines = sessionpart.split('\r\n');
  8494. for (var j = 0; j < lines.length; j++) {
  8495. if (lines[j].substring(0, needle.length) == needle) {
  8496. needles.push(lines[j]);
  8497. }
  8498. }
  8499. return needles;
  8500. },
  8501. candidateToJingle: function (line) {
  8502. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8503. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8504. if (line.indexOf('candidate:') === 0) {
  8505. line = 'a=' + line;
  8506. } else if (line.substring(0, 12) != 'a=candidate:') {
  8507. logger.log('parseCandidate called with a line that is not a candidate line');
  8508. logger.log(line);
  8509. return null;
  8510. }
  8511. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8512. line = line.substring(0, line.length - 2);
  8513. var candidate = {},
  8514. elems = line.split(' '),
  8515. i;
  8516. if (elems[6] != 'typ') {
  8517. logger.log('did not find typ in the right place');
  8518. logger.log(line);
  8519. return null;
  8520. }
  8521. candidate.foundation = elems[0].substring(12);
  8522. candidate.component = elems[1];
  8523. candidate.protocol = elems[2].toLowerCase();
  8524. candidate.priority = elems[3];
  8525. candidate.ip = elems[4];
  8526. candidate.port = elems[5];
  8527. // elems[6] => "typ"
  8528. candidate.type = elems[7];
  8529. candidate.generation = '0'; // default, may be overwritten below
  8530. for (i = 8; i < elems.length; i += 2) {
  8531. switch (elems[i]) {
  8532. case 'raddr':
  8533. candidate['rel-addr'] = elems[i + 1];
  8534. break;
  8535. case 'rport':
  8536. candidate['rel-port'] = elems[i + 1];
  8537. break;
  8538. case 'generation':
  8539. candidate.generation = elems[i + 1];
  8540. break;
  8541. case 'tcptype':
  8542. candidate.tcptype = elems[i + 1];
  8543. break;
  8544. default: // TODO
  8545. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8546. }
  8547. }
  8548. candidate.network = '1';
  8549. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8550. return candidate;
  8551. },
  8552. candidateFromJingle: function (cand) {
  8553. var line = 'a=candidate:';
  8554. line += cand.getAttribute('foundation');
  8555. line += ' ';
  8556. line += cand.getAttribute('component');
  8557. line += ' ';
  8558. var protocol = cand.getAttribute('protocol');
  8559. // use tcp candidates for FF
  8560. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  8561. protocol = 'tcp';
  8562. }
  8563. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  8564. line += ' ';
  8565. line += cand.getAttribute('priority');
  8566. line += ' ';
  8567. line += cand.getAttribute('ip');
  8568. line += ' ';
  8569. line += cand.getAttribute('port');
  8570. line += ' ';
  8571. line += 'typ';
  8572. line += ' ' + cand.getAttribute('type');
  8573. line += ' ';
  8574. switch (cand.getAttribute('type')) {
  8575. case 'srflx':
  8576. case 'prflx':
  8577. case 'relay':
  8578. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  8579. line += 'raddr';
  8580. line += ' ';
  8581. line += cand.getAttribute('rel-addr');
  8582. line += ' ';
  8583. line += 'rport';
  8584. line += ' ';
  8585. line += cand.getAttribute('rel-port');
  8586. line += ' ';
  8587. }
  8588. break;
  8589. }
  8590. if (protocol.toLowerCase() == 'tcp') {
  8591. line += 'tcptype';
  8592. line += ' ';
  8593. line += cand.getAttribute('tcptype');
  8594. line += ' ';
  8595. }
  8596. line += 'generation';
  8597. line += ' ';
  8598. line += cand.getAttribute('generation') || '0';
  8599. return line + '\r\n';
  8600. }
  8601. };
  8602. module.exports = SDPUtil;
  8603. }).call(this,"/modules/xmpp/SDPUtil.js")
  8604. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],33:[function(require,module,exports){
  8605. (function (__filename){
  8606. /* global $ */
  8607. var RTC = require('../RTC/RTC');
  8608. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8609. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  8610. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8611. var SSRCReplacement = require("./LocalSSRCReplacement");
  8612. function TraceablePeerConnection(ice_config, constraints, session) {
  8613. var self = this;
  8614. this.session = session;
  8615. var RTCPeerConnectionType = null;
  8616. if (RTCBrowserType.isFirefox()) {
  8617. RTCPeerConnectionType = mozRTCPeerConnection;
  8618. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  8619. RTCPeerConnectionType = RTCPeerConnection;
  8620. } else {
  8621. RTCPeerConnectionType = webkitRTCPeerConnection;
  8622. }
  8623. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  8624. this.updateLog = [];
  8625. this.stats = {};
  8626. this.statsinterval = null;
  8627. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  8628. var Interop = require('sdp-interop').Interop;
  8629. this.interop = new Interop();
  8630. var Simulcast = require('sdp-simulcast');
  8631. this.simulcast = new Simulcast({numOfLayers: 2, explodeRemoteSimulcast: false});
  8632. // override as desired
  8633. this.trace = function (what, info) {
  8634. /*logger.warn('WTRACE', what, info);
  8635. if (info && RTCBrowserType.isIExplorer()) {
  8636. if (info.length > 1024) {
  8637. logger.warn('WTRACE', what, info.substr(1024));
  8638. }
  8639. if (info.length > 2048) {
  8640. logger.warn('WTRACE', what, info.substr(2048));
  8641. }
  8642. }*/
  8643. self.updateLog.push({
  8644. time: new Date(),
  8645. type: what,
  8646. value: info || ""
  8647. });
  8648. };
  8649. this.onicecandidate = null;
  8650. this.peerconnection.onicecandidate = function (event) {
  8651. // FIXME: this causes stack overflow with Temasys Plugin
  8652. if (!RTCBrowserType.isTemasysPluginUsed())
  8653. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  8654. if (self.onicecandidate !== null) {
  8655. self.onicecandidate(event);
  8656. }
  8657. };
  8658. this.onaddstream = null;
  8659. this.peerconnection.onaddstream = function (event) {
  8660. self.trace('onaddstream', event.stream.id);
  8661. if (self.onaddstream !== null) {
  8662. self.onaddstream(event);
  8663. }
  8664. };
  8665. this.onremovestream = null;
  8666. this.peerconnection.onremovestream = function (event) {
  8667. self.trace('onremovestream', event.stream.id);
  8668. if (self.onremovestream !== null) {
  8669. self.onremovestream(event);
  8670. }
  8671. };
  8672. this.onsignalingstatechange = null;
  8673. this.peerconnection.onsignalingstatechange = function (event) {
  8674. self.trace('onsignalingstatechange', self.signalingState);
  8675. if (self.onsignalingstatechange !== null) {
  8676. self.onsignalingstatechange(event);
  8677. }
  8678. };
  8679. this.oniceconnectionstatechange = null;
  8680. this.peerconnection.oniceconnectionstatechange = function (event) {
  8681. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  8682. if (self.oniceconnectionstatechange !== null) {
  8683. self.oniceconnectionstatechange(event);
  8684. }
  8685. };
  8686. this.onnegotiationneeded = null;
  8687. this.peerconnection.onnegotiationneeded = function (event) {
  8688. self.trace('onnegotiationneeded');
  8689. if (self.onnegotiationneeded !== null) {
  8690. self.onnegotiationneeded(event);
  8691. }
  8692. };
  8693. self.ondatachannel = null;
  8694. this.peerconnection.ondatachannel = function (event) {
  8695. self.trace('ondatachannel', event);
  8696. if (self.ondatachannel !== null) {
  8697. self.ondatachannel(event);
  8698. }
  8699. };
  8700. // XXX: do all non-firefox browsers which we support also support this?
  8701. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  8702. this.statsinterval = window.setInterval(function() {
  8703. self.peerconnection.getStats(function(stats) {
  8704. var results = stats.result();
  8705. var now = new Date();
  8706. for (var i = 0; i < results.length; ++i) {
  8707. results[i].names().forEach(function (name) {
  8708. var id = results[i].id + '-' + name;
  8709. if (!self.stats[id]) {
  8710. self.stats[id] = {
  8711. startTime: now,
  8712. endTime: now,
  8713. values: [],
  8714. times: []
  8715. };
  8716. }
  8717. self.stats[id].values.push(results[i].stat(name));
  8718. self.stats[id].times.push(now.getTime());
  8719. if (self.stats[id].values.length > self.maxstats) {
  8720. self.stats[id].values.shift();
  8721. self.stats[id].times.shift();
  8722. }
  8723. self.stats[id].endTime = now;
  8724. });
  8725. }
  8726. });
  8727. }, 1000);
  8728. }
  8729. }
  8730. /**
  8731. * Returns a string representation of a SessionDescription object.
  8732. */
  8733. var dumpSDP = function(description) {
  8734. if (typeof description === 'undefined' || description == null) {
  8735. return '';
  8736. }
  8737. return 'type: ' + description.type + '\r\n' + description.sdp;
  8738. };
  8739. /**
  8740. * Takes a SessionDescription object and returns a "normalized" version.
  8741. * Currently it only takes care of ordering the a=ssrc lines.
  8742. */
  8743. var normalizePlanB = function(desc) {
  8744. if (typeof desc !== 'object' || desc === null ||
  8745. typeof desc.sdp !== 'string') {
  8746. logger.warn('An empty description was passed as an argument.');
  8747. return desc;
  8748. }
  8749. var transform = require('sdp-transform');
  8750. var session = transform.parse(desc.sdp);
  8751. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  8752. Array.isArray(session.media)) {
  8753. session.media.forEach(function (mLine) {
  8754. // Chrome appears to be picky about the order in which a=ssrc lines
  8755. // are listed in an m-line when rtx is enabled (and thus there are
  8756. // a=ssrc-group lines with FID semantics). Specifically if we have
  8757. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  8758. // the "a=ssrc:S1" lines, SRD fails.
  8759. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  8760. // first.
  8761. var firstSsrcs = [];
  8762. var newSsrcLines = [];
  8763. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  8764. mLine.ssrcGroups.forEach(function (group) {
  8765. if (typeof group.semantics !== 'undefined' &&
  8766. group.semantics === 'FID') {
  8767. if (typeof group.ssrcs !== 'undefined') {
  8768. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  8769. }
  8770. }
  8771. });
  8772. }
  8773. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  8774. var i;
  8775. for (i = 0; i<mLine.ssrcs.length; i++){
  8776. if (typeof mLine.ssrcs[i] === 'object'
  8777. && typeof mLine.ssrcs[i].id !== 'undefined'
  8778. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  8779. newSsrcLines.push(mLine.ssrcs[i]);
  8780. delete mLine.ssrcs[i];
  8781. }
  8782. }
  8783. for (i = 0; i<mLine.ssrcs.length; i++){
  8784. if (typeof mLine.ssrcs[i] !== 'undefined') {
  8785. newSsrcLines.push(mLine.ssrcs[i]);
  8786. }
  8787. }
  8788. mLine.ssrcs = newSsrcLines;
  8789. }
  8790. });
  8791. }
  8792. var resStr = transform.write(session);
  8793. return new RTCSessionDescription({
  8794. type: desc.type,
  8795. sdp: resStr
  8796. });
  8797. };
  8798. var getters = {
  8799. signalingState: function () {
  8800. return this.peerconnection.signalingState;
  8801. },
  8802. iceConnectionState: function () {
  8803. return this.peerconnection.iceConnectionState;
  8804. },
  8805. localDescription: function() {
  8806. var desc = this.peerconnection.localDescription;
  8807. // FIXME this should probably be after the Unified Plan -> Plan B
  8808. // transformation.
  8809. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  8810. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  8811. // if we're running on FF, transform to Plan B first.
  8812. if (RTCBrowserType.usesUnifiedPlan()) {
  8813. desc = this.interop.toPlanB(desc);
  8814. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  8815. }
  8816. return desc;
  8817. },
  8818. remoteDescription: function() {
  8819. var desc = this.peerconnection.remoteDescription;
  8820. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  8821. // if we're running on FF, transform to Plan B first.
  8822. if (RTCBrowserType.usesUnifiedPlan()) {
  8823. desc = this.interop.toPlanB(desc);
  8824. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  8825. }
  8826. return desc;
  8827. }
  8828. };
  8829. Object.keys(getters).forEach(function (prop) {
  8830. Object.defineProperty(
  8831. TraceablePeerConnection.prototype,
  8832. prop, {
  8833. get: getters[prop]
  8834. }
  8835. );
  8836. });
  8837. TraceablePeerConnection.prototype.addStream = function (stream) {
  8838. this.trace('addStream', stream.id);
  8839. try
  8840. {
  8841. this.peerconnection.addStream(stream);
  8842. }
  8843. catch (e)
  8844. {
  8845. logger.error(e);
  8846. }
  8847. };
  8848. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  8849. this.trace('removeStream', stream.id);
  8850. if(stopStreams) {
  8851. RTC.stopMediaStream(stream);
  8852. }
  8853. try {
  8854. // FF doesn't support this yet.
  8855. if (this.peerconnection.removeStream)
  8856. this.peerconnection.removeStream(stream);
  8857. } catch (e) {
  8858. logger.error(e);
  8859. }
  8860. };
  8861. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  8862. this.trace('createDataChannel', label, opts);
  8863. return this.peerconnection.createDataChannel(label, opts);
  8864. };
  8865. TraceablePeerConnection.prototype.setLocalDescription
  8866. = function (description, successCallback, failureCallback) {
  8867. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  8868. // if we're running on FF, transform to Plan A first.
  8869. if (RTCBrowserType.usesUnifiedPlan()) {
  8870. description = this.interop.toUnifiedPlan(description);
  8871. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  8872. }
  8873. var self = this;
  8874. this.peerconnection.setLocalDescription(description,
  8875. function () {
  8876. self.trace('setLocalDescriptionOnSuccess');
  8877. successCallback();
  8878. },
  8879. function (err) {
  8880. self.trace('setLocalDescriptionOnFailure', err);
  8881. failureCallback(err);
  8882. }
  8883. );
  8884. /*
  8885. if (this.statsinterval === null && this.maxstats > 0) {
  8886. // start gathering stats
  8887. }
  8888. */
  8889. };
  8890. TraceablePeerConnection.prototype.setRemoteDescription
  8891. = function (description, successCallback, failureCallback) {
  8892. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  8893. // TODO the focus should squeze or explode the remote simulcast
  8894. description = this.simulcast.mungeRemoteDescription(description);
  8895. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  8896. // if we're running on FF, transform to Plan A first.
  8897. if (RTCBrowserType.usesUnifiedPlan()) {
  8898. description = this.interop.toUnifiedPlan(description);
  8899. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  8900. }
  8901. if (RTCBrowserType.usesPlanB()) {
  8902. description = normalizePlanB(description);
  8903. }
  8904. var self = this;
  8905. this.peerconnection.setRemoteDescription(description,
  8906. function () {
  8907. self.trace('setRemoteDescriptionOnSuccess');
  8908. successCallback();
  8909. },
  8910. function (err) {
  8911. self.trace('setRemoteDescriptionOnFailure', err);
  8912. failureCallback(err);
  8913. }
  8914. );
  8915. /*
  8916. if (this.statsinterval === null && this.maxstats > 0) {
  8917. // start gathering stats
  8918. }
  8919. */
  8920. };
  8921. TraceablePeerConnection.prototype.close = function () {
  8922. this.trace('stop');
  8923. if (this.statsinterval !== null) {
  8924. window.clearInterval(this.statsinterval);
  8925. this.statsinterval = null;
  8926. }
  8927. this.peerconnection.close();
  8928. };
  8929. TraceablePeerConnection.prototype.createOffer
  8930. = function (successCallback, failureCallback, constraints) {
  8931. var self = this;
  8932. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  8933. this.peerconnection.createOffer(
  8934. function (offer) {
  8935. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  8936. // NOTE this is not tested because in meet the focus generates the
  8937. // offer.
  8938. // if we're running on FF, transform to Plan B first.
  8939. if (RTCBrowserType.usesUnifiedPlan()) {
  8940. offer = self.interop.toPlanB(offer);
  8941. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  8942. }
  8943. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  8944. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8945. offer = self.simulcast.mungeLocalDescription(offer);
  8946. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  8947. }
  8948. successCallback(offer);
  8949. },
  8950. function(err) {
  8951. self.trace('createOfferOnFailure', err);
  8952. failureCallback(err);
  8953. },
  8954. constraints
  8955. );
  8956. };
  8957. TraceablePeerConnection.prototype.createAnswer
  8958. = function (successCallback, failureCallback, constraints) {
  8959. var self = this;
  8960. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  8961. this.peerconnection.createAnswer(
  8962. function (answer) {
  8963. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  8964. // if we're running on FF, transform to Plan A first.
  8965. if (RTCBrowserType.usesUnifiedPlan()) {
  8966. answer = self.interop.toPlanB(answer);
  8967. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  8968. }
  8969. // munge local video SSRC
  8970. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  8971. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8972. answer = self.simulcast.mungeLocalDescription(answer);
  8973. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  8974. }
  8975. successCallback(answer);
  8976. },
  8977. function(err) {
  8978. self.trace('createAnswerOnFailure', err);
  8979. failureCallback(err);
  8980. },
  8981. constraints
  8982. );
  8983. };
  8984. TraceablePeerConnection.prototype.addIceCandidate
  8985. = function (candidate, successCallback, failureCallback) {
  8986. //var self = this;
  8987. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  8988. this.peerconnection.addIceCandidate(candidate);
  8989. /* maybe later
  8990. this.peerconnection.addIceCandidate(candidate,
  8991. function () {
  8992. self.trace('addIceCandidateOnSuccess');
  8993. successCallback();
  8994. },
  8995. function (err) {
  8996. self.trace('addIceCandidateOnFailure', err);
  8997. failureCallback(err);
  8998. }
  8999. );
  9000. */
  9001. };
  9002. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  9003. // TODO: Is this the correct way to handle Opera, Temasys?
  9004. if (RTCBrowserType.isFirefox()) {
  9005. // ignore for now...
  9006. if(!errback)
  9007. errback = function () {};
  9008. this.peerconnection.getStats(null, callback, errback);
  9009. } else {
  9010. this.peerconnection.getStats(callback);
  9011. }
  9012. };
  9013. module.exports = TraceablePeerConnection;
  9014. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  9015. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"./LocalSSRCReplacement":29,"jitsi-meet-logger":47,"sdp-interop":65,"sdp-simulcast":68,"sdp-transform":75}],34:[function(require,module,exports){
  9016. (function (__filename){
  9017. /* global $, $iq, APP, config, messageHandler,
  9018. roomName, sessionTerminated, Strophe, Util */
  9019. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9020. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9021. var Settings = require("../settings/Settings");
  9022. var AuthenticationEvents
  9023. = require("../../service/authentication/AuthenticationEvents");
  9024. function createExpBackoffTimer(step) {
  9025. var count = 1;
  9026. return function (reset) {
  9027. // Reset call
  9028. if (reset) {
  9029. count = 1;
  9030. return;
  9031. }
  9032. // Calculate next timeout
  9033. var timeout = Math.pow(2, count - 1);
  9034. count += 1;
  9035. return timeout * step;
  9036. };
  9037. }
  9038. function Moderator(roomName, xmpp, emitter) {
  9039. this.roomName = roomName;
  9040. this.xmppService = xmpp;
  9041. this.getNextTimeout = createExpBackoffTimer(1000);
  9042. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  9043. // External authentication stuff
  9044. this.externalAuthEnabled = false;
  9045. this.settings = new Settings(roomName);
  9046. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  9047. // it will be enabled automatically if focus detects the component through
  9048. // service discovery.
  9049. this.sipGatewayEnabled =
  9050. this.xmppService.options.hosts.call_control !== undefined;
  9051. this.eventEmitter = emitter;
  9052. this.connection = this.xmppService.connection;
  9053. this.focusUserJid;
  9054. //FIXME:
  9055. // Message listener that talks to POPUP window
  9056. function listener(event) {
  9057. if (event.data && event.data.sessionId) {
  9058. if (event.origin !== window.location.origin) {
  9059. logger.warn("Ignoring sessionId from different origin: " +
  9060. event.origin);
  9061. return;
  9062. }
  9063. localStorage.setItem('sessionId', event.data.sessionId);
  9064. // After popup is closed we will authenticate
  9065. }
  9066. }
  9067. // Register
  9068. if (window.addEventListener) {
  9069. window.addEventListener("message", listener, false);
  9070. } else {
  9071. window.attachEvent("onmessage", listener);
  9072. }
  9073. }
  9074. Moderator.prototype.isExternalAuthEnabled = function () {
  9075. return this.externalAuthEnabled;
  9076. };
  9077. Moderator.prototype.isSipGatewayEnabled = function () {
  9078. return this.sipGatewayEnabled;
  9079. };
  9080. Moderator.prototype.onMucMemberLeft = function (jid) {
  9081. logger.info("Someone left is it focus ? " + jid);
  9082. var resource = Strophe.getResourceFromJid(jid);
  9083. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  9084. logger.info(
  9085. "Focus has left the room - leaving conference");
  9086. //hangUp();
  9087. // We'd rather reload to have everything re-initialized
  9088. //FIXME: show some message before reload
  9089. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  9090. }
  9091. };
  9092. Moderator.prototype.setFocusUserJid = function (focusJid) {
  9093. if (!this.focusUserJid) {
  9094. this.focusUserJid = focusJid;
  9095. logger.info("Focus jid set to: " + this.focusUserJid);
  9096. }
  9097. };
  9098. Moderator.prototype.getFocusUserJid = function () {
  9099. return this.focusUserJid;
  9100. };
  9101. Moderator.prototype.getFocusComponent = function () {
  9102. // Get focus component address
  9103. var focusComponent = this.xmppService.options.hosts.focus;
  9104. // If not specified use default: 'focus.domain'
  9105. if (!focusComponent) {
  9106. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  9107. }
  9108. return focusComponent;
  9109. };
  9110. Moderator.prototype.createConferenceIq = function () {
  9111. // Generate create conference IQ
  9112. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  9113. // Session Id used for authentication
  9114. var sessionId = localStorage.getItem('sessionId');
  9115. var machineUID = this.settings.getSettings().uid;
  9116. logger.info(
  9117. "Session ID: " + sessionId + " machine UID: " + machineUID);
  9118. elem.c('conference', {
  9119. xmlns: 'http://jitsi.org/protocol/focus',
  9120. room: this.roomName,
  9121. 'machine-uid': machineUID
  9122. });
  9123. if (sessionId) {
  9124. elem.attrs({ 'session-id': sessionId});
  9125. }
  9126. if (this.xmppService.options.hosts.bridge !== undefined) {
  9127. elem.c(
  9128. 'property', {
  9129. name: 'bridge',
  9130. value: this.xmppService.options.hosts.bridge
  9131. }).up();
  9132. }
  9133. if (this.xmppService.options.enforcedBridge !== undefined) {
  9134. elem.c(
  9135. 'property', {
  9136. name: 'enforcedBridge',
  9137. value: this.xmppService.options.enforcedBridge
  9138. }).up();
  9139. }
  9140. // Tell the focus we have Jigasi configured
  9141. if (this.xmppService.options.hosts.call_control !== undefined) {
  9142. elem.c(
  9143. 'property', {
  9144. name: 'call_control',
  9145. value: this.xmppService.options.hosts.call_control
  9146. }).up();
  9147. }
  9148. if (this.xmppService.options.channelLastN !== undefined) {
  9149. elem.c(
  9150. 'property', {
  9151. name: 'channelLastN',
  9152. value: this.xmppService.options.channelLastN
  9153. }).up();
  9154. }
  9155. if (this.xmppService.options.adaptiveLastN !== undefined) {
  9156. elem.c(
  9157. 'property', {
  9158. name: 'adaptiveLastN',
  9159. value: this.xmppService.options.adaptiveLastN
  9160. }).up();
  9161. }
  9162. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  9163. elem.c(
  9164. 'property', {
  9165. name: 'adaptiveSimulcast',
  9166. value: this.xmppService.options.adaptiveSimulcast
  9167. }).up();
  9168. }
  9169. if (this.xmppService.options.openSctp !== undefined) {
  9170. elem.c(
  9171. 'property', {
  9172. name: 'openSctp',
  9173. value: this.xmppService.options.openSctp
  9174. }).up();
  9175. }
  9176. if (this.xmppService.options.startAudioMuted !== undefined)
  9177. {
  9178. elem.c(
  9179. 'property', {
  9180. name: 'startAudioMuted',
  9181. value: this.xmppService.options.startAudioMuted
  9182. }).up();
  9183. }
  9184. if (this.xmppService.options.startVideoMuted !== undefined)
  9185. {
  9186. elem.c(
  9187. 'property', {
  9188. name: 'startVideoMuted',
  9189. value: this.xmppService.options.startVideoMuted
  9190. }).up();
  9191. }
  9192. elem.c(
  9193. 'property', {
  9194. name: 'simulcastMode',
  9195. value: 'rewriting'
  9196. }).up();
  9197. elem.up();
  9198. return elem;
  9199. };
  9200. Moderator.prototype.parseSessionId = function (resultIq) {
  9201. var sessionId = $(resultIq).find('conference').attr('session-id');
  9202. if (sessionId) {
  9203. logger.info('Received sessionId: ' + sessionId);
  9204. localStorage.setItem('sessionId', sessionId);
  9205. }
  9206. };
  9207. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9208. this.setFocusUserJid(
  9209. $(resultIq).find('conference').attr('focusjid'));
  9210. var authenticationEnabled
  9211. = $(resultIq).find(
  9212. '>conference>property' +
  9213. '[name=\'authentication\'][value=\'true\']').length > 0;
  9214. logger.info("Authentication enabled: " + authenticationEnabled);
  9215. this.externalAuthEnabled = $(resultIq).find(
  9216. '>conference>property' +
  9217. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9218. console.info(
  9219. 'External authentication enabled: ' + this.externalAuthEnabled);
  9220. if (!this.externalAuthEnabled) {
  9221. // We expect to receive sessionId in 'internal' authentication mode
  9222. this.parseSessionId(resultIq);
  9223. }
  9224. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9225. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9226. authenticationEnabled, authIdentity);
  9227. // Check if focus has auto-detected Jigasi component(this will be also
  9228. // included if we have passed our host from the config)
  9229. if ($(resultIq).find(
  9230. '>conference>property' +
  9231. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9232. this.sipGatewayEnabled = true;
  9233. }
  9234. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9235. };
  9236. // FIXME = we need to show the fact that we're waiting for the focus
  9237. // to the user(or that focus is not available)
  9238. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9239. // Try to use focus user JID from the config
  9240. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9241. // Send create conference IQ
  9242. var iq = this.createConferenceIq();
  9243. var self = this;
  9244. this.connection.sendIQ(
  9245. iq,
  9246. function (result) {
  9247. // Setup config options
  9248. self.parseConfigOptions(result);
  9249. if ('true' === $(result).find('conference').attr('ready')) {
  9250. // Reset both timers
  9251. self.getNextTimeout(true);
  9252. self.getNextErrorTimeout(true);
  9253. // Exec callback
  9254. callback();
  9255. } else {
  9256. var waitMs = self.getNextTimeout();
  9257. logger.info("Waiting for the focus... " + waitMs);
  9258. // Reset error timeout
  9259. self.getNextErrorTimeout(true);
  9260. window.setTimeout(
  9261. function () {
  9262. self.allocateConferenceFocus(callback);
  9263. }, waitMs);
  9264. }
  9265. },
  9266. function (error) {
  9267. // Invalid session ? remove and try again
  9268. // without session ID to get a new one
  9269. var invalidSession
  9270. = $(error).find('>error>session-invalid').length;
  9271. if (invalidSession) {
  9272. logger.info("Session expired! - removing");
  9273. localStorage.removeItem("sessionId");
  9274. }
  9275. if ($(error).find('>error>graceful-shutdown').length) {
  9276. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9277. return;
  9278. }
  9279. // Check for error returned by the reservation system
  9280. var reservationErr = $(error).find('>error>reservation-error');
  9281. if (reservationErr.length) {
  9282. // Trigger error event
  9283. var errorCode = reservationErr.attr('error-code');
  9284. var errorMsg;
  9285. if ($(error).find('>error>text')) {
  9286. errorMsg = $(error).find('>error>text').text();
  9287. }
  9288. self.eventEmitter.emit(
  9289. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9290. return;
  9291. }
  9292. // Not authorized to create new room
  9293. if ($(error).find('>error>not-authorized').length) {
  9294. logger.warn("Unauthorized to start the conference", error);
  9295. var toDomain
  9296. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9297. if (toDomain !==
  9298. this.xmppService.options.hosts.anonymousdomain) {
  9299. //FIXME: "is external" should come either from
  9300. // the focus or config.js
  9301. self.externalAuthEnabled = true;
  9302. }
  9303. self.eventEmitter.emit(
  9304. XMPPEvents.AUTHENTICATION_REQUIRED,
  9305. function () {
  9306. self.allocateConferenceFocus(
  9307. callback);
  9308. });
  9309. return;
  9310. }
  9311. var waitMs = self.getNextErrorTimeout();
  9312. logger.error("Focus error, retry after " + waitMs, error);
  9313. // Show message
  9314. var focusComponent = self.getFocusComponent();
  9315. var retrySec = waitMs / 1000;
  9316. //FIXME: message is duplicated ?
  9317. // Do not show in case of session invalid
  9318. // which means just a retry
  9319. if (!invalidSession) {
  9320. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9321. focusComponent, retrySec);
  9322. }
  9323. // Reset response timeout
  9324. self.getNextTimeout(true);
  9325. window.setTimeout(
  9326. function () {
  9327. self.allocateConferenceFocus(callback);
  9328. }, waitMs);
  9329. }
  9330. );
  9331. };
  9332. Moderator.prototype.getLoginUrl = function (urlCallback) {
  9333. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9334. iq.c('login-url', {
  9335. xmlns: 'http://jitsi.org/protocol/focus',
  9336. room: this.roomName,
  9337. 'machine-uid': this.settings.getSettings().uid
  9338. });
  9339. this.connection.sendIQ(
  9340. iq,
  9341. function (result) {
  9342. var url = $(result).find('login-url').attr('url');
  9343. url = url = decodeURIComponent(url);
  9344. if (url) {
  9345. logger.info("Got auth url: " + url);
  9346. urlCallback(url);
  9347. } else {
  9348. logger.error(
  9349. "Failed to get auth url from the focus", result);
  9350. }
  9351. },
  9352. function (error) {
  9353. logger.error("Get auth url error", error);
  9354. }
  9355. );
  9356. };
  9357. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  9358. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9359. iq.c('login-url', {
  9360. xmlns: 'http://jitsi.org/protocol/focus',
  9361. room: this.roomName,
  9362. 'machine-uid': this.settings.getSettings().uid,
  9363. popup: true
  9364. });
  9365. this.connection.sendIQ(
  9366. iq,
  9367. function (result) {
  9368. var url = $(result).find('login-url').attr('url');
  9369. url = url = decodeURIComponent(url);
  9370. if (url) {
  9371. logger.info("Got POPUP auth url: " + url);
  9372. urlCallback(url);
  9373. } else {
  9374. logger.error(
  9375. "Failed to get POPUP auth url from the focus", result);
  9376. }
  9377. },
  9378. function (error) {
  9379. logger.error('Get POPUP auth url error', error);
  9380. }
  9381. );
  9382. };
  9383. Moderator.prototype.logout = function (callback) {
  9384. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9385. var sessionId = localStorage.getItem('sessionId');
  9386. if (!sessionId) {
  9387. callback();
  9388. return;
  9389. }
  9390. iq.c('logout', {
  9391. xmlns: 'http://jitsi.org/protocol/focus',
  9392. 'session-id': sessionId
  9393. });
  9394. this.connection.sendIQ(
  9395. iq,
  9396. function (result) {
  9397. var logoutUrl = $(result).find('logout').attr('logout-url');
  9398. if (logoutUrl) {
  9399. logoutUrl = decodeURIComponent(logoutUrl);
  9400. }
  9401. logger.info("Log out OK, url: " + logoutUrl, result);
  9402. localStorage.removeItem('sessionId');
  9403. callback(logoutUrl);
  9404. },
  9405. function (error) {
  9406. logger.error("Logout error", error);
  9407. }
  9408. );
  9409. };
  9410. module.exports = Moderator;
  9411. }).call(this,"/modules/xmpp/moderator.js")
  9412. },{"../../service/authentication/AuthenticationEvents":81,"../../service/xmpp/XMPPEvents":85,"../settings/Settings":21,"jitsi-meet-logger":47}],35:[function(require,module,exports){
  9413. (function (__filename){
  9414. /* jshint -W117 */
  9415. /* a simple MUC connection plugin
  9416. * can only handle a single MUC room
  9417. */
  9418. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9419. var ChatRoom = require("./ChatRoom");
  9420. module.exports = function(XMPP) {
  9421. Strophe.addConnectionPlugin('emuc', {
  9422. connection: null,
  9423. rooms: {},//map with the rooms
  9424. init: function (conn) {
  9425. this.connection = conn;
  9426. // add handlers (just once)
  9427. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  9428. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  9429. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  9430. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  9431. },
  9432. createRoom: function (jid, password, options) {
  9433. var roomJid = Strophe.getBareJidFromJid(jid);
  9434. if (this.rooms[roomJid]) {
  9435. logger.error("You are already in the room!");
  9436. return;
  9437. }
  9438. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  9439. return this.rooms[roomJid];
  9440. },
  9441. doLeave: function (jid) {
  9442. this.rooms[jid].doLeave();
  9443. delete this.rooms[jid];
  9444. },
  9445. onPresence: function (pres) {
  9446. var from = pres.getAttribute('from');
  9447. // What is this for? A workaround for something?
  9448. if (pres.getAttribute('type')) {
  9449. return true;
  9450. }
  9451. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9452. if(!room)
  9453. return;
  9454. // Parse status.
  9455. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  9456. room.createNonAnonymousRoom();
  9457. }
  9458. room.onPresence(pres);
  9459. return true;
  9460. },
  9461. onPresenceUnavailable: function (pres) {
  9462. var from = pres.getAttribute('from');
  9463. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9464. if(!room)
  9465. return;
  9466. room.onPresenceUnavailable(pres, from);
  9467. return true;
  9468. },
  9469. onPresenceError: function (pres) {
  9470. var from = pres.getAttribute('from');
  9471. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9472. if(!room)
  9473. return;
  9474. room.onPresenceError(pres, from);
  9475. return true;
  9476. },
  9477. onMessage: function (msg) {
  9478. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  9479. var from = msg.getAttribute('from');
  9480. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9481. if(!room)
  9482. return;
  9483. room.onMessage(msg, from);
  9484. return true;
  9485. },
  9486. setJingleSession: function (from, session) {
  9487. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9488. if(!room)
  9489. return;
  9490. room.setJingleSession(session);
  9491. }
  9492. });
  9493. };
  9494. }).call(this,"/modules/xmpp/strophe.emuc.js")
  9495. },{"./ChatRoom":26,"jitsi-meet-logger":47}],36:[function(require,module,exports){
  9496. (function (__filename){
  9497. /* jshint -W117 */
  9498. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9499. var JingleSession = require("./JingleSessionPC");
  9500. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9501. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9502. module.exports = function(XMPP, eventEmitter) {
  9503. Strophe.addConnectionPlugin('jingle', {
  9504. connection: null,
  9505. sessions: {},
  9506. jid2session: {},
  9507. ice_config: {iceServers: []},
  9508. media_constraints: {
  9509. mandatory: {
  9510. 'OfferToReceiveAudio': true,
  9511. 'OfferToReceiveVideo': true
  9512. }
  9513. // MozDontOfferDataChannel: true when this is firefox
  9514. },
  9515. init: function (conn) {
  9516. this.connection = conn;
  9517. if (this.connection.disco) {
  9518. // http://xmpp.org/extensions/xep-0167.html#support
  9519. // http://xmpp.org/extensions/xep-0176.html#support
  9520. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  9521. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  9522. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  9523. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  9524. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  9525. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  9526. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  9527. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  9528. || RTCBrowserType.isTemasysPluginUsed()) {
  9529. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  9530. }
  9531. // this is dealt with by SDP O/A so we don't need to announce this
  9532. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  9533. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  9534. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  9535. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  9536. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  9537. }
  9538. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  9539. },
  9540. onJingle: function (iq) {
  9541. var sid = $(iq).find('jingle').attr('sid');
  9542. var action = $(iq).find('jingle').attr('action');
  9543. var fromJid = iq.getAttribute('from');
  9544. // send ack first
  9545. var ack = $iq({type: 'result',
  9546. to: fromJid,
  9547. id: iq.getAttribute('id')
  9548. });
  9549. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  9550. var sess = this.sessions[sid];
  9551. if ('session-initiate' != action) {
  9552. if (sess === null) {
  9553. ack.type = 'error';
  9554. ack.c('error', {type: 'cancel'})
  9555. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9556. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9557. this.connection.send(ack);
  9558. return true;
  9559. }
  9560. // local jid is not checked
  9561. if (fromJid != sess.peerjid) {
  9562. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  9563. ack.type = 'error';
  9564. ack.c('error', {type: 'cancel'})
  9565. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9566. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9567. this.connection.send(ack);
  9568. return true;
  9569. }
  9570. } else if (sess !== undefined) {
  9571. // existing session with same session id
  9572. // this might be out-of-order if the sess.peerjid is the same as from
  9573. ack.type = 'error';
  9574. ack.c('error', {type: 'cancel'})
  9575. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  9576. logger.warn('duplicate session id', sid);
  9577. this.connection.send(ack);
  9578. return true;
  9579. }
  9580. // FIXME: check for a defined action
  9581. this.connection.send(ack);
  9582. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  9583. switch (action) {
  9584. case 'session-initiate':
  9585. console.log("(TIME) received session-initiate:\t",
  9586. window.performance.now());
  9587. var startMuted = $(iq).find('jingle>startmuted');
  9588. if (startMuted && startMuted.length > 0) {
  9589. var audioMuted = startMuted.attr("audio");
  9590. var videoMuted = startMuted.attr("video");
  9591. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  9592. audioMuted === "true", videoMuted === "true");
  9593. }
  9594. sess = new JingleSession(
  9595. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  9596. this.connection, XMPP);
  9597. // configure session
  9598. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  9599. this.connection.emuc.setJingleSession(fromBareJid, sess);
  9600. sess.media_constraints = this.media_constraints;
  9601. sess.ice_config = this.ice_config;
  9602. sess.initialize(fromJid, false);
  9603. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  9604. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  9605. sess.setOffer($(iq).find('>jingle'));
  9606. this.sessions[sess.sid] = sess;
  9607. this.jid2session[sess.peerjid] = sess;
  9608. // the callback should either
  9609. // .sendAnswer and .accept
  9610. // or .sendTerminate -- not necessarily synchronous
  9611. sess.sendAnswer();
  9612. sess.accept();
  9613. break;
  9614. case 'session-accept':
  9615. sess.setAnswer($(iq).find('>jingle'));
  9616. sess.accept();
  9617. break;
  9618. case 'session-terminate':
  9619. // If this is not the focus sending the terminate, we have
  9620. // nothing more to do here.
  9621. if (Object.keys(this.sessions).length < 1
  9622. || !(this.sessions[Object.keys(this.sessions)[0]]
  9623. instanceof JingleSession))
  9624. {
  9625. break;
  9626. }
  9627. logger.log('terminating...', sess.sid);
  9628. sess.terminate();
  9629. this.terminate(sess.sid);
  9630. if ($(iq).find('>jingle>reason').length) {
  9631. $(document).trigger('callterminated.jingle', [
  9632. sess.sid,
  9633. sess.peerjid,
  9634. $(iq).find('>jingle>reason>:first')[0].tagName,
  9635. $(iq).find('>jingle>reason>text').text()
  9636. ]);
  9637. } else {
  9638. $(document).trigger('callterminated.jingle',
  9639. [sess.sid, sess.peerjid]);
  9640. }
  9641. break;
  9642. case 'transport-info':
  9643. sess.addIceCandidate($(iq).find('>jingle>content'));
  9644. break;
  9645. case 'session-info':
  9646. var affected;
  9647. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9648. $(document).trigger('ringing.jingle', [sess.sid]);
  9649. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9650. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9651. $(document).trigger('mute.jingle', [sess.sid, affected]);
  9652. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9653. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9654. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  9655. }
  9656. break;
  9657. case 'addsource': // FIXME: proprietary, un-jingleish
  9658. case 'source-add': // FIXME: proprietary
  9659. sess.addSource($(iq).find('>jingle>content'));
  9660. break;
  9661. case 'removesource': // FIXME: proprietary, un-jingleish
  9662. case 'source-remove': // FIXME: proprietary
  9663. sess.removeSource($(iq).find('>jingle>content'));
  9664. break;
  9665. default:
  9666. logger.warn('jingle action not implemented', action);
  9667. break;
  9668. }
  9669. return true;
  9670. },
  9671. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  9672. if (sid === null || sid === undefined) {
  9673. for (sid in this.sessions) {
  9674. if (this.sessions[sid].state != 'ended') {
  9675. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9676. this.sessions[sid].terminate();
  9677. }
  9678. delete this.jid2session[this.sessions[sid].peerjid];
  9679. delete this.sessions[sid];
  9680. }
  9681. } else if (this.sessions.hasOwnProperty(sid)) {
  9682. if (this.sessions[sid].state != 'ended') {
  9683. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9684. this.sessions[sid].terminate();
  9685. }
  9686. delete this.jid2session[this.sessions[sid].peerjid];
  9687. delete this.sessions[sid];
  9688. }
  9689. },
  9690. getStunAndTurnCredentials: function () {
  9691. // get stun and turn configuration from server via xep-0215
  9692. // uses time-limited credentials as described in
  9693. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  9694. //
  9695. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  9696. // for a prosody module which implements this
  9697. //
  9698. // currently, this doesn't work with updateIce and therefore credentials with a long
  9699. // validity have to be fetched before creating the peerconnection
  9700. // TODO: implement refresh via updateIce as described in
  9701. // https://code.google.com/p/webrtc/issues/detail?id=1650
  9702. var self = this;
  9703. this.connection.sendIQ(
  9704. $iq({type: 'get', to: this.connection.domain})
  9705. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  9706. function (res) {
  9707. var iceservers = [];
  9708. $(res).find('>services>service').each(function (idx, el) {
  9709. el = $(el);
  9710. var dict = {};
  9711. var type = el.attr('type');
  9712. switch (type) {
  9713. case 'stun':
  9714. dict.url = 'stun:' + el.attr('host');
  9715. if (el.attr('port')) {
  9716. dict.url += ':' + el.attr('port');
  9717. }
  9718. iceservers.push(dict);
  9719. break;
  9720. case 'turn':
  9721. case 'turns':
  9722. dict.url = type + ':';
  9723. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  9724. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  9725. dict.url += el.attr('username') + '@';
  9726. } else {
  9727. dict.username = el.attr('username'); // only works in M28
  9728. }
  9729. }
  9730. dict.url += el.attr('host');
  9731. if (el.attr('port') && el.attr('port') != '3478') {
  9732. dict.url += ':' + el.attr('port');
  9733. }
  9734. if (el.attr('transport') && el.attr('transport') != 'udp') {
  9735. dict.url += '?transport=' + el.attr('transport');
  9736. }
  9737. if (el.attr('password')) {
  9738. dict.credential = el.attr('password');
  9739. }
  9740. iceservers.push(dict);
  9741. break;
  9742. }
  9743. });
  9744. self.ice_config.iceServers = iceservers;
  9745. },
  9746. function (err) {
  9747. logger.warn('getting turn credentials failed', err);
  9748. logger.warn('is mod_turncredentials or similar installed?');
  9749. }
  9750. );
  9751. // implement push?
  9752. },
  9753. /**
  9754. * Returns the data saved in 'updateLog' in a format to be logged.
  9755. */
  9756. getLog: function () {
  9757. var data = {};
  9758. var self = this;
  9759. Object.keys(this.sessions).forEach(function (sid) {
  9760. var session = self.sessions[sid];
  9761. if (session.peerconnection && session.peerconnection.updateLog) {
  9762. // FIXME: should probably be a .dump call
  9763. data["jingle_" + session.sid] = {
  9764. updateLog: session.peerconnection.updateLog,
  9765. stats: session.peerconnection.stats,
  9766. url: window.location.href
  9767. };
  9768. }
  9769. });
  9770. return data;
  9771. }
  9772. });
  9773. };
  9774. }).call(this,"/modules/xmpp/strophe.jingle.js")
  9775. },{"../../service/xmpp/XMPPEvents":85,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":47}],37:[function(require,module,exports){
  9776. /* global Strophe */
  9777. module.exports = function () {
  9778. Strophe.addConnectionPlugin('logger', {
  9779. // logs raw stanzas and makes them available for download as JSON
  9780. connection: null,
  9781. log: [],
  9782. init: function (conn) {
  9783. this.connection = conn;
  9784. this.connection.rawInput = this.log_incoming.bind(this);
  9785. this.connection.rawOutput = this.log_outgoing.bind(this);
  9786. },
  9787. log_incoming: function (stanza) {
  9788. this.log.push([new Date().getTime(), 'incoming', stanza]);
  9789. },
  9790. log_outgoing: function (stanza) {
  9791. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  9792. }
  9793. });
  9794. };
  9795. },{}],38:[function(require,module,exports){
  9796. (function (__filename){
  9797. /* global $, $iq, Strophe */
  9798. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9799. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9800. /**
  9801. * Ping every 20 sec
  9802. */
  9803. var PING_INTERVAL = 20000;
  9804. /**
  9805. * Ping timeout error after 15 sec of waiting.
  9806. */
  9807. var PING_TIMEOUT = 15000;
  9808. /**
  9809. * Will close the connection after 3 consecutive ping errors.
  9810. */
  9811. var PING_THRESHOLD = 3;
  9812. /**
  9813. * XEP-0199 ping plugin.
  9814. *
  9815. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  9816. */
  9817. module.exports = function (XMPP, eventEmitter) {
  9818. Strophe.addConnectionPlugin('ping', {
  9819. connection: null,
  9820. failedPings: 0,
  9821. /**
  9822. * Initializes the plugin. Method called by Strophe.
  9823. * @param connection Strophe connection instance.
  9824. */
  9825. init: function (connection) {
  9826. this.connection = connection;
  9827. Strophe.addNamespace('PING', "urn:xmpp:ping");
  9828. },
  9829. /**
  9830. * Sends "ping" to given <tt>jid</tt>
  9831. * @param jid the JID to which ping request will be sent.
  9832. * @param success callback called on success.
  9833. * @param error callback called on error.
  9834. * @param timeout ms how long are we going to wait for the response. On
  9835. * timeout <tt>error<//t> callback is called with undefined error
  9836. * argument.
  9837. */
  9838. ping: function (jid, success, error, timeout) {
  9839. var iq = $iq({type: 'get', to: jid});
  9840. iq.c('ping', {xmlns: Strophe.NS.PING});
  9841. this.connection.sendIQ(iq, success, error, timeout);
  9842. },
  9843. /**
  9844. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  9845. * @param jid the JID to be checked for ping support.
  9846. * @param callback function with boolean argument which will be
  9847. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  9848. */
  9849. hasPingSupport: function (jid, callback) {
  9850. this.connection.disco.info(
  9851. jid, null,
  9852. function (result) {
  9853. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  9854. callback(ping.length > 0);
  9855. },
  9856. function (error) {
  9857. logger.error("Ping feature discovery error", error);
  9858. callback(false);
  9859. }
  9860. );
  9861. },
  9862. /**
  9863. * Starts to send ping in given interval to specified remote JID.
  9864. * This plugin supports only one such task and <tt>stopInterval</tt>
  9865. * must be called before starting a new one.
  9866. * @param remoteJid remote JID to which ping requests will be sent to.
  9867. * @param interval task interval in ms.
  9868. */
  9869. startInterval: function (remoteJid, interval) {
  9870. if (this.intervalId) {
  9871. logger.error("Ping task scheduled already");
  9872. return;
  9873. }
  9874. if (!interval)
  9875. interval = PING_INTERVAL;
  9876. var self = this;
  9877. this.intervalId = window.setInterval(function () {
  9878. self.ping(remoteJid,
  9879. function (result) {
  9880. // Ping OK
  9881. self.failedPings = 0;
  9882. },
  9883. function (error) {
  9884. self.failedPings += 1;
  9885. logger.error(
  9886. "Ping " + (error ? "error" : "timeout"), error);
  9887. if (self.failedPings >= PING_THRESHOLD) {
  9888. self.connection.disconnect();
  9889. }
  9890. }, PING_TIMEOUT);
  9891. }, interval);
  9892. logger.info("XMPP pings will be sent every " + interval + " ms");
  9893. },
  9894. /**
  9895. * Stops current "ping" interval task.
  9896. */
  9897. stopInterval: function () {
  9898. if (this.intervalId) {
  9899. window.clearInterval(this.intervalId);
  9900. this.intervalId = null;
  9901. this.failedPings = 0;
  9902. logger.info("Ping interval cleared");
  9903. }
  9904. }
  9905. });
  9906. };
  9907. }).call(this,"/modules/xmpp/strophe.ping.js")
  9908. },{"../../service/xmpp/XMPPEvents":85,"jitsi-meet-logger":47}],39:[function(require,module,exports){
  9909. (function (__filename){
  9910. /* jshint -W117 */
  9911. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9912. module.exports = function() {
  9913. Strophe.addConnectionPlugin('rayo',
  9914. {
  9915. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  9916. connection: null,
  9917. init: function (conn) {
  9918. this.connection = conn;
  9919. if (this.connection.disco) {
  9920. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  9921. }
  9922. this.connection.addHandler(
  9923. this.onRayo.bind(this),
  9924. this.RAYO_XMLNS, 'iq', 'set', null, null);
  9925. },
  9926. onRayo: function (iq) {
  9927. logger.info("Rayo IQ", iq);
  9928. },
  9929. dial: function (to, from, roomName, roomPass) {
  9930. var self = this;
  9931. var req = $iq(
  9932. {
  9933. type: 'set',
  9934. to: this.connection.emuc.focusMucJid
  9935. }
  9936. );
  9937. req.c('dial',
  9938. {
  9939. xmlns: this.RAYO_XMLNS,
  9940. to: to,
  9941. from: from
  9942. });
  9943. req.c('header',
  9944. {
  9945. name: 'JvbRoomName',
  9946. value: roomName
  9947. }).up();
  9948. if (roomPass !== null && roomPass.length) {
  9949. req.c('header',
  9950. {
  9951. name: 'JvbRoomPassword',
  9952. value: roomPass
  9953. }).up();
  9954. }
  9955. this.connection.sendIQ(
  9956. req,
  9957. function (result) {
  9958. logger.info('Dial result ', result);
  9959. var resource = $(result).find('ref').attr('uri');
  9960. this.call_resource = resource.substr('xmpp:'.length);
  9961. logger.info(
  9962. "Received call resource: " + this.call_resource);
  9963. },
  9964. function (error) {
  9965. logger.info('Dial error ', error);
  9966. }
  9967. );
  9968. },
  9969. hang_up: function () {
  9970. if (!this.call_resource) {
  9971. logger.warn("No call in progress");
  9972. return;
  9973. }
  9974. var self = this;
  9975. var req = $iq(
  9976. {
  9977. type: 'set',
  9978. to: this.call_resource
  9979. }
  9980. );
  9981. req.c('hangup',
  9982. {
  9983. xmlns: this.RAYO_XMLNS
  9984. });
  9985. this.connection.sendIQ(
  9986. req,
  9987. function (result) {
  9988. logger.info('Hangup result ', result);
  9989. self.call_resource = null;
  9990. },
  9991. function (error) {
  9992. logger.info('Hangup error ', error);
  9993. self.call_resource = null;
  9994. }
  9995. );
  9996. }
  9997. }
  9998. );
  9999. };
  10000. }).call(this,"/modules/xmpp/strophe.rayo.js")
  10001. },{"jitsi-meet-logger":47}],40:[function(require,module,exports){
  10002. (function (__filename){
  10003. /* global Strophe */
  10004. /**
  10005. * Strophe logger implementation. Logs from level WARN and above.
  10006. */
  10007. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10008. module.exports = function () {
  10009. Strophe.log = function (level, msg) {
  10010. switch (level) {
  10011. case Strophe.LogLevel.WARN:
  10012. logger.warn("Strophe: " + msg);
  10013. break;
  10014. case Strophe.LogLevel.ERROR:
  10015. case Strophe.LogLevel.FATAL:
  10016. logger.error("Strophe: " + msg);
  10017. break;
  10018. }
  10019. };
  10020. Strophe.getStatusString = function (status) {
  10021. switch (status) {
  10022. case Strophe.Status.ERROR:
  10023. return "ERROR";
  10024. case Strophe.Status.CONNECTING:
  10025. return "CONNECTING";
  10026. case Strophe.Status.CONNFAIL:
  10027. return "CONNFAIL";
  10028. case Strophe.Status.AUTHENTICATING:
  10029. return "AUTHENTICATING";
  10030. case Strophe.Status.AUTHFAIL:
  10031. return "AUTHFAIL";
  10032. case Strophe.Status.CONNECTED:
  10033. return "CONNECTED";
  10034. case Strophe.Status.DISCONNECTED:
  10035. return "DISCONNECTED";
  10036. case Strophe.Status.DISCONNECTING:
  10037. return "DISCONNECTING";
  10038. case Strophe.Status.ATTACHED:
  10039. return "ATTACHED";
  10040. default:
  10041. return "unknown";
  10042. }
  10043. };
  10044. };
  10045. }).call(this,"/modules/xmpp/strophe.util.js")
  10046. },{"jitsi-meet-logger":47}],41:[function(require,module,exports){
  10047. (function (__filename){
  10048. /* global $, APP, config, Strophe*/
  10049. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10050. var EventEmitter = require("events");
  10051. var Pako = require("pako");
  10052. var RTCEvents = require("../../service/RTC/RTCEvents");
  10053. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10054. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  10055. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  10056. var RTC = require("../RTC/RTC");
  10057. var authenticatedUser = false;
  10058. function createConnection(bosh) {
  10059. bosh = bosh || '/http-bind';
  10060. return new Strophe.Connection(bosh);
  10061. };
  10062. //!!!!!!!!!! FIXME: ...
  10063. function initStrophePlugins(XMPP)
  10064. {
  10065. require("./strophe.emuc")(XMPP);
  10066. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  10067. // require("./strophe.moderate")(XMPP, eventEmitter);
  10068. require("./strophe.util")();
  10069. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  10070. require("./strophe.rayo")();
  10071. require("./strophe.logger")();
  10072. }
  10073. //!!!!!!!!!! FIXME: ...
  10074. ///**
  10075. // * If given <tt>localStream</tt> is video one this method will advertise it's
  10076. // * video type in MUC presence.
  10077. // * @param localStream new or modified <tt>LocalStream</tt>.
  10078. // */
  10079. //function broadcastLocalVideoType(localStream) {
  10080. // if (localStream.videoType)
  10081. // XMPP.addToPresence('videoType', localStream.videoType);
  10082. //}
  10083. //
  10084. //function registerListeners() {
  10085. // RTC.addStreamListener(
  10086. // broadcastLocalVideoType,
  10087. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  10088. // );
  10089. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  10090. // XMPP.addToPresence("devices", devices);
  10091. // });
  10092. //}
  10093. function XMPP(options) {
  10094. this.eventEmitter = new EventEmitter();
  10095. this.connection = null;
  10096. this.disconnectInProgress = false;
  10097. this.forceMuted = false;
  10098. this.options = options;
  10099. initStrophePlugins(this);
  10100. // registerListeners();
  10101. this.connection = createConnection(options.bosh);
  10102. }
  10103. XMPP.prototype.getConnection = function(){ return connection; };
  10104. XMPP.prototype._connect = function (jid, password) {
  10105. var self = this;
  10106. // connection.connect() starts the connection process.
  10107. //
  10108. // As the connection process proceeds, the user supplied callback will
  10109. // be triggered multiple times with status updates. The callback should
  10110. // take two arguments - the status code and the error condition.
  10111. //
  10112. // The status code will be one of the values in the Strophe.Status
  10113. // constants. The error condition will be one of the conditions defined
  10114. // in RFC 3920 or the condition ‘strophe-parsererror’.
  10115. //
  10116. // The Parameters wait, hold and route are optional and only relevant
  10117. // for BOSH connections. Please see XEP 124 for a more detailed
  10118. // explanation of the optional parameters.
  10119. //
  10120. // Connection status constants for use by the connection handler
  10121. // callback.
  10122. //
  10123. // Status.ERROR - An error has occurred (websockets specific)
  10124. // Status.CONNECTING - The connection is currently being made
  10125. // Status.CONNFAIL - The connection attempt failed
  10126. // Status.AUTHENTICATING - The connection is authenticating
  10127. // Status.AUTHFAIL - The authentication attempt failed
  10128. // Status.CONNECTED - The connection has succeeded
  10129. // Status.DISCONNECTED - The connection has been terminated
  10130. // Status.DISCONNECTING - The connection is currently being terminated
  10131. // Status.ATTACHED - The connection has been attached
  10132. var anonymousConnectionFailed = false;
  10133. var connectionFailed = false;
  10134. var lastErrorMsg;
  10135. this.connection.connect(jid, password, function (status, msg) {
  10136. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  10137. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  10138. if (status === Strophe.Status.CONNECTED) {
  10139. if (self.options.useStunTurn) {
  10140. self.connection.jingle.getStunAndTurnCredentials();
  10141. }
  10142. logger.info("My Jabber ID: " + self.connection.jid);
  10143. // Schedule ping ?
  10144. var pingJid = self.connection.domain;
  10145. self.connection.ping.hasPingSupport(
  10146. pingJid,
  10147. function (hasPing) {
  10148. if (hasPing)
  10149. self.connection.ping.startInterval(pingJid);
  10150. else
  10151. logger.warn("Ping NOT supported by " + pingJid);
  10152. }
  10153. );
  10154. if (password)
  10155. authenticatedUser = true;
  10156. if (self.connection && self.connection.connected &&
  10157. Strophe.getResourceFromJid(self.connection.jid)) {
  10158. // .connected is true while connecting?
  10159. // self.connection.send($pres());
  10160. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  10161. Strophe.getResourceFromJid(self.connection.jid));
  10162. }
  10163. } else if (status === Strophe.Status.CONNFAIL) {
  10164. if (msg === 'x-strophe-bad-non-anon-jid') {
  10165. anonymousConnectionFailed = true;
  10166. }
  10167. else
  10168. {
  10169. connectionFailed = true;
  10170. }
  10171. lastErrorMsg = msg;
  10172. } else if (status === Strophe.Status.DISCONNECTED) {
  10173. // Stop ping interval
  10174. self.connection.ping.stopInterval();
  10175. self.disconnectInProgress = false;
  10176. if (anonymousConnectionFailed) {
  10177. // prompt user for username and password
  10178. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10179. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10180. } else if(connectionFailed) {
  10181. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10182. JitsiConnectionErrors.OTHER_ERROR,
  10183. msg ? msg : lastErrorMsg);
  10184. } else {
  10185. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  10186. msg ? msg : lastErrorMsg);
  10187. }
  10188. } else if (status === Strophe.Status.AUTHFAIL) {
  10189. // wrong password or username, prompt user
  10190. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10191. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10192. }
  10193. });
  10194. }
  10195. XMPP.prototype.connect = function (jid, password) {
  10196. if(!jid) {
  10197. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10198. // Force authenticated domain if room is appended with '?login=true'
  10199. if (this.options.hosts.anonymousdomain &&
  10200. window.location.search.indexOf("login=true") !== -1) {
  10201. configDomain = this.options.hosts.domain;
  10202. }
  10203. jid = configDomain || window.location.hostname;
  10204. }
  10205. return this._connect(jid, password);
  10206. };
  10207. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  10208. var roomjid = roomName + '@' + this.options.hosts.muc;
  10209. if (useNicks) {
  10210. if (nick) {
  10211. roomjid += '/' + nick;
  10212. } else {
  10213. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10214. }
  10215. } else {
  10216. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10217. if(!authenticatedUser)
  10218. tmpJid = tmpJid.substr(0, 8);
  10219. roomjid += '/' + tmpJid;
  10220. }
  10221. return this.connection.emuc.createRoom(roomjid, null, options);
  10222. }
  10223. XMPP.prototype.addListener = function(type, listener) {
  10224. this.eventEmitter.on(type, listener);
  10225. };
  10226. XMPP.prototype.removeListener = function (type, listener) {
  10227. this.eventEmitter.removeListener(type, listener);
  10228. };
  10229. //FIXME: this should work with the room
  10230. XMPP.prototype.leaveRoom = function (jid) {
  10231. var handler = this.connection.jingle.jid2session[jid];
  10232. if (handler && handler.peerconnection) {
  10233. // FIXME: probably removing streams is not required and close() should
  10234. // be enough
  10235. if (RTC.localAudio) {
  10236. handler.peerconnection.removeStream(
  10237. RTC.localAudio.getOriginalStream(), true);
  10238. }
  10239. if (RTC.localVideo) {
  10240. handler.peerconnection.removeStream(
  10241. RTC.localVideo.getOriginalStream(), true);
  10242. }
  10243. handler.peerconnection.close();
  10244. }
  10245. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10246. this.connection.emuc.doLeave(jid);
  10247. };
  10248. /**
  10249. * Sends 'data' as a log message to the focus. Returns true iff a message
  10250. * was sent.
  10251. * @param data
  10252. * @returns {boolean} true iff a message was sent.
  10253. */
  10254. XMPP.prototype.sendLogs = function (data) {
  10255. if(!this.connection.emuc.focusMucJid)
  10256. return false;
  10257. var deflate = true;
  10258. var content = JSON.stringify(data);
  10259. if (deflate) {
  10260. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10261. }
  10262. content = Base64.encode(content);
  10263. // XEP-0337-ish
  10264. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  10265. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  10266. id: 'PeerConnectionStats'});
  10267. message.c('message').t(content).up();
  10268. if (deflate) {
  10269. message.c('tag', {name: "deflated", value: "true"}).up();
  10270. }
  10271. message.up();
  10272. this.connection.send(message);
  10273. return true;
  10274. };
  10275. // Gets the logs from strophe.jingle.
  10276. XMPP.prototype.getJingleLog = function () {
  10277. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  10278. };
  10279. // Gets the logs from strophe.
  10280. XMPP.prototype.getXmppLog = function () {
  10281. return this.connection.logger ? this.connection.logger.log : null;
  10282. };
  10283. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  10284. this.connection.rayo.dial(to, from, roomName,roomPass);
  10285. };
  10286. XMPP.prototype.setMute = function (jid, mute) {
  10287. this.connection.moderate.setMute(jid, mute);
  10288. };
  10289. XMPP.prototype.eject = function (jid) {
  10290. this.connection.moderate.eject(jid);
  10291. };
  10292. XMPP.prototype.getSessions = function () {
  10293. return this.connection.jingle.sessions;
  10294. };
  10295. XMPP.prototype.disconnect = function () {
  10296. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  10297. {
  10298. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  10299. return;
  10300. }
  10301. this.disconnectInProgress = true;
  10302. this.connection.disconnect();
  10303. };
  10304. /**
  10305. * Gets the SSRC of local media stream.
  10306. * @param mediaType the media type that tells whether we want to get
  10307. * the SSRC of local audio or video stream.
  10308. * @returns {*} the SSRC number for local media stream or <tt>null</tt> if
  10309. * not available.
  10310. */
  10311. XMPP.prototype.getLocalSSRC = function (mediaType) {
  10312. if (this.connection.jingle.activecall &&
  10313. this.connection.jingle.activecall.peerconnection) {
  10314. return this.connection.jingle.activecall.getLocalSSRC(mediaType);
  10315. } else {
  10316. return null;
  10317. }
  10318. };
  10319. module.exports = XMPP;
  10320. }).call(this,"/modules/xmpp/xmpp.js")
  10321. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":79,"../../service/xmpp/XMPPEvents":85,"../RTC/RTC":16,"./strophe.emuc":35,"./strophe.jingle":36,"./strophe.logger":37,"./strophe.ping":38,"./strophe.rayo":39,"./strophe.util":40,"events":43,"jitsi-meet-logger":47,"pako":48}],42:[function(require,module,exports){
  10322. (function (process){
  10323. /*!
  10324. * async
  10325. * https://github.com/caolan/async
  10326. *
  10327. * Copyright 2010-2014 Caolan McMahon
  10328. * Released under the MIT license
  10329. */
  10330. /*jshint onevar: false, indent:4 */
  10331. /*global setImmediate: false, setTimeout: false, console: false */
  10332. (function () {
  10333. var async = {};
  10334. // global on the server, window in the browser
  10335. var root, previous_async;
  10336. root = this;
  10337. if (root != null) {
  10338. previous_async = root.async;
  10339. }
  10340. async.noConflict = function () {
  10341. root.async = previous_async;
  10342. return async;
  10343. };
  10344. function only_once(fn) {
  10345. var called = false;
  10346. return function() {
  10347. if (called) throw new Error("Callback was already called.");
  10348. called = true;
  10349. fn.apply(root, arguments);
  10350. }
  10351. }
  10352. //// cross-browser compatiblity functions ////
  10353. var _toString = Object.prototype.toString;
  10354. var _isArray = Array.isArray || function (obj) {
  10355. return _toString.call(obj) === '[object Array]';
  10356. };
  10357. var _each = function (arr, iterator) {
  10358. if (arr.forEach) {
  10359. return arr.forEach(iterator);
  10360. }
  10361. for (var i = 0; i < arr.length; i += 1) {
  10362. iterator(arr[i], i, arr);
  10363. }
  10364. };
  10365. var _map = function (arr, iterator) {
  10366. if (arr.map) {
  10367. return arr.map(iterator);
  10368. }
  10369. var results = [];
  10370. _each(arr, function (x, i, a) {
  10371. results.push(iterator(x, i, a));
  10372. });
  10373. return results;
  10374. };
  10375. var _reduce = function (arr, iterator, memo) {
  10376. if (arr.reduce) {
  10377. return arr.reduce(iterator, memo);
  10378. }
  10379. _each(arr, function (x, i, a) {
  10380. memo = iterator(memo, x, i, a);
  10381. });
  10382. return memo;
  10383. };
  10384. var _keys = function (obj) {
  10385. if (Object.keys) {
  10386. return Object.keys(obj);
  10387. }
  10388. var keys = [];
  10389. for (var k in obj) {
  10390. if (obj.hasOwnProperty(k)) {
  10391. keys.push(k);
  10392. }
  10393. }
  10394. return keys;
  10395. };
  10396. //// exported async module functions ////
  10397. //// nextTick implementation with browser-compatible fallback ////
  10398. if (typeof process === 'undefined' || !(process.nextTick)) {
  10399. if (typeof setImmediate === 'function') {
  10400. async.nextTick = function (fn) {
  10401. // not a direct alias for IE10 compatibility
  10402. setImmediate(fn);
  10403. };
  10404. async.setImmediate = async.nextTick;
  10405. }
  10406. else {
  10407. async.nextTick = function (fn) {
  10408. setTimeout(fn, 0);
  10409. };
  10410. async.setImmediate = async.nextTick;
  10411. }
  10412. }
  10413. else {
  10414. async.nextTick = process.nextTick;
  10415. if (typeof setImmediate !== 'undefined') {
  10416. async.setImmediate = function (fn) {
  10417. // not a direct alias for IE10 compatibility
  10418. setImmediate(fn);
  10419. };
  10420. }
  10421. else {
  10422. async.setImmediate = async.nextTick;
  10423. }
  10424. }
  10425. async.each = function (arr, iterator, callback) {
  10426. callback = callback || function () {};
  10427. if (!arr.length) {
  10428. return callback();
  10429. }
  10430. var completed = 0;
  10431. _each(arr, function (x) {
  10432. iterator(x, only_once(done) );
  10433. });
  10434. function done(err) {
  10435. if (err) {
  10436. callback(err);
  10437. callback = function () {};
  10438. }
  10439. else {
  10440. completed += 1;
  10441. if (completed >= arr.length) {
  10442. callback();
  10443. }
  10444. }
  10445. }
  10446. };
  10447. async.forEach = async.each;
  10448. async.eachSeries = function (arr, iterator, callback) {
  10449. callback = callback || function () {};
  10450. if (!arr.length) {
  10451. return callback();
  10452. }
  10453. var completed = 0;
  10454. var iterate = function () {
  10455. iterator(arr[completed], function (err) {
  10456. if (err) {
  10457. callback(err);
  10458. callback = function () {};
  10459. }
  10460. else {
  10461. completed += 1;
  10462. if (completed >= arr.length) {
  10463. callback();
  10464. }
  10465. else {
  10466. iterate();
  10467. }
  10468. }
  10469. });
  10470. };
  10471. iterate();
  10472. };
  10473. async.forEachSeries = async.eachSeries;
  10474. async.eachLimit = function (arr, limit, iterator, callback) {
  10475. var fn = _eachLimit(limit);
  10476. fn.apply(null, [arr, iterator, callback]);
  10477. };
  10478. async.forEachLimit = async.eachLimit;
  10479. var _eachLimit = function (limit) {
  10480. return function (arr, iterator, callback) {
  10481. callback = callback || function () {};
  10482. if (!arr.length || limit <= 0) {
  10483. return callback();
  10484. }
  10485. var completed = 0;
  10486. var started = 0;
  10487. var running = 0;
  10488. (function replenish () {
  10489. if (completed >= arr.length) {
  10490. return callback();
  10491. }
  10492. while (running < limit && started < arr.length) {
  10493. started += 1;
  10494. running += 1;
  10495. iterator(arr[started - 1], function (err) {
  10496. if (err) {
  10497. callback(err);
  10498. callback = function () {};
  10499. }
  10500. else {
  10501. completed += 1;
  10502. running -= 1;
  10503. if (completed >= arr.length) {
  10504. callback();
  10505. }
  10506. else {
  10507. replenish();
  10508. }
  10509. }
  10510. });
  10511. }
  10512. })();
  10513. };
  10514. };
  10515. var doParallel = function (fn) {
  10516. return function () {
  10517. var args = Array.prototype.slice.call(arguments);
  10518. return fn.apply(null, [async.each].concat(args));
  10519. };
  10520. };
  10521. var doParallelLimit = function(limit, fn) {
  10522. return function () {
  10523. var args = Array.prototype.slice.call(arguments);
  10524. return fn.apply(null, [_eachLimit(limit)].concat(args));
  10525. };
  10526. };
  10527. var doSeries = function (fn) {
  10528. return function () {
  10529. var args = Array.prototype.slice.call(arguments);
  10530. return fn.apply(null, [async.eachSeries].concat(args));
  10531. };
  10532. };
  10533. var _asyncMap = function (eachfn, arr, iterator, callback) {
  10534. arr = _map(arr, function (x, i) {
  10535. return {index: i, value: x};
  10536. });
  10537. if (!callback) {
  10538. eachfn(arr, function (x, callback) {
  10539. iterator(x.value, function (err) {
  10540. callback(err);
  10541. });
  10542. });
  10543. } else {
  10544. var results = [];
  10545. eachfn(arr, function (x, callback) {
  10546. iterator(x.value, function (err, v) {
  10547. results[x.index] = v;
  10548. callback(err);
  10549. });
  10550. }, function (err) {
  10551. callback(err, results);
  10552. });
  10553. }
  10554. };
  10555. async.map = doParallel(_asyncMap);
  10556. async.mapSeries = doSeries(_asyncMap);
  10557. async.mapLimit = function (arr, limit, iterator, callback) {
  10558. return _mapLimit(limit)(arr, iterator, callback);
  10559. };
  10560. var _mapLimit = function(limit) {
  10561. return doParallelLimit(limit, _asyncMap);
  10562. };
  10563. // reduce only has a series version, as doing reduce in parallel won't
  10564. // work in many situations.
  10565. async.reduce = function (arr, memo, iterator, callback) {
  10566. async.eachSeries(arr, function (x, callback) {
  10567. iterator(memo, x, function (err, v) {
  10568. memo = v;
  10569. callback(err);
  10570. });
  10571. }, function (err) {
  10572. callback(err, memo);
  10573. });
  10574. };
  10575. // inject alias
  10576. async.inject = async.reduce;
  10577. // foldl alias
  10578. async.foldl = async.reduce;
  10579. async.reduceRight = function (arr, memo, iterator, callback) {
  10580. var reversed = _map(arr, function (x) {
  10581. return x;
  10582. }).reverse();
  10583. async.reduce(reversed, memo, iterator, callback);
  10584. };
  10585. // foldr alias
  10586. async.foldr = async.reduceRight;
  10587. var _filter = function (eachfn, arr, iterator, callback) {
  10588. var results = [];
  10589. arr = _map(arr, function (x, i) {
  10590. return {index: i, value: x};
  10591. });
  10592. eachfn(arr, function (x, callback) {
  10593. iterator(x.value, function (v) {
  10594. if (v) {
  10595. results.push(x);
  10596. }
  10597. callback();
  10598. });
  10599. }, function (err) {
  10600. callback(_map(results.sort(function (a, b) {
  10601. return a.index - b.index;
  10602. }), function (x) {
  10603. return x.value;
  10604. }));
  10605. });
  10606. };
  10607. async.filter = doParallel(_filter);
  10608. async.filterSeries = doSeries(_filter);
  10609. // select alias
  10610. async.select = async.filter;
  10611. async.selectSeries = async.filterSeries;
  10612. var _reject = function (eachfn, arr, iterator, callback) {
  10613. var results = [];
  10614. arr = _map(arr, function (x, i) {
  10615. return {index: i, value: x};
  10616. });
  10617. eachfn(arr, function (x, callback) {
  10618. iterator(x.value, function (v) {
  10619. if (!v) {
  10620. results.push(x);
  10621. }
  10622. callback();
  10623. });
  10624. }, function (err) {
  10625. callback(_map(results.sort(function (a, b) {
  10626. return a.index - b.index;
  10627. }), function (x) {
  10628. return x.value;
  10629. }));
  10630. });
  10631. };
  10632. async.reject = doParallel(_reject);
  10633. async.rejectSeries = doSeries(_reject);
  10634. var _detect = function (eachfn, arr, iterator, main_callback) {
  10635. eachfn(arr, function (x, callback) {
  10636. iterator(x, function (result) {
  10637. if (result) {
  10638. main_callback(x);
  10639. main_callback = function () {};
  10640. }
  10641. else {
  10642. callback();
  10643. }
  10644. });
  10645. }, function (err) {
  10646. main_callback();
  10647. });
  10648. };
  10649. async.detect = doParallel(_detect);
  10650. async.detectSeries = doSeries(_detect);
  10651. async.some = function (arr, iterator, main_callback) {
  10652. async.each(arr, function (x, callback) {
  10653. iterator(x, function (v) {
  10654. if (v) {
  10655. main_callback(true);
  10656. main_callback = function () {};
  10657. }
  10658. callback();
  10659. });
  10660. }, function (err) {
  10661. main_callback(false);
  10662. });
  10663. };
  10664. // any alias
  10665. async.any = async.some;
  10666. async.every = function (arr, iterator, main_callback) {
  10667. async.each(arr, function (x, callback) {
  10668. iterator(x, function (v) {
  10669. if (!v) {
  10670. main_callback(false);
  10671. main_callback = function () {};
  10672. }
  10673. callback();
  10674. });
  10675. }, function (err) {
  10676. main_callback(true);
  10677. });
  10678. };
  10679. // all alias
  10680. async.all = async.every;
  10681. async.sortBy = function (arr, iterator, callback) {
  10682. async.map(arr, function (x, callback) {
  10683. iterator(x, function (err, criteria) {
  10684. if (err) {
  10685. callback(err);
  10686. }
  10687. else {
  10688. callback(null, {value: x, criteria: criteria});
  10689. }
  10690. });
  10691. }, function (err, results) {
  10692. if (err) {
  10693. return callback(err);
  10694. }
  10695. else {
  10696. var fn = function (left, right) {
  10697. var a = left.criteria, b = right.criteria;
  10698. return a < b ? -1 : a > b ? 1 : 0;
  10699. };
  10700. callback(null, _map(results.sort(fn), function (x) {
  10701. return x.value;
  10702. }));
  10703. }
  10704. });
  10705. };
  10706. async.auto = function (tasks, callback) {
  10707. callback = callback || function () {};
  10708. var keys = _keys(tasks);
  10709. var remainingTasks = keys.length
  10710. if (!remainingTasks) {
  10711. return callback();
  10712. }
  10713. var results = {};
  10714. var listeners = [];
  10715. var addListener = function (fn) {
  10716. listeners.unshift(fn);
  10717. };
  10718. var removeListener = function (fn) {
  10719. for (var i = 0; i < listeners.length; i += 1) {
  10720. if (listeners[i] === fn) {
  10721. listeners.splice(i, 1);
  10722. return;
  10723. }
  10724. }
  10725. };
  10726. var taskComplete = function () {
  10727. remainingTasks--
  10728. _each(listeners.slice(0), function (fn) {
  10729. fn();
  10730. });
  10731. };
  10732. addListener(function () {
  10733. if (!remainingTasks) {
  10734. var theCallback = callback;
  10735. // prevent final callback from calling itself if it errors
  10736. callback = function () {};
  10737. theCallback(null, results);
  10738. }
  10739. });
  10740. _each(keys, function (k) {
  10741. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  10742. var taskCallback = function (err) {
  10743. var args = Array.prototype.slice.call(arguments, 1);
  10744. if (args.length <= 1) {
  10745. args = args[0];
  10746. }
  10747. if (err) {
  10748. var safeResults = {};
  10749. _each(_keys(results), function(rkey) {
  10750. safeResults[rkey] = results[rkey];
  10751. });
  10752. safeResults[k] = args;
  10753. callback(err, safeResults);
  10754. // stop subsequent errors hitting callback multiple times
  10755. callback = function () {};
  10756. }
  10757. else {
  10758. results[k] = args;
  10759. async.setImmediate(taskComplete);
  10760. }
  10761. };
  10762. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  10763. var ready = function () {
  10764. return _reduce(requires, function (a, x) {
  10765. return (a && results.hasOwnProperty(x));
  10766. }, true) && !results.hasOwnProperty(k);
  10767. };
  10768. if (ready()) {
  10769. task[task.length - 1](taskCallback, results);
  10770. }
  10771. else {
  10772. var listener = function () {
  10773. if (ready()) {
  10774. removeListener(listener);
  10775. task[task.length - 1](taskCallback, results);
  10776. }
  10777. };
  10778. addListener(listener);
  10779. }
  10780. });
  10781. };
  10782. async.retry = function(times, task, callback) {
  10783. var DEFAULT_TIMES = 5;
  10784. var attempts = [];
  10785. // Use defaults if times not passed
  10786. if (typeof times === 'function') {
  10787. callback = task;
  10788. task = times;
  10789. times = DEFAULT_TIMES;
  10790. }
  10791. // Make sure times is a number
  10792. times = parseInt(times, 10) || DEFAULT_TIMES;
  10793. var wrappedTask = function(wrappedCallback, wrappedResults) {
  10794. var retryAttempt = function(task, finalAttempt) {
  10795. return function(seriesCallback) {
  10796. task(function(err, result){
  10797. seriesCallback(!err || finalAttempt, {err: err, result: result});
  10798. }, wrappedResults);
  10799. };
  10800. };
  10801. while (times) {
  10802. attempts.push(retryAttempt(task, !(times-=1)));
  10803. }
  10804. async.series(attempts, function(done, data){
  10805. data = data[data.length - 1];
  10806. (wrappedCallback || callback)(data.err, data.result);
  10807. });
  10808. }
  10809. // If a callback is passed, run this as a controll flow
  10810. return callback ? wrappedTask() : wrappedTask
  10811. };
  10812. async.waterfall = function (tasks, callback) {
  10813. callback = callback || function () {};
  10814. if (!_isArray(tasks)) {
  10815. var err = new Error('First argument to waterfall must be an array of functions');
  10816. return callback(err);
  10817. }
  10818. if (!tasks.length) {
  10819. return callback();
  10820. }
  10821. var wrapIterator = function (iterator) {
  10822. return function (err) {
  10823. if (err) {
  10824. callback.apply(null, arguments);
  10825. callback = function () {};
  10826. }
  10827. else {
  10828. var args = Array.prototype.slice.call(arguments, 1);
  10829. var next = iterator.next();
  10830. if (next) {
  10831. args.push(wrapIterator(next));
  10832. }
  10833. else {
  10834. args.push(callback);
  10835. }
  10836. async.setImmediate(function () {
  10837. iterator.apply(null, args);
  10838. });
  10839. }
  10840. };
  10841. };
  10842. wrapIterator(async.iterator(tasks))();
  10843. };
  10844. var _parallel = function(eachfn, tasks, callback) {
  10845. callback = callback || function () {};
  10846. if (_isArray(tasks)) {
  10847. eachfn.map(tasks, function (fn, callback) {
  10848. if (fn) {
  10849. fn(function (err) {
  10850. var args = Array.prototype.slice.call(arguments, 1);
  10851. if (args.length <= 1) {
  10852. args = args[0];
  10853. }
  10854. callback.call(null, err, args);
  10855. });
  10856. }
  10857. }, callback);
  10858. }
  10859. else {
  10860. var results = {};
  10861. eachfn.each(_keys(tasks), function (k, callback) {
  10862. tasks[k](function (err) {
  10863. var args = Array.prototype.slice.call(arguments, 1);
  10864. if (args.length <= 1) {
  10865. args = args[0];
  10866. }
  10867. results[k] = args;
  10868. callback(err);
  10869. });
  10870. }, function (err) {
  10871. callback(err, results);
  10872. });
  10873. }
  10874. };
  10875. async.parallel = function (tasks, callback) {
  10876. _parallel({ map: async.map, each: async.each }, tasks, callback);
  10877. };
  10878. async.parallelLimit = function(tasks, limit, callback) {
  10879. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  10880. };
  10881. async.series = function (tasks, callback) {
  10882. callback = callback || function () {};
  10883. if (_isArray(tasks)) {
  10884. async.mapSeries(tasks, function (fn, callback) {
  10885. if (fn) {
  10886. fn(function (err) {
  10887. var args = Array.prototype.slice.call(arguments, 1);
  10888. if (args.length <= 1) {
  10889. args = args[0];
  10890. }
  10891. callback.call(null, err, args);
  10892. });
  10893. }
  10894. }, callback);
  10895. }
  10896. else {
  10897. var results = {};
  10898. async.eachSeries(_keys(tasks), function (k, callback) {
  10899. tasks[k](function (err) {
  10900. var args = Array.prototype.slice.call(arguments, 1);
  10901. if (args.length <= 1) {
  10902. args = args[0];
  10903. }
  10904. results[k] = args;
  10905. callback(err);
  10906. });
  10907. }, function (err) {
  10908. callback(err, results);
  10909. });
  10910. }
  10911. };
  10912. async.iterator = function (tasks) {
  10913. var makeCallback = function (index) {
  10914. var fn = function () {
  10915. if (tasks.length) {
  10916. tasks[index].apply(null, arguments);
  10917. }
  10918. return fn.next();
  10919. };
  10920. fn.next = function () {
  10921. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  10922. };
  10923. return fn;
  10924. };
  10925. return makeCallback(0);
  10926. };
  10927. async.apply = function (fn) {
  10928. var args = Array.prototype.slice.call(arguments, 1);
  10929. return function () {
  10930. return fn.apply(
  10931. null, args.concat(Array.prototype.slice.call(arguments))
  10932. );
  10933. };
  10934. };
  10935. var _concat = function (eachfn, arr, fn, callback) {
  10936. var r = [];
  10937. eachfn(arr, function (x, cb) {
  10938. fn(x, function (err, y) {
  10939. r = r.concat(y || []);
  10940. cb(err);
  10941. });
  10942. }, function (err) {
  10943. callback(err, r);
  10944. });
  10945. };
  10946. async.concat = doParallel(_concat);
  10947. async.concatSeries = doSeries(_concat);
  10948. async.whilst = function (test, iterator, callback) {
  10949. if (test()) {
  10950. iterator(function (err) {
  10951. if (err) {
  10952. return callback(err);
  10953. }
  10954. async.whilst(test, iterator, callback);
  10955. });
  10956. }
  10957. else {
  10958. callback();
  10959. }
  10960. };
  10961. async.doWhilst = function (iterator, test, callback) {
  10962. iterator(function (err) {
  10963. if (err) {
  10964. return callback(err);
  10965. }
  10966. var args = Array.prototype.slice.call(arguments, 1);
  10967. if (test.apply(null, args)) {
  10968. async.doWhilst(iterator, test, callback);
  10969. }
  10970. else {
  10971. callback();
  10972. }
  10973. });
  10974. };
  10975. async.until = function (test, iterator, callback) {
  10976. if (!test()) {
  10977. iterator(function (err) {
  10978. if (err) {
  10979. return callback(err);
  10980. }
  10981. async.until(test, iterator, callback);
  10982. });
  10983. }
  10984. else {
  10985. callback();
  10986. }
  10987. };
  10988. async.doUntil = function (iterator, test, callback) {
  10989. iterator(function (err) {
  10990. if (err) {
  10991. return callback(err);
  10992. }
  10993. var args = Array.prototype.slice.call(arguments, 1);
  10994. if (!test.apply(null, args)) {
  10995. async.doUntil(iterator, test, callback);
  10996. }
  10997. else {
  10998. callback();
  10999. }
  11000. });
  11001. };
  11002. async.queue = function (worker, concurrency) {
  11003. if (concurrency === undefined) {
  11004. concurrency = 1;
  11005. }
  11006. function _insert(q, data, pos, callback) {
  11007. if (!q.started){
  11008. q.started = true;
  11009. }
  11010. if (!_isArray(data)) {
  11011. data = [data];
  11012. }
  11013. if(data.length == 0) {
  11014. // call drain immediately if there are no tasks
  11015. return async.setImmediate(function() {
  11016. if (q.drain) {
  11017. q.drain();
  11018. }
  11019. });
  11020. }
  11021. _each(data, function(task) {
  11022. var item = {
  11023. data: task,
  11024. callback: typeof callback === 'function' ? callback : null
  11025. };
  11026. if (pos) {
  11027. q.tasks.unshift(item);
  11028. } else {
  11029. q.tasks.push(item);
  11030. }
  11031. if (q.saturated && q.tasks.length === q.concurrency) {
  11032. q.saturated();
  11033. }
  11034. async.setImmediate(q.process);
  11035. });
  11036. }
  11037. var workers = 0;
  11038. var q = {
  11039. tasks: [],
  11040. concurrency: concurrency,
  11041. saturated: null,
  11042. empty: null,
  11043. drain: null,
  11044. started: false,
  11045. paused: false,
  11046. push: function (data, callback) {
  11047. _insert(q, data, false, callback);
  11048. },
  11049. kill: function () {
  11050. q.drain = null;
  11051. q.tasks = [];
  11052. },
  11053. unshift: function (data, callback) {
  11054. _insert(q, data, true, callback);
  11055. },
  11056. process: function () {
  11057. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  11058. var task = q.tasks.shift();
  11059. if (q.empty && q.tasks.length === 0) {
  11060. q.empty();
  11061. }
  11062. workers += 1;
  11063. var next = function () {
  11064. workers -= 1;
  11065. if (task.callback) {
  11066. task.callback.apply(task, arguments);
  11067. }
  11068. if (q.drain && q.tasks.length + workers === 0) {
  11069. q.drain();
  11070. }
  11071. q.process();
  11072. };
  11073. var cb = only_once(next);
  11074. worker(task.data, cb);
  11075. }
  11076. },
  11077. length: function () {
  11078. return q.tasks.length;
  11079. },
  11080. running: function () {
  11081. return workers;
  11082. },
  11083. idle: function() {
  11084. return q.tasks.length + workers === 0;
  11085. },
  11086. pause: function () {
  11087. if (q.paused === true) { return; }
  11088. q.paused = true;
  11089. q.process();
  11090. },
  11091. resume: function () {
  11092. if (q.paused === false) { return; }
  11093. q.paused = false;
  11094. q.process();
  11095. }
  11096. };
  11097. return q;
  11098. };
  11099. async.priorityQueue = function (worker, concurrency) {
  11100. function _compareTasks(a, b){
  11101. return a.priority - b.priority;
  11102. };
  11103. function _binarySearch(sequence, item, compare) {
  11104. var beg = -1,
  11105. end = sequence.length - 1;
  11106. while (beg < end) {
  11107. var mid = beg + ((end - beg + 1) >>> 1);
  11108. if (compare(item, sequence[mid]) >= 0) {
  11109. beg = mid;
  11110. } else {
  11111. end = mid - 1;
  11112. }
  11113. }
  11114. return beg;
  11115. }
  11116. function _insert(q, data, priority, callback) {
  11117. if (!q.started){
  11118. q.started = true;
  11119. }
  11120. if (!_isArray(data)) {
  11121. data = [data];
  11122. }
  11123. if(data.length == 0) {
  11124. // call drain immediately if there are no tasks
  11125. return async.setImmediate(function() {
  11126. if (q.drain) {
  11127. q.drain();
  11128. }
  11129. });
  11130. }
  11131. _each(data, function(task) {
  11132. var item = {
  11133. data: task,
  11134. priority: priority,
  11135. callback: typeof callback === 'function' ? callback : null
  11136. };
  11137. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  11138. if (q.saturated && q.tasks.length === q.concurrency) {
  11139. q.saturated();
  11140. }
  11141. async.setImmediate(q.process);
  11142. });
  11143. }
  11144. // Start with a normal queue
  11145. var q = async.queue(worker, concurrency);
  11146. // Override push to accept second parameter representing priority
  11147. q.push = function (data, priority, callback) {
  11148. _insert(q, data, priority, callback);
  11149. };
  11150. // Remove unshift function
  11151. delete q.unshift;
  11152. return q;
  11153. };
  11154. async.cargo = function (worker, payload) {
  11155. var working = false,
  11156. tasks = [];
  11157. var cargo = {
  11158. tasks: tasks,
  11159. payload: payload,
  11160. saturated: null,
  11161. empty: null,
  11162. drain: null,
  11163. drained: true,
  11164. push: function (data, callback) {
  11165. if (!_isArray(data)) {
  11166. data = [data];
  11167. }
  11168. _each(data, function(task) {
  11169. tasks.push({
  11170. data: task,
  11171. callback: typeof callback === 'function' ? callback : null
  11172. });
  11173. cargo.drained = false;
  11174. if (cargo.saturated && tasks.length === payload) {
  11175. cargo.saturated();
  11176. }
  11177. });
  11178. async.setImmediate(cargo.process);
  11179. },
  11180. process: function process() {
  11181. if (working) return;
  11182. if (tasks.length === 0) {
  11183. if(cargo.drain && !cargo.drained) cargo.drain();
  11184. cargo.drained = true;
  11185. return;
  11186. }
  11187. var ts = typeof payload === 'number'
  11188. ? tasks.splice(0, payload)
  11189. : tasks.splice(0, tasks.length);
  11190. var ds = _map(ts, function (task) {
  11191. return task.data;
  11192. });
  11193. if(cargo.empty) cargo.empty();
  11194. working = true;
  11195. worker(ds, function () {
  11196. working = false;
  11197. var args = arguments;
  11198. _each(ts, function (data) {
  11199. if (data.callback) {
  11200. data.callback.apply(null, args);
  11201. }
  11202. });
  11203. process();
  11204. });
  11205. },
  11206. length: function () {
  11207. return tasks.length;
  11208. },
  11209. running: function () {
  11210. return working;
  11211. }
  11212. };
  11213. return cargo;
  11214. };
  11215. var _console_fn = function (name) {
  11216. return function (fn) {
  11217. var args = Array.prototype.slice.call(arguments, 1);
  11218. fn.apply(null, args.concat([function (err) {
  11219. var args = Array.prototype.slice.call(arguments, 1);
  11220. if (typeof console !== 'undefined') {
  11221. if (err) {
  11222. if (console.error) {
  11223. console.error(err);
  11224. }
  11225. }
  11226. else if (console[name]) {
  11227. _each(args, function (x) {
  11228. console[name](x);
  11229. });
  11230. }
  11231. }
  11232. }]));
  11233. };
  11234. };
  11235. async.log = _console_fn('log');
  11236. async.dir = _console_fn('dir');
  11237. /*async.info = _console_fn('info');
  11238. async.warn = _console_fn('warn');
  11239. async.error = _console_fn('error');*/
  11240. async.memoize = function (fn, hasher) {
  11241. var memo = {};
  11242. var queues = {};
  11243. hasher = hasher || function (x) {
  11244. return x;
  11245. };
  11246. var memoized = function () {
  11247. var args = Array.prototype.slice.call(arguments);
  11248. var callback = args.pop();
  11249. var key = hasher.apply(null, args);
  11250. if (key in memo) {
  11251. async.nextTick(function () {
  11252. callback.apply(null, memo[key]);
  11253. });
  11254. }
  11255. else if (key in queues) {
  11256. queues[key].push(callback);
  11257. }
  11258. else {
  11259. queues[key] = [callback];
  11260. fn.apply(null, args.concat([function () {
  11261. memo[key] = arguments;
  11262. var q = queues[key];
  11263. delete queues[key];
  11264. for (var i = 0, l = q.length; i < l; i++) {
  11265. q[i].apply(null, arguments);
  11266. }
  11267. }]));
  11268. }
  11269. };
  11270. memoized.memo = memo;
  11271. memoized.unmemoized = fn;
  11272. return memoized;
  11273. };
  11274. async.unmemoize = function (fn) {
  11275. return function () {
  11276. return (fn.unmemoized || fn).apply(null, arguments);
  11277. };
  11278. };
  11279. async.times = function (count, iterator, callback) {
  11280. var counter = [];
  11281. for (var i = 0; i < count; i++) {
  11282. counter.push(i);
  11283. }
  11284. return async.map(counter, iterator, callback);
  11285. };
  11286. async.timesSeries = function (count, iterator, callback) {
  11287. var counter = [];
  11288. for (var i = 0; i < count; i++) {
  11289. counter.push(i);
  11290. }
  11291. return async.mapSeries(counter, iterator, callback);
  11292. };
  11293. async.seq = function (/* functions... */) {
  11294. var fns = arguments;
  11295. return function () {
  11296. var that = this;
  11297. var args = Array.prototype.slice.call(arguments);
  11298. var callback = args.pop();
  11299. async.reduce(fns, args, function (newargs, fn, cb) {
  11300. fn.apply(that, newargs.concat([function () {
  11301. var err = arguments[0];
  11302. var nextargs = Array.prototype.slice.call(arguments, 1);
  11303. cb(err, nextargs);
  11304. }]))
  11305. },
  11306. function (err, results) {
  11307. callback.apply(that, [err].concat(results));
  11308. });
  11309. };
  11310. };
  11311. async.compose = function (/* functions... */) {
  11312. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  11313. };
  11314. var _applyEach = function (eachfn, fns /*args...*/) {
  11315. var go = function () {
  11316. var that = this;
  11317. var args = Array.prototype.slice.call(arguments);
  11318. var callback = args.pop();
  11319. return eachfn(fns, function (fn, cb) {
  11320. fn.apply(that, args.concat([cb]));
  11321. },
  11322. callback);
  11323. };
  11324. if (arguments.length > 2) {
  11325. var args = Array.prototype.slice.call(arguments, 2);
  11326. return go.apply(this, args);
  11327. }
  11328. else {
  11329. return go;
  11330. }
  11331. };
  11332. async.applyEach = doParallel(_applyEach);
  11333. async.applyEachSeries = doSeries(_applyEach);
  11334. async.forever = function (fn, callback) {
  11335. function next(err) {
  11336. if (err) {
  11337. if (callback) {
  11338. return callback(err);
  11339. }
  11340. throw err;
  11341. }
  11342. fn(next);
  11343. }
  11344. next();
  11345. };
  11346. // Node.js
  11347. if (typeof module !== 'undefined' && module.exports) {
  11348. module.exports = async;
  11349. }
  11350. // AMD / RequireJS
  11351. else if (typeof define !== 'undefined' && define.amd) {
  11352. define([], function () {
  11353. return async;
  11354. });
  11355. }
  11356. // included directly via <script> tag
  11357. else {
  11358. root.async = async;
  11359. }
  11360. }());
  11361. }).call(this,require('_process'))
  11362. },{"_process":44}],43:[function(require,module,exports){
  11363. // Copyright Joyent, Inc. and other Node contributors.
  11364. //
  11365. // Permission is hereby granted, free of charge, to any person obtaining a
  11366. // copy of this software and associated documentation files (the
  11367. // "Software"), to deal in the Software without restriction, including
  11368. // without limitation the rights to use, copy, modify, merge, publish,
  11369. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11370. // persons to whom the Software is furnished to do so, subject to the
  11371. // following conditions:
  11372. //
  11373. // The above copyright notice and this permission notice shall be included
  11374. // in all copies or substantial portions of the Software.
  11375. //
  11376. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11377. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11378. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11379. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11380. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11381. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11382. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11383. function EventEmitter() {
  11384. this._events = this._events || {};
  11385. this._maxListeners = this._maxListeners || undefined;
  11386. }
  11387. module.exports = EventEmitter;
  11388. // Backwards-compat with node 0.10.x
  11389. EventEmitter.EventEmitter = EventEmitter;
  11390. EventEmitter.prototype._events = undefined;
  11391. EventEmitter.prototype._maxListeners = undefined;
  11392. // By default EventEmitters will print a warning if more than 10 listeners are
  11393. // added to it. This is a useful default which helps finding memory leaks.
  11394. EventEmitter.defaultMaxListeners = 10;
  11395. // Obviously not all Emitters should be limited to 10. This function allows
  11396. // that to be increased. Set to zero for unlimited.
  11397. EventEmitter.prototype.setMaxListeners = function(n) {
  11398. if (!isNumber(n) || n < 0 || isNaN(n))
  11399. throw TypeError('n must be a positive number');
  11400. this._maxListeners = n;
  11401. return this;
  11402. };
  11403. EventEmitter.prototype.emit = function(type) {
  11404. var er, handler, len, args, i, listeners;
  11405. if (!this._events)
  11406. this._events = {};
  11407. // If there is no 'error' event listener then throw.
  11408. if (type === 'error') {
  11409. if (!this._events.error ||
  11410. (isObject(this._events.error) && !this._events.error.length)) {
  11411. er = arguments[1];
  11412. if (er instanceof Error) {
  11413. throw er; // Unhandled 'error' event
  11414. }
  11415. throw TypeError('Uncaught, unspecified "error" event.');
  11416. }
  11417. }
  11418. handler = this._events[type];
  11419. if (isUndefined(handler))
  11420. return false;
  11421. if (isFunction(handler)) {
  11422. switch (arguments.length) {
  11423. // fast cases
  11424. case 1:
  11425. handler.call(this);
  11426. break;
  11427. case 2:
  11428. handler.call(this, arguments[1]);
  11429. break;
  11430. case 3:
  11431. handler.call(this, arguments[1], arguments[2]);
  11432. break;
  11433. // slower
  11434. default:
  11435. len = arguments.length;
  11436. args = new Array(len - 1);
  11437. for (i = 1; i < len; i++)
  11438. args[i - 1] = arguments[i];
  11439. handler.apply(this, args);
  11440. }
  11441. } else if (isObject(handler)) {
  11442. len = arguments.length;
  11443. args = new Array(len - 1);
  11444. for (i = 1; i < len; i++)
  11445. args[i - 1] = arguments[i];
  11446. listeners = handler.slice();
  11447. len = listeners.length;
  11448. for (i = 0; i < len; i++)
  11449. listeners[i].apply(this, args);
  11450. }
  11451. return true;
  11452. };
  11453. EventEmitter.prototype.addListener = function(type, listener) {
  11454. var m;
  11455. if (!isFunction(listener))
  11456. throw TypeError('listener must be a function');
  11457. if (!this._events)
  11458. this._events = {};
  11459. // To avoid recursion in the case that type === "newListener"! Before
  11460. // adding it to the listeners, first emit "newListener".
  11461. if (this._events.newListener)
  11462. this.emit('newListener', type,
  11463. isFunction(listener.listener) ?
  11464. listener.listener : listener);
  11465. if (!this._events[type])
  11466. // Optimize the case of one listener. Don't need the extra array object.
  11467. this._events[type] = listener;
  11468. else if (isObject(this._events[type]))
  11469. // If we've already got an array, just append.
  11470. this._events[type].push(listener);
  11471. else
  11472. // Adding the second element, need to change to array.
  11473. this._events[type] = [this._events[type], listener];
  11474. // Check for listener leak
  11475. if (isObject(this._events[type]) && !this._events[type].warned) {
  11476. var m;
  11477. if (!isUndefined(this._maxListeners)) {
  11478. m = this._maxListeners;
  11479. } else {
  11480. m = EventEmitter.defaultMaxListeners;
  11481. }
  11482. if (m && m > 0 && this._events[type].length > m) {
  11483. this._events[type].warned = true;
  11484. console.error('(node) warning: possible EventEmitter memory ' +
  11485. 'leak detected. %d listeners added. ' +
  11486. 'Use emitter.setMaxListeners() to increase limit.',
  11487. this._events[type].length);
  11488. if (typeof console.trace === 'function') {
  11489. // not supported in IE 10
  11490. console.trace();
  11491. }
  11492. }
  11493. }
  11494. return this;
  11495. };
  11496. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  11497. EventEmitter.prototype.once = function(type, listener) {
  11498. if (!isFunction(listener))
  11499. throw TypeError('listener must be a function');
  11500. var fired = false;
  11501. function g() {
  11502. this.removeListener(type, g);
  11503. if (!fired) {
  11504. fired = true;
  11505. listener.apply(this, arguments);
  11506. }
  11507. }
  11508. g.listener = listener;
  11509. this.on(type, g);
  11510. return this;
  11511. };
  11512. // emits a 'removeListener' event iff the listener was removed
  11513. EventEmitter.prototype.removeListener = function(type, listener) {
  11514. var list, position, length, i;
  11515. if (!isFunction(listener))
  11516. throw TypeError('listener must be a function');
  11517. if (!this._events || !this._events[type])
  11518. return this;
  11519. list = this._events[type];
  11520. length = list.length;
  11521. position = -1;
  11522. if (list === listener ||
  11523. (isFunction(list.listener) && list.listener === listener)) {
  11524. delete this._events[type];
  11525. if (this._events.removeListener)
  11526. this.emit('removeListener', type, listener);
  11527. } else if (isObject(list)) {
  11528. for (i = length; i-- > 0;) {
  11529. if (list[i] === listener ||
  11530. (list[i].listener && list[i].listener === listener)) {
  11531. position = i;
  11532. break;
  11533. }
  11534. }
  11535. if (position < 0)
  11536. return this;
  11537. if (list.length === 1) {
  11538. list.length = 0;
  11539. delete this._events[type];
  11540. } else {
  11541. list.splice(position, 1);
  11542. }
  11543. if (this._events.removeListener)
  11544. this.emit('removeListener', type, listener);
  11545. }
  11546. return this;
  11547. };
  11548. EventEmitter.prototype.removeAllListeners = function(type) {
  11549. var key, listeners;
  11550. if (!this._events)
  11551. return this;
  11552. // not listening for removeListener, no need to emit
  11553. if (!this._events.removeListener) {
  11554. if (arguments.length === 0)
  11555. this._events = {};
  11556. else if (this._events[type])
  11557. delete this._events[type];
  11558. return this;
  11559. }
  11560. // emit removeListener for all listeners on all events
  11561. if (arguments.length === 0) {
  11562. for (key in this._events) {
  11563. if (key === 'removeListener') continue;
  11564. this.removeAllListeners(key);
  11565. }
  11566. this.removeAllListeners('removeListener');
  11567. this._events = {};
  11568. return this;
  11569. }
  11570. listeners = this._events[type];
  11571. if (isFunction(listeners)) {
  11572. this.removeListener(type, listeners);
  11573. } else {
  11574. // LIFO order
  11575. while (listeners.length)
  11576. this.removeListener(type, listeners[listeners.length - 1]);
  11577. }
  11578. delete this._events[type];
  11579. return this;
  11580. };
  11581. EventEmitter.prototype.listeners = function(type) {
  11582. var ret;
  11583. if (!this._events || !this._events[type])
  11584. ret = [];
  11585. else if (isFunction(this._events[type]))
  11586. ret = [this._events[type]];
  11587. else
  11588. ret = this._events[type].slice();
  11589. return ret;
  11590. };
  11591. EventEmitter.listenerCount = function(emitter, type) {
  11592. var ret;
  11593. if (!emitter._events || !emitter._events[type])
  11594. ret = 0;
  11595. else if (isFunction(emitter._events[type]))
  11596. ret = 1;
  11597. else
  11598. ret = emitter._events[type].length;
  11599. return ret;
  11600. };
  11601. function isFunction(arg) {
  11602. return typeof arg === 'function';
  11603. }
  11604. function isNumber(arg) {
  11605. return typeof arg === 'number';
  11606. }
  11607. function isObject(arg) {
  11608. return typeof arg === 'object' && arg !== null;
  11609. }
  11610. function isUndefined(arg) {
  11611. return arg === void 0;
  11612. }
  11613. },{}],44:[function(require,module,exports){
  11614. // shim for using process in browser
  11615. var process = module.exports = {};
  11616. var queue = [];
  11617. var draining = false;
  11618. var currentQueue;
  11619. var queueIndex = -1;
  11620. function cleanUpNextTick() {
  11621. draining = false;
  11622. if (currentQueue.length) {
  11623. queue = currentQueue.concat(queue);
  11624. } else {
  11625. queueIndex = -1;
  11626. }
  11627. if (queue.length) {
  11628. drainQueue();
  11629. }
  11630. }
  11631. function drainQueue() {
  11632. if (draining) {
  11633. return;
  11634. }
  11635. var timeout = setTimeout(cleanUpNextTick);
  11636. draining = true;
  11637. var len = queue.length;
  11638. while(len) {
  11639. currentQueue = queue;
  11640. queue = [];
  11641. while (++queueIndex < len) {
  11642. if (currentQueue) {
  11643. currentQueue[queueIndex].run();
  11644. }
  11645. }
  11646. queueIndex = -1;
  11647. len = queue.length;
  11648. }
  11649. currentQueue = null;
  11650. draining = false;
  11651. clearTimeout(timeout);
  11652. }
  11653. process.nextTick = function (fun) {
  11654. var args = new Array(arguments.length - 1);
  11655. if (arguments.length > 1) {
  11656. for (var i = 1; i < arguments.length; i++) {
  11657. args[i - 1] = arguments[i];
  11658. }
  11659. }
  11660. queue.push(new Item(fun, args));
  11661. if (queue.length === 1 && !draining) {
  11662. setTimeout(drainQueue, 0);
  11663. }
  11664. };
  11665. // v8 likes predictible objects
  11666. function Item(fun, array) {
  11667. this.fun = fun;
  11668. this.array = array;
  11669. }
  11670. Item.prototype.run = function () {
  11671. this.fun.apply(null, this.array);
  11672. };
  11673. process.title = 'browser';
  11674. process.browser = true;
  11675. process.env = {};
  11676. process.argv = [];
  11677. process.version = ''; // empty string to avoid regexp issues
  11678. process.versions = {};
  11679. function noop() {}
  11680. process.on = noop;
  11681. process.addListener = noop;
  11682. process.once = noop;
  11683. process.off = noop;
  11684. process.removeListener = noop;
  11685. process.removeAllListeners = noop;
  11686. process.emit = noop;
  11687. process.binding = function (name) {
  11688. throw new Error('process.binding is not supported');
  11689. };
  11690. process.cwd = function () { return '/' };
  11691. process.chdir = function (dir) {
  11692. throw new Error('process.chdir is not supported');
  11693. };
  11694. process.umask = function() { return 0; };
  11695. },{}],45:[function(require,module,exports){
  11696. (function (process,global){
  11697. /*!
  11698. * @overview es6-promise - a tiny implementation of Promises/A+.
  11699. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  11700. * @license Licensed under MIT license
  11701. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  11702. * @version 3.0.2
  11703. */
  11704. (function() {
  11705. "use strict";
  11706. function lib$es6$promise$utils$$objectOrFunction(x) {
  11707. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  11708. }
  11709. function lib$es6$promise$utils$$isFunction(x) {
  11710. return typeof x === 'function';
  11711. }
  11712. function lib$es6$promise$utils$$isMaybeThenable(x) {
  11713. return typeof x === 'object' && x !== null;
  11714. }
  11715. var lib$es6$promise$utils$$_isArray;
  11716. if (!Array.isArray) {
  11717. lib$es6$promise$utils$$_isArray = function (x) {
  11718. return Object.prototype.toString.call(x) === '[object Array]';
  11719. };
  11720. } else {
  11721. lib$es6$promise$utils$$_isArray = Array.isArray;
  11722. }
  11723. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  11724. var lib$es6$promise$asap$$len = 0;
  11725. var lib$es6$promise$asap$$toString = {}.toString;
  11726. var lib$es6$promise$asap$$vertxNext;
  11727. var lib$es6$promise$asap$$customSchedulerFn;
  11728. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  11729. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  11730. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  11731. lib$es6$promise$asap$$len += 2;
  11732. if (lib$es6$promise$asap$$len === 2) {
  11733. // If len is 2, that means that we need to schedule an async flush.
  11734. // If additional callbacks are queued before the queue is flushed, they
  11735. // will be processed by this flush that we are scheduling.
  11736. if (lib$es6$promise$asap$$customSchedulerFn) {
  11737. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  11738. } else {
  11739. lib$es6$promise$asap$$scheduleFlush();
  11740. }
  11741. }
  11742. }
  11743. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  11744. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  11745. }
  11746. function lib$es6$promise$asap$$setAsap(asapFn) {
  11747. lib$es6$promise$asap$$asap = asapFn;
  11748. }
  11749. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  11750. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  11751. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  11752. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  11753. // test for web worker but not in IE10
  11754. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  11755. typeof importScripts !== 'undefined' &&
  11756. typeof MessageChannel !== 'undefined';
  11757. // node
  11758. function lib$es6$promise$asap$$useNextTick() {
  11759. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  11760. // see https://github.com/cujojs/when/issues/410 for details
  11761. return function() {
  11762. process.nextTick(lib$es6$promise$asap$$flush);
  11763. };
  11764. }
  11765. // vertx
  11766. function lib$es6$promise$asap$$useVertxTimer() {
  11767. return function() {
  11768. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  11769. };
  11770. }
  11771. function lib$es6$promise$asap$$useMutationObserver() {
  11772. var iterations = 0;
  11773. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  11774. var node = document.createTextNode('');
  11775. observer.observe(node, { characterData: true });
  11776. return function() {
  11777. node.data = (iterations = ++iterations % 2);
  11778. };
  11779. }
  11780. // web worker
  11781. function lib$es6$promise$asap$$useMessageChannel() {
  11782. var channel = new MessageChannel();
  11783. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  11784. return function () {
  11785. channel.port2.postMessage(0);
  11786. };
  11787. }
  11788. function lib$es6$promise$asap$$useSetTimeout() {
  11789. return function() {
  11790. setTimeout(lib$es6$promise$asap$$flush, 1);
  11791. };
  11792. }
  11793. var lib$es6$promise$asap$$queue = new Array(1000);
  11794. function lib$es6$promise$asap$$flush() {
  11795. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  11796. var callback = lib$es6$promise$asap$$queue[i];
  11797. var arg = lib$es6$promise$asap$$queue[i+1];
  11798. callback(arg);
  11799. lib$es6$promise$asap$$queue[i] = undefined;
  11800. lib$es6$promise$asap$$queue[i+1] = undefined;
  11801. }
  11802. lib$es6$promise$asap$$len = 0;
  11803. }
  11804. function lib$es6$promise$asap$$attemptVertx() {
  11805. try {
  11806. var r = require;
  11807. var vertx = r('vertx');
  11808. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  11809. return lib$es6$promise$asap$$useVertxTimer();
  11810. } catch(e) {
  11811. return lib$es6$promise$asap$$useSetTimeout();
  11812. }
  11813. }
  11814. var lib$es6$promise$asap$$scheduleFlush;
  11815. // Decide what async method to use to triggering processing of queued callbacks:
  11816. if (lib$es6$promise$asap$$isNode) {
  11817. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  11818. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  11819. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  11820. } else if (lib$es6$promise$asap$$isWorker) {
  11821. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  11822. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  11823. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  11824. } else {
  11825. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  11826. }
  11827. function lib$es6$promise$$internal$$noop() {}
  11828. var lib$es6$promise$$internal$$PENDING = void 0;
  11829. var lib$es6$promise$$internal$$FULFILLED = 1;
  11830. var lib$es6$promise$$internal$$REJECTED = 2;
  11831. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11832. function lib$es6$promise$$internal$$selfFulfillment() {
  11833. return new TypeError("You cannot resolve a promise with itself");
  11834. }
  11835. function lib$es6$promise$$internal$$cannotReturnOwn() {
  11836. return new TypeError('A promises callback cannot return that same promise.');
  11837. }
  11838. function lib$es6$promise$$internal$$getThen(promise) {
  11839. try {
  11840. return promise.then;
  11841. } catch(error) {
  11842. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  11843. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  11844. }
  11845. }
  11846. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  11847. try {
  11848. then.call(value, fulfillmentHandler, rejectionHandler);
  11849. } catch(e) {
  11850. return e;
  11851. }
  11852. }
  11853. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  11854. lib$es6$promise$asap$$asap(function(promise) {
  11855. var sealed = false;
  11856. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  11857. if (sealed) { return; }
  11858. sealed = true;
  11859. if (thenable !== value) {
  11860. lib$es6$promise$$internal$$resolve(promise, value);
  11861. } else {
  11862. lib$es6$promise$$internal$$fulfill(promise, value);
  11863. }
  11864. }, function(reason) {
  11865. if (sealed) { return; }
  11866. sealed = true;
  11867. lib$es6$promise$$internal$$reject(promise, reason);
  11868. }, 'Settle: ' + (promise._label || ' unknown promise'));
  11869. if (!sealed && error) {
  11870. sealed = true;
  11871. lib$es6$promise$$internal$$reject(promise, error);
  11872. }
  11873. }, promise);
  11874. }
  11875. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  11876. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  11877. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  11878. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  11879. lib$es6$promise$$internal$$reject(promise, thenable._result);
  11880. } else {
  11881. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  11882. lib$es6$promise$$internal$$resolve(promise, value);
  11883. }, function(reason) {
  11884. lib$es6$promise$$internal$$reject(promise, reason);
  11885. });
  11886. }
  11887. }
  11888. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  11889. if (maybeThenable.constructor === promise.constructor) {
  11890. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  11891. } else {
  11892. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  11893. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  11894. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  11895. } else if (then === undefined) {
  11896. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11897. } else if (lib$es6$promise$utils$$isFunction(then)) {
  11898. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  11899. } else {
  11900. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11901. }
  11902. }
  11903. }
  11904. function lib$es6$promise$$internal$$resolve(promise, value) {
  11905. if (promise === value) {
  11906. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  11907. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  11908. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  11909. } else {
  11910. lib$es6$promise$$internal$$fulfill(promise, value);
  11911. }
  11912. }
  11913. function lib$es6$promise$$internal$$publishRejection(promise) {
  11914. if (promise._onerror) {
  11915. promise._onerror(promise._result);
  11916. }
  11917. lib$es6$promise$$internal$$publish(promise);
  11918. }
  11919. function lib$es6$promise$$internal$$fulfill(promise, value) {
  11920. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11921. promise._result = value;
  11922. promise._state = lib$es6$promise$$internal$$FULFILLED;
  11923. if (promise._subscribers.length !== 0) {
  11924. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  11925. }
  11926. }
  11927. function lib$es6$promise$$internal$$reject(promise, reason) {
  11928. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11929. promise._state = lib$es6$promise$$internal$$REJECTED;
  11930. promise._result = reason;
  11931. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  11932. }
  11933. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  11934. var subscribers = parent._subscribers;
  11935. var length = subscribers.length;
  11936. parent._onerror = null;
  11937. subscribers[length] = child;
  11938. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  11939. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  11940. if (length === 0 && parent._state) {
  11941. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  11942. }
  11943. }
  11944. function lib$es6$promise$$internal$$publish(promise) {
  11945. var subscribers = promise._subscribers;
  11946. var settled = promise._state;
  11947. if (subscribers.length === 0) { return; }
  11948. var child, callback, detail = promise._result;
  11949. for (var i = 0; i < subscribers.length; i += 3) {
  11950. child = subscribers[i];
  11951. callback = subscribers[i + settled];
  11952. if (child) {
  11953. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  11954. } else {
  11955. callback(detail);
  11956. }
  11957. }
  11958. promise._subscribers.length = 0;
  11959. }
  11960. function lib$es6$promise$$internal$$ErrorObject() {
  11961. this.error = null;
  11962. }
  11963. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11964. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  11965. try {
  11966. return callback(detail);
  11967. } catch(e) {
  11968. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  11969. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  11970. }
  11971. }
  11972. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  11973. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  11974. value, error, succeeded, failed;
  11975. if (hasCallback) {
  11976. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  11977. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  11978. failed = true;
  11979. error = value.error;
  11980. value = null;
  11981. } else {
  11982. succeeded = true;
  11983. }
  11984. if (promise === value) {
  11985. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  11986. return;
  11987. }
  11988. } else {
  11989. value = detail;
  11990. succeeded = true;
  11991. }
  11992. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  11993. // noop
  11994. } else if (hasCallback && succeeded) {
  11995. lib$es6$promise$$internal$$resolve(promise, value);
  11996. } else if (failed) {
  11997. lib$es6$promise$$internal$$reject(promise, error);
  11998. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  11999. lib$es6$promise$$internal$$fulfill(promise, value);
  12000. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  12001. lib$es6$promise$$internal$$reject(promise, value);
  12002. }
  12003. }
  12004. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  12005. try {
  12006. resolver(function resolvePromise(value){
  12007. lib$es6$promise$$internal$$resolve(promise, value);
  12008. }, function rejectPromise(reason) {
  12009. lib$es6$promise$$internal$$reject(promise, reason);
  12010. });
  12011. } catch(e) {
  12012. lib$es6$promise$$internal$$reject(promise, e);
  12013. }
  12014. }
  12015. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  12016. var enumerator = this;
  12017. enumerator._instanceConstructor = Constructor;
  12018. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  12019. if (enumerator._validateInput(input)) {
  12020. enumerator._input = input;
  12021. enumerator.length = input.length;
  12022. enumerator._remaining = input.length;
  12023. enumerator._init();
  12024. if (enumerator.length === 0) {
  12025. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12026. } else {
  12027. enumerator.length = enumerator.length || 0;
  12028. enumerator._enumerate();
  12029. if (enumerator._remaining === 0) {
  12030. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  12031. }
  12032. }
  12033. } else {
  12034. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  12035. }
  12036. }
  12037. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  12038. return lib$es6$promise$utils$$isArray(input);
  12039. };
  12040. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  12041. return new Error('Array Methods must be provided an Array');
  12042. };
  12043. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  12044. this._result = new Array(this.length);
  12045. };
  12046. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  12047. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  12048. var enumerator = this;
  12049. var length = enumerator.length;
  12050. var promise = enumerator.promise;
  12051. var input = enumerator._input;
  12052. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12053. enumerator._eachEntry(input[i], i);
  12054. }
  12055. };
  12056. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  12057. var enumerator = this;
  12058. var c = enumerator._instanceConstructor;
  12059. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  12060. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  12061. entry._onerror = null;
  12062. enumerator._settledAt(entry._state, i, entry._result);
  12063. } else {
  12064. enumerator._willSettleAt(c.resolve(entry), i);
  12065. }
  12066. } else {
  12067. enumerator._remaining--;
  12068. enumerator._result[i] = entry;
  12069. }
  12070. };
  12071. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  12072. var enumerator = this;
  12073. var promise = enumerator.promise;
  12074. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  12075. enumerator._remaining--;
  12076. if (state === lib$es6$promise$$internal$$REJECTED) {
  12077. lib$es6$promise$$internal$$reject(promise, value);
  12078. } else {
  12079. enumerator._result[i] = value;
  12080. }
  12081. }
  12082. if (enumerator._remaining === 0) {
  12083. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  12084. }
  12085. };
  12086. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  12087. var enumerator = this;
  12088. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  12089. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  12090. }, function(reason) {
  12091. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  12092. });
  12093. };
  12094. function lib$es6$promise$promise$all$$all(entries) {
  12095. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  12096. }
  12097. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  12098. function lib$es6$promise$promise$race$$race(entries) {
  12099. /*jshint validthis:true */
  12100. var Constructor = this;
  12101. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12102. if (!lib$es6$promise$utils$$isArray(entries)) {
  12103. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  12104. return promise;
  12105. }
  12106. var length = entries.length;
  12107. function onFulfillment(value) {
  12108. lib$es6$promise$$internal$$resolve(promise, value);
  12109. }
  12110. function onRejection(reason) {
  12111. lib$es6$promise$$internal$$reject(promise, reason);
  12112. }
  12113. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  12114. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  12115. }
  12116. return promise;
  12117. }
  12118. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  12119. function lib$es6$promise$promise$resolve$$resolve(object) {
  12120. /*jshint validthis:true */
  12121. var Constructor = this;
  12122. if (object && typeof object === 'object' && object.constructor === Constructor) {
  12123. return object;
  12124. }
  12125. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12126. lib$es6$promise$$internal$$resolve(promise, object);
  12127. return promise;
  12128. }
  12129. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  12130. function lib$es6$promise$promise$reject$$reject(reason) {
  12131. /*jshint validthis:true */
  12132. var Constructor = this;
  12133. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  12134. lib$es6$promise$$internal$$reject(promise, reason);
  12135. return promise;
  12136. }
  12137. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  12138. var lib$es6$promise$promise$$counter = 0;
  12139. function lib$es6$promise$promise$$needsResolver() {
  12140. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  12141. }
  12142. function lib$es6$promise$promise$$needsNew() {
  12143. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  12144. }
  12145. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  12146. /**
  12147. Promise objects represent the eventual result of an asynchronous operation. The
  12148. primary way of interacting with a promise is through its `then` method, which
  12149. registers callbacks to receive either a promise's eventual value or the reason
  12150. why the promise cannot be fulfilled.
  12151. Terminology
  12152. -----------
  12153. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  12154. - `thenable` is an object or function that defines a `then` method.
  12155. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  12156. - `exception` is a value that is thrown using the throw statement.
  12157. - `reason` is a value that indicates why a promise was rejected.
  12158. - `settled` the final resting state of a promise, fulfilled or rejected.
  12159. A promise can be in one of three states: pending, fulfilled, or rejected.
  12160. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  12161. state. Promises that are rejected have a rejection reason and are in the
  12162. rejected state. A fulfillment value is never a thenable.
  12163. Promises can also be said to *resolve* a value. If this value is also a
  12164. promise, then the original promise's settled state will match the value's
  12165. settled state. So a promise that *resolves* a promise that rejects will
  12166. itself reject, and a promise that *resolves* a promise that fulfills will
  12167. itself fulfill.
  12168. Basic Usage:
  12169. ------------
  12170. ```js
  12171. var promise = new Promise(function(resolve, reject) {
  12172. // on success
  12173. resolve(value);
  12174. // on failure
  12175. reject(reason);
  12176. });
  12177. promise.then(function(value) {
  12178. // on fulfillment
  12179. }, function(reason) {
  12180. // on rejection
  12181. });
  12182. ```
  12183. Advanced Usage:
  12184. ---------------
  12185. Promises shine when abstracting away asynchronous interactions such as
  12186. `XMLHttpRequest`s.
  12187. ```js
  12188. function getJSON(url) {
  12189. return new Promise(function(resolve, reject){
  12190. var xhr = new XMLHttpRequest();
  12191. xhr.open('GET', url);
  12192. xhr.onreadystatechange = handler;
  12193. xhr.responseType = 'json';
  12194. xhr.setRequestHeader('Accept', 'application/json');
  12195. xhr.send();
  12196. function handler() {
  12197. if (this.readyState === this.DONE) {
  12198. if (this.status === 200) {
  12199. resolve(this.response);
  12200. } else {
  12201. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  12202. }
  12203. }
  12204. };
  12205. });
  12206. }
  12207. getJSON('/posts.json').then(function(json) {
  12208. // on fulfillment
  12209. }, function(reason) {
  12210. // on rejection
  12211. });
  12212. ```
  12213. Unlike callbacks, promises are great composable primitives.
  12214. ```js
  12215. Promise.all([
  12216. getJSON('/posts'),
  12217. getJSON('/comments')
  12218. ]).then(function(values){
  12219. values[0] // => postsJSON
  12220. values[1] // => commentsJSON
  12221. return values;
  12222. });
  12223. ```
  12224. @class Promise
  12225. @param {function} resolver
  12226. Useful for tooling.
  12227. @constructor
  12228. */
  12229. function lib$es6$promise$promise$$Promise(resolver) {
  12230. this._id = lib$es6$promise$promise$$counter++;
  12231. this._state = undefined;
  12232. this._result = undefined;
  12233. this._subscribers = [];
  12234. if (lib$es6$promise$$internal$$noop !== resolver) {
  12235. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12236. lib$es6$promise$promise$$needsResolver();
  12237. }
  12238. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12239. lib$es6$promise$promise$$needsNew();
  12240. }
  12241. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12242. }
  12243. }
  12244. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12245. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12246. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12247. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12248. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12249. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12250. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12251. lib$es6$promise$promise$$Promise.prototype = {
  12252. constructor: lib$es6$promise$promise$$Promise,
  12253. /**
  12254. The primary way of interacting with a promise is through its `then` method,
  12255. which registers callbacks to receive either a promise's eventual value or the
  12256. reason why the promise cannot be fulfilled.
  12257. ```js
  12258. findUser().then(function(user){
  12259. // user is available
  12260. }, function(reason){
  12261. // user is unavailable, and you are given the reason why
  12262. });
  12263. ```
  12264. Chaining
  12265. --------
  12266. The return value of `then` is itself a promise. This second, 'downstream'
  12267. promise is resolved with the return value of the first promise's fulfillment
  12268. or rejection handler, or rejected if the handler throws an exception.
  12269. ```js
  12270. findUser().then(function (user) {
  12271. return user.name;
  12272. }, function (reason) {
  12273. return 'default name';
  12274. }).then(function (userName) {
  12275. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  12276. // will be `'default name'`
  12277. });
  12278. findUser().then(function (user) {
  12279. throw new Error('Found user, but still unhappy');
  12280. }, function (reason) {
  12281. throw new Error('`findUser` rejected and we're unhappy');
  12282. }).then(function (value) {
  12283. // never reached
  12284. }, function (reason) {
  12285. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  12286. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  12287. });
  12288. ```
  12289. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  12290. ```js
  12291. findUser().then(function (user) {
  12292. throw new PedagogicalException('Upstream error');
  12293. }).then(function (value) {
  12294. // never reached
  12295. }).then(function (value) {
  12296. // never reached
  12297. }, function (reason) {
  12298. // The `PedgagocialException` is propagated all the way down to here
  12299. });
  12300. ```
  12301. Assimilation
  12302. ------------
  12303. Sometimes the value you want to propagate to a downstream promise can only be
  12304. retrieved asynchronously. This can be achieved by returning a promise in the
  12305. fulfillment or rejection handler. The downstream promise will then be pending
  12306. until the returned promise is settled. This is called *assimilation*.
  12307. ```js
  12308. findUser().then(function (user) {
  12309. return findCommentsByAuthor(user);
  12310. }).then(function (comments) {
  12311. // The user's comments are now available
  12312. });
  12313. ```
  12314. If the assimliated promise rejects, then the downstream promise will also reject.
  12315. ```js
  12316. findUser().then(function (user) {
  12317. return findCommentsByAuthor(user);
  12318. }).then(function (comments) {
  12319. // If `findCommentsByAuthor` fulfills, we'll have the value here
  12320. }, function (reason) {
  12321. // If `findCommentsByAuthor` rejects, we'll have the reason here
  12322. });
  12323. ```
  12324. Simple Example
  12325. --------------
  12326. Synchronous Example
  12327. ```javascript
  12328. var result;
  12329. try {
  12330. result = findResult();
  12331. // success
  12332. } catch(reason) {
  12333. // failure
  12334. }
  12335. ```
  12336. Errback Example
  12337. ```js
  12338. findResult(function(result, err){
  12339. if (err) {
  12340. // failure
  12341. } else {
  12342. // success
  12343. }
  12344. });
  12345. ```
  12346. Promise Example;
  12347. ```javascript
  12348. findResult().then(function(result){
  12349. // success
  12350. }, function(reason){
  12351. // failure
  12352. });
  12353. ```
  12354. Advanced Example
  12355. --------------
  12356. Synchronous Example
  12357. ```javascript
  12358. var author, books;
  12359. try {
  12360. author = findAuthor();
  12361. books = findBooksByAuthor(author);
  12362. // success
  12363. } catch(reason) {
  12364. // failure
  12365. }
  12366. ```
  12367. Errback Example
  12368. ```js
  12369. function foundBooks(books) {
  12370. }
  12371. function failure(reason) {
  12372. }
  12373. findAuthor(function(author, err){
  12374. if (err) {
  12375. failure(err);
  12376. // failure
  12377. } else {
  12378. try {
  12379. findBoooksByAuthor(author, function(books, err) {
  12380. if (err) {
  12381. failure(err);
  12382. } else {
  12383. try {
  12384. foundBooks(books);
  12385. } catch(reason) {
  12386. failure(reason);
  12387. }
  12388. }
  12389. });
  12390. } catch(error) {
  12391. failure(err);
  12392. }
  12393. // success
  12394. }
  12395. });
  12396. ```
  12397. Promise Example;
  12398. ```javascript
  12399. findAuthor().
  12400. then(findBooksByAuthor).
  12401. then(function(books){
  12402. // found books
  12403. }).catch(function(reason){
  12404. // something went wrong
  12405. });
  12406. ```
  12407. @method then
  12408. @param {Function} onFulfilled
  12409. @param {Function} onRejected
  12410. Useful for tooling.
  12411. @return {Promise}
  12412. */
  12413. then: function(onFulfillment, onRejection) {
  12414. var parent = this;
  12415. var state = parent._state;
  12416. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  12417. return this;
  12418. }
  12419. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  12420. var result = parent._result;
  12421. if (state) {
  12422. var callback = arguments[state - 1];
  12423. lib$es6$promise$asap$$asap(function(){
  12424. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  12425. });
  12426. } else {
  12427. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  12428. }
  12429. return child;
  12430. },
  12431. /**
  12432. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  12433. as the catch block of a try/catch statement.
  12434. ```js
  12435. function findAuthor(){
  12436. throw new Error('couldn't find that author');
  12437. }
  12438. // synchronous
  12439. try {
  12440. findAuthor();
  12441. } catch(reason) {
  12442. // something went wrong
  12443. }
  12444. // async with promises
  12445. findAuthor().catch(function(reason){
  12446. // something went wrong
  12447. });
  12448. ```
  12449. @method catch
  12450. @param {Function} onRejection
  12451. Useful for tooling.
  12452. @return {Promise}
  12453. */
  12454. 'catch': function(onRejection) {
  12455. return this.then(null, onRejection);
  12456. }
  12457. };
  12458. function lib$es6$promise$polyfill$$polyfill() {
  12459. var local;
  12460. if (typeof global !== 'undefined') {
  12461. local = global;
  12462. } else if (typeof self !== 'undefined') {
  12463. local = self;
  12464. } else {
  12465. try {
  12466. local = Function('return this')();
  12467. } catch (e) {
  12468. throw new Error('polyfill failed because global object is unavailable in this environment');
  12469. }
  12470. }
  12471. var P = local.Promise;
  12472. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  12473. return;
  12474. }
  12475. local.Promise = lib$es6$promise$promise$$default;
  12476. }
  12477. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  12478. var lib$es6$promise$umd$$ES6Promise = {
  12479. 'Promise': lib$es6$promise$promise$$default,
  12480. 'polyfill': lib$es6$promise$polyfill$$default
  12481. };
  12482. /* global define:true module:true window: true */
  12483. if (typeof define === 'function' && define['amd']) {
  12484. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  12485. } else if (typeof module !== 'undefined' && module['exports']) {
  12486. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  12487. } else if (typeof this !== 'undefined') {
  12488. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  12489. }
  12490. lib$es6$promise$polyfill$$default();
  12491. }).call(this);
  12492. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12493. },{"_process":44}],46:[function(require,module,exports){
  12494. /* Copyright @ 2015 Atlassian Pty Ltd
  12495. *
  12496. * Licensed under the Apache License, Version 2.0 (the "License");
  12497. * you may not use this file except in compliance with the License.
  12498. * You may obtain a copy of the License at
  12499. *
  12500. * http://www.apache.org/licenses/LICENSE-2.0
  12501. *
  12502. * Unless required by applicable law or agreed to in writing, software
  12503. * distributed under the License is distributed on an "AS IS" BASIS,
  12504. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12505. * See the License for the specific language governing permissions and
  12506. * limitations under the License.
  12507. */
  12508. /**
  12509. * Ordered log levels.
  12510. */
  12511. var levels = {
  12512. "trace": 0,
  12513. "debug": 1,
  12514. "info": 2,
  12515. "log": 3,
  12516. "warn": 4,
  12517. "error": 5
  12518. };
  12519. /**
  12520. * Parses Error's object stack trace and extracts information about the last
  12521. * caller before the log method was called.
  12522. * @returns JS object with info about the caller - method name, file location,
  12523. * line and column.
  12524. */
  12525. function getCallerInfo() {
  12526. var callerInfo = {
  12527. methodName: "",
  12528. fileLocation: "",
  12529. line: null,
  12530. column: null
  12531. };
  12532. //gets the part of the stack without the logger wrappers
  12533. var error = new Error();
  12534. var stack = error.stack? error.stack.split("\n") : [];
  12535. if(!stack || stack.length < 1) {
  12536. return callerInfo;
  12537. }
  12538. var m = null;
  12539. if(stack[3]) {
  12540. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  12541. }
  12542. if(!m || m.length <= 4) {
  12543. //Firefox && Safari
  12544. if(stack[2].indexOf("log@") === 0){
  12545. //Safari
  12546. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  12547. } else {
  12548. //Firefox
  12549. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  12550. }
  12551. return callerInfo;
  12552. }
  12553. callerInfo.methodName = m[1];
  12554. callerInfo.fileLocation = m[2];
  12555. callerInfo.line = m[3];
  12556. callerInfo.column = m[4];
  12557. return callerInfo;
  12558. }
  12559. /**
  12560. * Logs messages using the transports and level from the logger.
  12561. * @param logger a logger instance.
  12562. * @param level the log level of the message. See the levels variable.
  12563. * @param arguments array with arguments that will be logged.
  12564. */
  12565. function log() {
  12566. var logger = arguments[0], level = arguments[1],
  12567. args = Array.prototype.slice.call(arguments, 2);
  12568. if(levels[level] <= logger.level) {
  12569. return;
  12570. }
  12571. var callerInfo = getCallerInfo();
  12572. for(var i = 0; i < logger.transports.length; i++) {
  12573. var t = logger.transports[i];
  12574. var l = t[level];
  12575. if(l && typeof(l) === "function") {
  12576. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  12577. .apply(t, args);
  12578. }
  12579. }
  12580. }
  12581. /**
  12582. *
  12583. * Constructs new logger object.
  12584. * @param level the logging level for the new logger
  12585. * @param id optional identifier for the logger instance.
  12586. * @param transports optional list of handlers(objects) for the logs.
  12587. * The handlers must support - log, warn, error, debug, info, trace.
  12588. * @param format optional (NOT implemented) string.
  12589. */
  12590. function Logger(level, id, transports, format) {
  12591. this.id = id;
  12592. this.format = format;
  12593. if(!this.transports) {
  12594. this.transports = [];
  12595. this.transports.push(Logger.consoleTransport);
  12596. }
  12597. this.level = levels[level];
  12598. var methods = Object.keys(levels);
  12599. for(var i = 0; i < methods.length; i++){
  12600. this[methods[i]] =
  12601. log.bind(null, this, methods[i]);
  12602. }
  12603. }
  12604. /**
  12605. * Sets the log level for the logger.
  12606. * @param level the new log level.
  12607. */
  12608. Logger.prototype.setLevel = function (level) {
  12609. this.level = levels[level];
  12610. };
  12611. module.exports = Logger;
  12612. /**
  12613. * The default transport - console
  12614. */
  12615. Logger.consoleTransport = console;
  12616. /**
  12617. * Enum for the supported log levels.
  12618. */
  12619. Logger.levels = {
  12620. TRACE: "trace",
  12621. DEBUG: "debug",
  12622. INFO: "info",
  12623. LOG: "log",
  12624. WARN: "warn",
  12625. ERROR: "error"
  12626. };
  12627. },{}],47:[function(require,module,exports){
  12628. /* Copyright @ 2015 Atlassian Pty Ltd
  12629. *
  12630. * Licensed under the Apache License, Version 2.0 (the "License");
  12631. * you may not use this file except in compliance with the License.
  12632. * You may obtain a copy of the License at
  12633. *
  12634. * http://www.apache.org/licenses/LICENSE-2.0
  12635. *
  12636. * Unless required by applicable law or agreed to in writing, software
  12637. * distributed under the License is distributed on an "AS IS" BASIS,
  12638. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12639. * See the License for the specific language governing permissions and
  12640. * limitations under the License.
  12641. */
  12642. var Logger = require("./Logger");
  12643. /**
  12644. * Map with the created loggers with ID.
  12645. */
  12646. var idLoggers = {};
  12647. /**
  12648. * Array with the loggers without id.
  12649. */
  12650. var loggers = [];
  12651. /**
  12652. * Log level for the lbrary.
  12653. */
  12654. var curLevel = Logger.levels.TRACE;
  12655. module.exports = {
  12656. /**
  12657. * Creates new logger.
  12658. * @arguments the same as Logger constructor
  12659. */
  12660. getLogger: function(id, transports, format) {
  12661. var logger = new Logger(curLevel, id, transports, format);
  12662. if(id) {
  12663. idLoggers[id] = idLoggers[id] || [];
  12664. idLoggers[id].push(logger);
  12665. } else {
  12666. loggers.push(logger);
  12667. }
  12668. return logger;
  12669. },
  12670. /**
  12671. * Changes the log level for the existing loggers by id.
  12672. * @param level the new log level.
  12673. * @param id if specified the level will be changed only for loggers with the
  12674. * same id. Otherwise the operation will affect all loggers that don't
  12675. * have id.
  12676. */
  12677. setLogLevelById: function(level, id) {
  12678. var l = id? (idLoggers[id] || []) : loggers;
  12679. for(var i = 0; i < l.length; i++) {
  12680. l[i].setLevel(level);
  12681. }
  12682. },
  12683. /**
  12684. * Changes the log level for all existing loggers.
  12685. * @param level the new log level.
  12686. */
  12687. setLogLevel: function (level) {
  12688. curLevel = level;
  12689. var i = 0;
  12690. for(; i < loggers.length; i++) {
  12691. loggers[i].setLevel(level);
  12692. }
  12693. for(var id in idLoggers) {
  12694. var l = idLoggers[id] || [];
  12695. for(i = 0; i < l.length; i++) {
  12696. l[i].setLevel(level);
  12697. }
  12698. }
  12699. },
  12700. /**
  12701. * The supported log levels.
  12702. */
  12703. levels: Logger.levels
  12704. };
  12705. },{"./Logger":46}],48:[function(require,module,exports){
  12706. // Top level file is just a mixin of submodules & constants
  12707. 'use strict';
  12708. var assign = require('./lib/utils/common').assign;
  12709. var deflate = require('./lib/deflate');
  12710. var inflate = require('./lib/inflate');
  12711. var constants = require('./lib/zlib/constants');
  12712. var pako = {};
  12713. assign(pako, deflate, inflate, constants);
  12714. module.exports = pako;
  12715. },{"./lib/deflate":49,"./lib/inflate":50,"./lib/utils/common":51,"./lib/zlib/constants":54}],49:[function(require,module,exports){
  12716. 'use strict';
  12717. var zlib_deflate = require('./zlib/deflate.js');
  12718. var utils = require('./utils/common');
  12719. var strings = require('./utils/strings');
  12720. var msg = require('./zlib/messages');
  12721. var zstream = require('./zlib/zstream');
  12722. var toString = Object.prototype.toString;
  12723. /* Public constants ==========================================================*/
  12724. /* ===========================================================================*/
  12725. var Z_NO_FLUSH = 0;
  12726. var Z_FINISH = 4;
  12727. var Z_OK = 0;
  12728. var Z_STREAM_END = 1;
  12729. var Z_SYNC_FLUSH = 2;
  12730. var Z_DEFAULT_COMPRESSION = -1;
  12731. var Z_DEFAULT_STRATEGY = 0;
  12732. var Z_DEFLATED = 8;
  12733. /* ===========================================================================*/
  12734. /**
  12735. * class Deflate
  12736. *
  12737. * Generic JS-style wrapper for zlib calls. If you don't need
  12738. * streaming behaviour - use more simple functions: [[deflate]],
  12739. * [[deflateRaw]] and [[gzip]].
  12740. **/
  12741. /* internal
  12742. * Deflate.chunks -> Array
  12743. *
  12744. * Chunks of output data, if [[Deflate#onData]] not overriden.
  12745. **/
  12746. /**
  12747. * Deflate.result -> Uint8Array|Array
  12748. *
  12749. * Compressed result, generated by default [[Deflate#onData]]
  12750. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  12751. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  12752. * push a chunk with explicit flush (call [[Deflate#push]] with
  12753. * `Z_SYNC_FLUSH` param).
  12754. **/
  12755. /**
  12756. * Deflate.err -> Number
  12757. *
  12758. * Error code after deflate finished. 0 (Z_OK) on success.
  12759. * You will not need it in real life, because deflate errors
  12760. * are possible only on wrong options or bad `onData` / `onEnd`
  12761. * custom handlers.
  12762. **/
  12763. /**
  12764. * Deflate.msg -> String
  12765. *
  12766. * Error message, if [[Deflate.err]] != 0
  12767. **/
  12768. /**
  12769. * new Deflate(options)
  12770. * - options (Object): zlib deflate options.
  12771. *
  12772. * Creates new deflator instance with specified params. Throws exception
  12773. * on bad params. Supported options:
  12774. *
  12775. * - `level`
  12776. * - `windowBits`
  12777. * - `memLevel`
  12778. * - `strategy`
  12779. *
  12780. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12781. * for more information on these.
  12782. *
  12783. * Additional options, for internal needs:
  12784. *
  12785. * - `chunkSize` - size of generated data chunks (16K by default)
  12786. * - `raw` (Boolean) - do raw deflate
  12787. * - `gzip` (Boolean) - create gzip wrapper
  12788. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12789. * (each char code [0..255])
  12790. * - `header` (Object) - custom header for gzip
  12791. * - `text` (Boolean) - true if compressed data believed to be text
  12792. * - `time` (Number) - modification time, unix timestamp
  12793. * - `os` (Number) - operation system code
  12794. * - `extra` (Array) - array of bytes with extra data (max 65536)
  12795. * - `name` (String) - file name (binary string)
  12796. * - `comment` (String) - comment (binary string)
  12797. * - `hcrc` (Boolean) - true if header crc should be added
  12798. *
  12799. * ##### Example:
  12800. *
  12801. * ```javascript
  12802. * var pako = require('pako')
  12803. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12804. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12805. *
  12806. * var deflate = new pako.Deflate({ level: 3});
  12807. *
  12808. * deflate.push(chunk1, false);
  12809. * deflate.push(chunk2, true); // true -> last chunk
  12810. *
  12811. * if (deflate.err) { throw new Error(deflate.err); }
  12812. *
  12813. * console.log(deflate.result);
  12814. * ```
  12815. **/
  12816. var Deflate = function(options) {
  12817. this.options = utils.assign({
  12818. level: Z_DEFAULT_COMPRESSION,
  12819. method: Z_DEFLATED,
  12820. chunkSize: 16384,
  12821. windowBits: 15,
  12822. memLevel: 8,
  12823. strategy: Z_DEFAULT_STRATEGY,
  12824. to: ''
  12825. }, options || {});
  12826. var opt = this.options;
  12827. if (opt.raw && (opt.windowBits > 0)) {
  12828. opt.windowBits = -opt.windowBits;
  12829. }
  12830. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  12831. opt.windowBits += 16;
  12832. }
  12833. this.err = 0; // error code, if happens (0 = Z_OK)
  12834. this.msg = ''; // error message
  12835. this.ended = false; // used to avoid multiple onEnd() calls
  12836. this.chunks = []; // chunks of compressed data
  12837. this.strm = new zstream();
  12838. this.strm.avail_out = 0;
  12839. var status = zlib_deflate.deflateInit2(
  12840. this.strm,
  12841. opt.level,
  12842. opt.method,
  12843. opt.windowBits,
  12844. opt.memLevel,
  12845. opt.strategy
  12846. );
  12847. if (status !== Z_OK) {
  12848. throw new Error(msg[status]);
  12849. }
  12850. if (opt.header) {
  12851. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  12852. }
  12853. };
  12854. /**
  12855. * Deflate#push(data[, mode]) -> Boolean
  12856. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  12857. * converted to utf8 byte sequence.
  12858. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12859. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12860. *
  12861. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  12862. * new compressed chunks. Returns `true` on success. The last data block must have
  12863. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12864. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12865. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  12866. *
  12867. * On fail call [[Deflate#onEnd]] with error code and return false.
  12868. *
  12869. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12870. * array format is detected automatically). Also, don't skip last param and always
  12871. * use the same type in your code (boolean or number). That will improve JS speed.
  12872. *
  12873. * For regular `Array`-s make sure all elements are [0..255].
  12874. *
  12875. * ##### Example
  12876. *
  12877. * ```javascript
  12878. * push(chunk, false); // push one of data chunks
  12879. * ...
  12880. * push(chunk, true); // push last chunk
  12881. * ```
  12882. **/
  12883. Deflate.prototype.push = function(data, mode) {
  12884. var strm = this.strm;
  12885. var chunkSize = this.options.chunkSize;
  12886. var status, _mode;
  12887. if (this.ended) { return false; }
  12888. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  12889. // Convert data if needed
  12890. if (typeof data === 'string') {
  12891. // If we need to compress text, change encoding to utf8.
  12892. strm.input = strings.string2buf(data);
  12893. } else if (toString.call(data) === '[object ArrayBuffer]') {
  12894. strm.input = new Uint8Array(data);
  12895. } else {
  12896. strm.input = data;
  12897. }
  12898. strm.next_in = 0;
  12899. strm.avail_in = strm.input.length;
  12900. do {
  12901. if (strm.avail_out === 0) {
  12902. strm.output = new utils.Buf8(chunkSize);
  12903. strm.next_out = 0;
  12904. strm.avail_out = chunkSize;
  12905. }
  12906. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  12907. if (status !== Z_STREAM_END && status !== Z_OK) {
  12908. this.onEnd(status);
  12909. this.ended = true;
  12910. return false;
  12911. }
  12912. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  12913. if (this.options.to === 'string') {
  12914. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  12915. } else {
  12916. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  12917. }
  12918. }
  12919. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  12920. // Finalize on the last chunk.
  12921. if (_mode === Z_FINISH) {
  12922. status = zlib_deflate.deflateEnd(this.strm);
  12923. this.onEnd(status);
  12924. this.ended = true;
  12925. return status === Z_OK;
  12926. }
  12927. // callback interim results if Z_SYNC_FLUSH.
  12928. if (_mode === Z_SYNC_FLUSH) {
  12929. this.onEnd(Z_OK);
  12930. strm.avail_out = 0;
  12931. return true;
  12932. }
  12933. return true;
  12934. };
  12935. /**
  12936. * Deflate#onData(chunk) -> Void
  12937. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  12938. * on js engine support. When string output requested, each chunk
  12939. * will be string.
  12940. *
  12941. * By default, stores data blocks in `chunks[]` property and glue
  12942. * those in `onEnd`. Override this handler, if you need another behaviour.
  12943. **/
  12944. Deflate.prototype.onData = function(chunk) {
  12945. this.chunks.push(chunk);
  12946. };
  12947. /**
  12948. * Deflate#onEnd(status) -> Void
  12949. * - status (Number): deflate status. 0 (Z_OK) on success,
  12950. * other if not.
  12951. *
  12952. * Called once after you tell deflate that the input stream is
  12953. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  12954. * or if an error happened. By default - join collected chunks,
  12955. * free memory and fill `results` / `err` properties.
  12956. **/
  12957. Deflate.prototype.onEnd = function(status) {
  12958. // On success - join
  12959. if (status === Z_OK) {
  12960. if (this.options.to === 'string') {
  12961. this.result = this.chunks.join('');
  12962. } else {
  12963. this.result = utils.flattenChunks(this.chunks);
  12964. }
  12965. }
  12966. this.chunks = [];
  12967. this.err = status;
  12968. this.msg = this.strm.msg;
  12969. };
  12970. /**
  12971. * deflate(data[, options]) -> Uint8Array|Array|String
  12972. * - data (Uint8Array|Array|String): input data to compress.
  12973. * - options (Object): zlib deflate options.
  12974. *
  12975. * Compress `data` with deflate alrorythm and `options`.
  12976. *
  12977. * Supported options are:
  12978. *
  12979. * - level
  12980. * - windowBits
  12981. * - memLevel
  12982. * - strategy
  12983. *
  12984. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12985. * for more information on these.
  12986. *
  12987. * Sugar (options):
  12988. *
  12989. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  12990. * negative windowBits implicitly.
  12991. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12992. * (each char code [0..255])
  12993. *
  12994. * ##### Example:
  12995. *
  12996. * ```javascript
  12997. * var pako = require('pako')
  12998. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  12999. *
  13000. * console.log(pako.deflate(data));
  13001. * ```
  13002. **/
  13003. function deflate(input, options) {
  13004. var deflator = new Deflate(options);
  13005. deflator.push(input, true);
  13006. // That will never happens, if you don't cheat with options :)
  13007. if (deflator.err) { throw deflator.msg; }
  13008. return deflator.result;
  13009. }
  13010. /**
  13011. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  13012. * - data (Uint8Array|Array|String): input data to compress.
  13013. * - options (Object): zlib deflate options.
  13014. *
  13015. * The same as [[deflate]], but creates raw data, without wrapper
  13016. * (header and adler32 crc).
  13017. **/
  13018. function deflateRaw(input, options) {
  13019. options = options || {};
  13020. options.raw = true;
  13021. return deflate(input, options);
  13022. }
  13023. /**
  13024. * gzip(data[, options]) -> Uint8Array|Array|String
  13025. * - data (Uint8Array|Array|String): input data to compress.
  13026. * - options (Object): zlib deflate options.
  13027. *
  13028. * The same as [[deflate]], but create gzip wrapper instead of
  13029. * deflate one.
  13030. **/
  13031. function gzip(input, options) {
  13032. options = options || {};
  13033. options.gzip = true;
  13034. return deflate(input, options);
  13035. }
  13036. exports.Deflate = Deflate;
  13037. exports.deflate = deflate;
  13038. exports.deflateRaw = deflateRaw;
  13039. exports.gzip = gzip;
  13040. },{"./utils/common":51,"./utils/strings":52,"./zlib/deflate.js":56,"./zlib/messages":61,"./zlib/zstream":63}],50:[function(require,module,exports){
  13041. 'use strict';
  13042. var zlib_inflate = require('./zlib/inflate.js');
  13043. var utils = require('./utils/common');
  13044. var strings = require('./utils/strings');
  13045. var c = require('./zlib/constants');
  13046. var msg = require('./zlib/messages');
  13047. var zstream = require('./zlib/zstream');
  13048. var gzheader = require('./zlib/gzheader');
  13049. var toString = Object.prototype.toString;
  13050. /**
  13051. * class Inflate
  13052. *
  13053. * Generic JS-style wrapper for zlib calls. If you don't need
  13054. * streaming behaviour - use more simple functions: [[inflate]]
  13055. * and [[inflateRaw]].
  13056. **/
  13057. /* internal
  13058. * inflate.chunks -> Array
  13059. *
  13060. * Chunks of output data, if [[Inflate#onData]] not overriden.
  13061. **/
  13062. /**
  13063. * Inflate.result -> Uint8Array|Array|String
  13064. *
  13065. * Uncompressed result, generated by default [[Inflate#onData]]
  13066. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13067. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13068. * push a chunk with explicit flush (call [[Inflate#push]] with
  13069. * `Z_SYNC_FLUSH` param).
  13070. **/
  13071. /**
  13072. * Inflate.err -> Number
  13073. *
  13074. * Error code after inflate finished. 0 (Z_OK) on success.
  13075. * Should be checked if broken data possible.
  13076. **/
  13077. /**
  13078. * Inflate.msg -> String
  13079. *
  13080. * Error message, if [[Inflate.err]] != 0
  13081. **/
  13082. /**
  13083. * new Inflate(options)
  13084. * - options (Object): zlib inflate options.
  13085. *
  13086. * Creates new inflator instance with specified params. Throws exception
  13087. * on bad params. Supported options:
  13088. *
  13089. * - `windowBits`
  13090. *
  13091. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13092. * for more information on these.
  13093. *
  13094. * Additional options, for internal needs:
  13095. *
  13096. * - `chunkSize` - size of generated data chunks (16K by default)
  13097. * - `raw` (Boolean) - do raw inflate
  13098. * - `to` (String) - if equal to 'string', then result will be converted
  13099. * from utf8 to utf16 (javascript) string. When string output requested,
  13100. * chunk length can differ from `chunkSize`, depending on content.
  13101. *
  13102. * By default, when no options set, autodetect deflate/gzip data format via
  13103. * wrapper header.
  13104. *
  13105. * ##### Example:
  13106. *
  13107. * ```javascript
  13108. * var pako = require('pako')
  13109. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13110. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13111. *
  13112. * var inflate = new pako.Inflate({ level: 3});
  13113. *
  13114. * inflate.push(chunk1, false);
  13115. * inflate.push(chunk2, true); // true -> last chunk
  13116. *
  13117. * if (inflate.err) { throw new Error(inflate.err); }
  13118. *
  13119. * console.log(inflate.result);
  13120. * ```
  13121. **/
  13122. var Inflate = function(options) {
  13123. this.options = utils.assign({
  13124. chunkSize: 16384,
  13125. windowBits: 0,
  13126. to: ''
  13127. }, options || {});
  13128. var opt = this.options;
  13129. // Force window size for `raw` data, if not set directly,
  13130. // because we have no header for autodetect.
  13131. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  13132. opt.windowBits = -opt.windowBits;
  13133. if (opt.windowBits === 0) { opt.windowBits = -15; }
  13134. }
  13135. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  13136. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  13137. !(options && options.windowBits)) {
  13138. opt.windowBits += 32;
  13139. }
  13140. // Gzip header has no info about windows size, we can do autodetect only
  13141. // for deflate. So, if window size not set, force it to max when gzip possible
  13142. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  13143. // bit 3 (16) -> gzipped data
  13144. // bit 4 (32) -> autodetect gzip/deflate
  13145. if ((opt.windowBits & 15) === 0) {
  13146. opt.windowBits |= 15;
  13147. }
  13148. }
  13149. this.err = 0; // error code, if happens (0 = Z_OK)
  13150. this.msg = ''; // error message
  13151. this.ended = false; // used to avoid multiple onEnd() calls
  13152. this.chunks = []; // chunks of compressed data
  13153. this.strm = new zstream();
  13154. this.strm.avail_out = 0;
  13155. var status = zlib_inflate.inflateInit2(
  13156. this.strm,
  13157. opt.windowBits
  13158. );
  13159. if (status !== c.Z_OK) {
  13160. throw new Error(msg[status]);
  13161. }
  13162. this.header = new gzheader();
  13163. zlib_inflate.inflateGetHeader(this.strm, this.header);
  13164. };
  13165. /**
  13166. * Inflate#push(data[, mode]) -> Boolean
  13167. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  13168. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13169. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  13170. *
  13171. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  13172. * new output chunks. Returns `true` on success. The last data block must have
  13173. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13174. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13175. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13176. *
  13177. * On fail call [[Inflate#onEnd]] with error code and return false.
  13178. *
  13179. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13180. * format is detected automatically). Also, don't skip last param and always
  13181. * use the same type in your code (boolean or number). That will improve JS speed.
  13182. *
  13183. * For regular `Array`-s make sure all elements are [0..255].
  13184. *
  13185. * ##### Example
  13186. *
  13187. * ```javascript
  13188. * push(chunk, false); // push one of data chunks
  13189. * ...
  13190. * push(chunk, true); // push last chunk
  13191. * ```
  13192. **/
  13193. Inflate.prototype.push = function(data, mode) {
  13194. var strm = this.strm;
  13195. var chunkSize = this.options.chunkSize;
  13196. var status, _mode;
  13197. var next_out_utf8, tail, utf8str;
  13198. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13199. // when we check that all output data was flushed.
  13200. var allowBufError = false;
  13201. if (this.ended) { return false; }
  13202. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13203. // Convert data if needed
  13204. if (typeof data === 'string') {
  13205. // Only binary strings can be decompressed on practice
  13206. strm.input = strings.binstring2buf(data);
  13207. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13208. strm.input = new Uint8Array(data);
  13209. } else {
  13210. strm.input = data;
  13211. }
  13212. strm.next_in = 0;
  13213. strm.avail_in = strm.input.length;
  13214. do {
  13215. if (strm.avail_out === 0) {
  13216. strm.output = new utils.Buf8(chunkSize);
  13217. strm.next_out = 0;
  13218. strm.avail_out = chunkSize;
  13219. }
  13220. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13221. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13222. status = c.Z_OK;
  13223. allowBufError = false;
  13224. }
  13225. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13226. this.onEnd(status);
  13227. this.ended = true;
  13228. return false;
  13229. }
  13230. if (strm.next_out) {
  13231. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13232. if (this.options.to === 'string') {
  13233. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13234. tail = strm.next_out - next_out_utf8;
  13235. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13236. // move tail
  13237. strm.next_out = tail;
  13238. strm.avail_out = chunkSize - tail;
  13239. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13240. this.onData(utf8str);
  13241. } else {
  13242. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13243. }
  13244. }
  13245. }
  13246. // When no more input data, we should check that internal inflate buffers
  13247. // are flushed. The only way to do it when avail_out = 0 - run one more
  13248. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13249. // Here we set flag to process this error properly.
  13250. //
  13251. // NOTE. Deflate does not return error in this case and does not needs such
  13252. // logic.
  13253. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13254. allowBufError = true;
  13255. }
  13256. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13257. if (status === c.Z_STREAM_END) {
  13258. _mode = c.Z_FINISH;
  13259. }
  13260. // Finalize on the last chunk.
  13261. if (_mode === c.Z_FINISH) {
  13262. status = zlib_inflate.inflateEnd(this.strm);
  13263. this.onEnd(status);
  13264. this.ended = true;
  13265. return status === c.Z_OK;
  13266. }
  13267. // callback interim results if Z_SYNC_FLUSH.
  13268. if (_mode === c.Z_SYNC_FLUSH) {
  13269. this.onEnd(c.Z_OK);
  13270. strm.avail_out = 0;
  13271. return true;
  13272. }
  13273. return true;
  13274. };
  13275. /**
  13276. * Inflate#onData(chunk) -> Void
  13277. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13278. * on js engine support. When string output requested, each chunk
  13279. * will be string.
  13280. *
  13281. * By default, stores data blocks in `chunks[]` property and glue
  13282. * those in `onEnd`. Override this handler, if you need another behaviour.
  13283. **/
  13284. Inflate.prototype.onData = function(chunk) {
  13285. this.chunks.push(chunk);
  13286. };
  13287. /**
  13288. * Inflate#onEnd(status) -> Void
  13289. * - status (Number): inflate status. 0 (Z_OK) on success,
  13290. * other if not.
  13291. *
  13292. * Called either after you tell inflate that the input stream is
  13293. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13294. * or if an error happened. By default - join collected chunks,
  13295. * free memory and fill `results` / `err` properties.
  13296. **/
  13297. Inflate.prototype.onEnd = function(status) {
  13298. // On success - join
  13299. if (status === c.Z_OK) {
  13300. if (this.options.to === 'string') {
  13301. // Glue & convert here, until we teach pako to send
  13302. // utf8 alligned strings to onData
  13303. this.result = this.chunks.join('');
  13304. } else {
  13305. this.result = utils.flattenChunks(this.chunks);
  13306. }
  13307. }
  13308. this.chunks = [];
  13309. this.err = status;
  13310. this.msg = this.strm.msg;
  13311. };
  13312. /**
  13313. * inflate(data[, options]) -> Uint8Array|Array|String
  13314. * - data (Uint8Array|Array|String): input data to decompress.
  13315. * - options (Object): zlib inflate options.
  13316. *
  13317. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  13318. * format via wrapper header by default. That's why we don't provide
  13319. * separate `ungzip` method.
  13320. *
  13321. * Supported options are:
  13322. *
  13323. * - windowBits
  13324. *
  13325. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13326. * for more information.
  13327. *
  13328. * Sugar (options):
  13329. *
  13330. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13331. * negative windowBits implicitly.
  13332. * - `to` (String) - if equal to 'string', then result will be converted
  13333. * from utf8 to utf16 (javascript) string. When string output requested,
  13334. * chunk length can differ from `chunkSize`, depending on content.
  13335. *
  13336. *
  13337. * ##### Example:
  13338. *
  13339. * ```javascript
  13340. * var pako = require('pako')
  13341. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  13342. * , output;
  13343. *
  13344. * try {
  13345. * output = pako.inflate(input);
  13346. * } catch (err)
  13347. * console.log(err);
  13348. * }
  13349. * ```
  13350. **/
  13351. function inflate(input, options) {
  13352. var inflator = new Inflate(options);
  13353. inflator.push(input, true);
  13354. // That will never happens, if you don't cheat with options :)
  13355. if (inflator.err) { throw inflator.msg; }
  13356. return inflator.result;
  13357. }
  13358. /**
  13359. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  13360. * - data (Uint8Array|Array|String): input data to decompress.
  13361. * - options (Object): zlib inflate options.
  13362. *
  13363. * The same as [[inflate]], but creates raw data, without wrapper
  13364. * (header and adler32 crc).
  13365. **/
  13366. function inflateRaw(input, options) {
  13367. options = options || {};
  13368. options.raw = true;
  13369. return inflate(input, options);
  13370. }
  13371. /**
  13372. * ungzip(data[, options]) -> Uint8Array|Array|String
  13373. * - data (Uint8Array|Array|String): input data to decompress.
  13374. * - options (Object): zlib inflate options.
  13375. *
  13376. * Just shortcut to [[inflate]], because it autodetects format
  13377. * by header.content. Done for convenience.
  13378. **/
  13379. exports.Inflate = Inflate;
  13380. exports.inflate = inflate;
  13381. exports.inflateRaw = inflateRaw;
  13382. exports.ungzip = inflate;
  13383. },{"./utils/common":51,"./utils/strings":52,"./zlib/constants":54,"./zlib/gzheader":57,"./zlib/inflate.js":59,"./zlib/messages":61,"./zlib/zstream":63}],51:[function(require,module,exports){
  13384. 'use strict';
  13385. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  13386. (typeof Uint16Array !== 'undefined') &&
  13387. (typeof Int32Array !== 'undefined');
  13388. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  13389. var sources = Array.prototype.slice.call(arguments, 1);
  13390. while (sources.length) {
  13391. var source = sources.shift();
  13392. if (!source) { continue; }
  13393. if (typeof source !== 'object') {
  13394. throw new TypeError(source + 'must be non-object');
  13395. }
  13396. for (var p in source) {
  13397. if (source.hasOwnProperty(p)) {
  13398. obj[p] = source[p];
  13399. }
  13400. }
  13401. }
  13402. return obj;
  13403. };
  13404. // reduce buffer size, avoiding mem copy
  13405. exports.shrinkBuf = function (buf, size) {
  13406. if (buf.length === size) { return buf; }
  13407. if (buf.subarray) { return buf.subarray(0, size); }
  13408. buf.length = size;
  13409. return buf;
  13410. };
  13411. var fnTyped = {
  13412. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13413. if (src.subarray && dest.subarray) {
  13414. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  13415. return;
  13416. }
  13417. // Fallback to ordinary array
  13418. for (var i=0; i<len; i++) {
  13419. dest[dest_offs + i] = src[src_offs + i];
  13420. }
  13421. },
  13422. // Join array of chunks to single array.
  13423. flattenChunks: function(chunks) {
  13424. var i, l, len, pos, chunk, result;
  13425. // calculate data length
  13426. len = 0;
  13427. for (i=0, l=chunks.length; i<l; i++) {
  13428. len += chunks[i].length;
  13429. }
  13430. // join chunks
  13431. result = new Uint8Array(len);
  13432. pos = 0;
  13433. for (i=0, l=chunks.length; i<l; i++) {
  13434. chunk = chunks[i];
  13435. result.set(chunk, pos);
  13436. pos += chunk.length;
  13437. }
  13438. return result;
  13439. }
  13440. };
  13441. var fnUntyped = {
  13442. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13443. for (var i=0; i<len; i++) {
  13444. dest[dest_offs + i] = src[src_offs + i];
  13445. }
  13446. },
  13447. // Join array of chunks to single array.
  13448. flattenChunks: function(chunks) {
  13449. return [].concat.apply([], chunks);
  13450. }
  13451. };
  13452. // Enable/Disable typed arrays use, for testing
  13453. //
  13454. exports.setTyped = function (on) {
  13455. if (on) {
  13456. exports.Buf8 = Uint8Array;
  13457. exports.Buf16 = Uint16Array;
  13458. exports.Buf32 = Int32Array;
  13459. exports.assign(exports, fnTyped);
  13460. } else {
  13461. exports.Buf8 = Array;
  13462. exports.Buf16 = Array;
  13463. exports.Buf32 = Array;
  13464. exports.assign(exports, fnUntyped);
  13465. }
  13466. };
  13467. exports.setTyped(TYPED_OK);
  13468. },{}],52:[function(require,module,exports){
  13469. // String encode/decode helpers
  13470. 'use strict';
  13471. var utils = require('./common');
  13472. // Quick check if we can use fast array to bin string conversion
  13473. //
  13474. // - apply(Array) can fail on Android 2.2
  13475. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  13476. //
  13477. var STR_APPLY_OK = true;
  13478. var STR_APPLY_UIA_OK = true;
  13479. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  13480. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  13481. // Table with utf8 lengths (calculated by first byte of sequence)
  13482. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13483. // because max possible codepoint is 0x10ffff
  13484. var _utf8len = new utils.Buf8(256);
  13485. for (var q=0; q<256; q++) {
  13486. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  13487. }
  13488. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  13489. // convert string to array (typed, when possible)
  13490. exports.string2buf = function (str) {
  13491. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13492. // count binary size
  13493. for (m_pos = 0; m_pos < str_len; m_pos++) {
  13494. c = str.charCodeAt(m_pos);
  13495. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13496. c2 = str.charCodeAt(m_pos+1);
  13497. if ((c2 & 0xfc00) === 0xdc00) {
  13498. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13499. m_pos++;
  13500. }
  13501. }
  13502. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  13503. }
  13504. // allocate buffer
  13505. buf = new utils.Buf8(buf_len);
  13506. // convert
  13507. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  13508. c = str.charCodeAt(m_pos);
  13509. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13510. c2 = str.charCodeAt(m_pos+1);
  13511. if ((c2 & 0xfc00) === 0xdc00) {
  13512. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13513. m_pos++;
  13514. }
  13515. }
  13516. if (c < 0x80) {
  13517. /* one byte */
  13518. buf[i++] = c;
  13519. } else if (c < 0x800) {
  13520. /* two bytes */
  13521. buf[i++] = 0xC0 | (c >>> 6);
  13522. buf[i++] = 0x80 | (c & 0x3f);
  13523. } else if (c < 0x10000) {
  13524. /* three bytes */
  13525. buf[i++] = 0xE0 | (c >>> 12);
  13526. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13527. buf[i++] = 0x80 | (c & 0x3f);
  13528. } else {
  13529. /* four bytes */
  13530. buf[i++] = 0xf0 | (c >>> 18);
  13531. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  13532. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13533. buf[i++] = 0x80 | (c & 0x3f);
  13534. }
  13535. }
  13536. return buf;
  13537. };
  13538. // Helper (used in 2 places)
  13539. function buf2binstring(buf, len) {
  13540. // use fallback for big arrays to avoid stack overflow
  13541. if (len < 65537) {
  13542. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  13543. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  13544. }
  13545. }
  13546. var result = '';
  13547. for (var i=0; i < len; i++) {
  13548. result += String.fromCharCode(buf[i]);
  13549. }
  13550. return result;
  13551. }
  13552. // Convert byte array to binary string
  13553. exports.buf2binstring = function(buf) {
  13554. return buf2binstring(buf, buf.length);
  13555. };
  13556. // Convert binary string (typed, when possible)
  13557. exports.binstring2buf = function(str) {
  13558. var buf = new utils.Buf8(str.length);
  13559. for (var i=0, len=buf.length; i < len; i++) {
  13560. buf[i] = str.charCodeAt(i);
  13561. }
  13562. return buf;
  13563. };
  13564. // convert array to string
  13565. exports.buf2string = function (buf, max) {
  13566. var i, out, c, c_len;
  13567. var len = max || buf.length;
  13568. // Reserve max possible length (2 words per char)
  13569. // NB: by unknown reasons, Array is significantly faster for
  13570. // String.fromCharCode.apply than Uint16Array.
  13571. var utf16buf = new Array(len*2);
  13572. for (out=0, i=0; i<len;) {
  13573. c = buf[i++];
  13574. // quick process ascii
  13575. if (c < 0x80) { utf16buf[out++] = c; continue; }
  13576. c_len = _utf8len[c];
  13577. // skip 5 & 6 byte codes
  13578. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  13579. // apply mask on first byte
  13580. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  13581. // join the rest
  13582. while (c_len > 1 && i < len) {
  13583. c = (c << 6) | (buf[i++] & 0x3f);
  13584. c_len--;
  13585. }
  13586. // terminated by end of string?
  13587. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  13588. if (c < 0x10000) {
  13589. utf16buf[out++] = c;
  13590. } else {
  13591. c -= 0x10000;
  13592. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  13593. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  13594. }
  13595. }
  13596. return buf2binstring(utf16buf, out);
  13597. };
  13598. // Calculate max possible position in utf8 buffer,
  13599. // that will not break sequence. If that's not possible
  13600. // - (very small limits) return max size as is.
  13601. //
  13602. // buf[] - utf8 bytes array
  13603. // max - length limit (mandatory);
  13604. exports.utf8border = function(buf, max) {
  13605. var pos;
  13606. max = max || buf.length;
  13607. if (max > buf.length) { max = buf.length; }
  13608. // go back from last position, until start of sequence found
  13609. pos = max-1;
  13610. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  13611. // Fuckup - very small and broken sequence,
  13612. // return max, because we should return something anyway.
  13613. if (pos < 0) { return max; }
  13614. // If we came to start of buffer - that means vuffer is too small,
  13615. // return max too.
  13616. if (pos === 0) { return max; }
  13617. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  13618. };
  13619. },{"./common":51}],53:[function(require,module,exports){
  13620. 'use strict';
  13621. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  13622. // It doesn't worth to make additional optimizationa as in original.
  13623. // Small size is preferable.
  13624. function adler32(adler, buf, len, pos) {
  13625. var s1 = (adler & 0xffff) |0,
  13626. s2 = ((adler >>> 16) & 0xffff) |0,
  13627. n = 0;
  13628. while (len !== 0) {
  13629. // Set limit ~ twice less than 5552, to keep
  13630. // s2 in 31-bits, because we force signed ints.
  13631. // in other case %= will fail.
  13632. n = len > 2000 ? 2000 : len;
  13633. len -= n;
  13634. do {
  13635. s1 = (s1 + buf[pos++]) |0;
  13636. s2 = (s2 + s1) |0;
  13637. } while (--n);
  13638. s1 %= 65521;
  13639. s2 %= 65521;
  13640. }
  13641. return (s1 | (s2 << 16)) |0;
  13642. }
  13643. module.exports = adler32;
  13644. },{}],54:[function(require,module,exports){
  13645. module.exports = {
  13646. /* Allowed flush values; see deflate() and inflate() below for details */
  13647. Z_NO_FLUSH: 0,
  13648. Z_PARTIAL_FLUSH: 1,
  13649. Z_SYNC_FLUSH: 2,
  13650. Z_FULL_FLUSH: 3,
  13651. Z_FINISH: 4,
  13652. Z_BLOCK: 5,
  13653. Z_TREES: 6,
  13654. /* Return codes for the compression/decompression functions. Negative values
  13655. * are errors, positive values are used for special but normal events.
  13656. */
  13657. Z_OK: 0,
  13658. Z_STREAM_END: 1,
  13659. Z_NEED_DICT: 2,
  13660. Z_ERRNO: -1,
  13661. Z_STREAM_ERROR: -2,
  13662. Z_DATA_ERROR: -3,
  13663. //Z_MEM_ERROR: -4,
  13664. Z_BUF_ERROR: -5,
  13665. //Z_VERSION_ERROR: -6,
  13666. /* compression levels */
  13667. Z_NO_COMPRESSION: 0,
  13668. Z_BEST_SPEED: 1,
  13669. Z_BEST_COMPRESSION: 9,
  13670. Z_DEFAULT_COMPRESSION: -1,
  13671. Z_FILTERED: 1,
  13672. Z_HUFFMAN_ONLY: 2,
  13673. Z_RLE: 3,
  13674. Z_FIXED: 4,
  13675. Z_DEFAULT_STRATEGY: 0,
  13676. /* Possible values of the data_type field (though see inflate()) */
  13677. Z_BINARY: 0,
  13678. Z_TEXT: 1,
  13679. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  13680. Z_UNKNOWN: 2,
  13681. /* The deflate compression method */
  13682. Z_DEFLATED: 8
  13683. //Z_NULL: null // Use -1 or null inline, depending on var type
  13684. };
  13685. },{}],55:[function(require,module,exports){
  13686. 'use strict';
  13687. // Note: we can't get significant speed boost here.
  13688. // So write code to minimize size - no pregenerated tables
  13689. // and array tools dependencies.
  13690. // Use ordinary array, since untyped makes no boost here
  13691. function makeTable() {
  13692. var c, table = [];
  13693. for (var n =0; n < 256; n++) {
  13694. c = n;
  13695. for (var k =0; k < 8; k++) {
  13696. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  13697. }
  13698. table[n] = c;
  13699. }
  13700. return table;
  13701. }
  13702. // Create table on load. Just 255 signed longs. Not a problem.
  13703. var crcTable = makeTable();
  13704. function crc32(crc, buf, len, pos) {
  13705. var t = crcTable,
  13706. end = pos + len;
  13707. crc = crc ^ (-1);
  13708. for (var i = pos; i < end; i++) {
  13709. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  13710. }
  13711. return (crc ^ (-1)); // >>> 0;
  13712. }
  13713. module.exports = crc32;
  13714. },{}],56:[function(require,module,exports){
  13715. 'use strict';
  13716. var utils = require('../utils/common');
  13717. var trees = require('./trees');
  13718. var adler32 = require('./adler32');
  13719. var crc32 = require('./crc32');
  13720. var msg = require('./messages');
  13721. /* Public constants ==========================================================*/
  13722. /* ===========================================================================*/
  13723. /* Allowed flush values; see deflate() and inflate() below for details */
  13724. var Z_NO_FLUSH = 0;
  13725. var Z_PARTIAL_FLUSH = 1;
  13726. //var Z_SYNC_FLUSH = 2;
  13727. var Z_FULL_FLUSH = 3;
  13728. var Z_FINISH = 4;
  13729. var Z_BLOCK = 5;
  13730. //var Z_TREES = 6;
  13731. /* Return codes for the compression/decompression functions. Negative values
  13732. * are errors, positive values are used for special but normal events.
  13733. */
  13734. var Z_OK = 0;
  13735. var Z_STREAM_END = 1;
  13736. //var Z_NEED_DICT = 2;
  13737. //var Z_ERRNO = -1;
  13738. var Z_STREAM_ERROR = -2;
  13739. var Z_DATA_ERROR = -3;
  13740. //var Z_MEM_ERROR = -4;
  13741. var Z_BUF_ERROR = -5;
  13742. //var Z_VERSION_ERROR = -6;
  13743. /* compression levels */
  13744. //var Z_NO_COMPRESSION = 0;
  13745. //var Z_BEST_SPEED = 1;
  13746. //var Z_BEST_COMPRESSION = 9;
  13747. var Z_DEFAULT_COMPRESSION = -1;
  13748. var Z_FILTERED = 1;
  13749. var Z_HUFFMAN_ONLY = 2;
  13750. var Z_RLE = 3;
  13751. var Z_FIXED = 4;
  13752. var Z_DEFAULT_STRATEGY = 0;
  13753. /* Possible values of the data_type field (though see inflate()) */
  13754. //var Z_BINARY = 0;
  13755. //var Z_TEXT = 1;
  13756. //var Z_ASCII = 1; // = Z_TEXT
  13757. var Z_UNKNOWN = 2;
  13758. /* The deflate compression method */
  13759. var Z_DEFLATED = 8;
  13760. /*============================================================================*/
  13761. var MAX_MEM_LEVEL = 9;
  13762. /* Maximum value for memLevel in deflateInit2 */
  13763. var MAX_WBITS = 15;
  13764. /* 32K LZ77 window */
  13765. var DEF_MEM_LEVEL = 8;
  13766. var LENGTH_CODES = 29;
  13767. /* number of length codes, not counting the special END_BLOCK code */
  13768. var LITERALS = 256;
  13769. /* number of literal bytes 0..255 */
  13770. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  13771. /* number of Literal or Length codes, including the END_BLOCK code */
  13772. var D_CODES = 30;
  13773. /* number of distance codes */
  13774. var BL_CODES = 19;
  13775. /* number of codes used to transfer the bit lengths */
  13776. var HEAP_SIZE = 2*L_CODES + 1;
  13777. /* maximum heap size */
  13778. var MAX_BITS = 15;
  13779. /* All codes must not exceed MAX_BITS bits */
  13780. var MIN_MATCH = 3;
  13781. var MAX_MATCH = 258;
  13782. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  13783. var PRESET_DICT = 0x20;
  13784. var INIT_STATE = 42;
  13785. var EXTRA_STATE = 69;
  13786. var NAME_STATE = 73;
  13787. var COMMENT_STATE = 91;
  13788. var HCRC_STATE = 103;
  13789. var BUSY_STATE = 113;
  13790. var FINISH_STATE = 666;
  13791. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  13792. var BS_BLOCK_DONE = 2; /* block flush performed */
  13793. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  13794. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  13795. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  13796. function err(strm, errorCode) {
  13797. strm.msg = msg[errorCode];
  13798. return errorCode;
  13799. }
  13800. function rank(f) {
  13801. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  13802. }
  13803. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  13804. /* =========================================================================
  13805. * Flush as much pending output as possible. All deflate() output goes
  13806. * through this function so some applications may wish to modify it
  13807. * to avoid allocating a large strm->output buffer and copying into it.
  13808. * (See also read_buf()).
  13809. */
  13810. function flush_pending(strm) {
  13811. var s = strm.state;
  13812. //_tr_flush_bits(s);
  13813. var len = s.pending;
  13814. if (len > strm.avail_out) {
  13815. len = strm.avail_out;
  13816. }
  13817. if (len === 0) { return; }
  13818. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  13819. strm.next_out += len;
  13820. s.pending_out += len;
  13821. strm.total_out += len;
  13822. strm.avail_out -= len;
  13823. s.pending -= len;
  13824. if (s.pending === 0) {
  13825. s.pending_out = 0;
  13826. }
  13827. }
  13828. function flush_block_only (s, last) {
  13829. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  13830. s.block_start = s.strstart;
  13831. flush_pending(s.strm);
  13832. }
  13833. function put_byte(s, b) {
  13834. s.pending_buf[s.pending++] = b;
  13835. }
  13836. /* =========================================================================
  13837. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  13838. * IN assertion: the stream state is correct and there is enough room in
  13839. * pending_buf.
  13840. */
  13841. function putShortMSB(s, b) {
  13842. // put_byte(s, (Byte)(b >> 8));
  13843. // put_byte(s, (Byte)(b & 0xff));
  13844. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  13845. s.pending_buf[s.pending++] = b & 0xff;
  13846. }
  13847. /* ===========================================================================
  13848. * Read a new buffer from the current input stream, update the adler32
  13849. * and total number of bytes read. All deflate() input goes through
  13850. * this function so some applications may wish to modify it to avoid
  13851. * allocating a large strm->input buffer and copying from it.
  13852. * (See also flush_pending()).
  13853. */
  13854. function read_buf(strm, buf, start, size) {
  13855. var len = strm.avail_in;
  13856. if (len > size) { len = size; }
  13857. if (len === 0) { return 0; }
  13858. strm.avail_in -= len;
  13859. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  13860. if (strm.state.wrap === 1) {
  13861. strm.adler = adler32(strm.adler, buf, len, start);
  13862. }
  13863. else if (strm.state.wrap === 2) {
  13864. strm.adler = crc32(strm.adler, buf, len, start);
  13865. }
  13866. strm.next_in += len;
  13867. strm.total_in += len;
  13868. return len;
  13869. }
  13870. /* ===========================================================================
  13871. * Set match_start to the longest match starting at the given string and
  13872. * return its length. Matches shorter or equal to prev_length are discarded,
  13873. * in which case the result is equal to prev_length and match_start is
  13874. * garbage.
  13875. * IN assertions: cur_match is the head of the hash chain for the current
  13876. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  13877. * OUT assertion: the match length is not greater than s->lookahead.
  13878. */
  13879. function longest_match(s, cur_match) {
  13880. var chain_length = s.max_chain_length; /* max hash chain length */
  13881. var scan = s.strstart; /* current string */
  13882. var match; /* matched string */
  13883. var len; /* length of current match */
  13884. var best_len = s.prev_length; /* best match length so far */
  13885. var nice_match = s.nice_match; /* stop if match long enough */
  13886. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  13887. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  13888. var _win = s.window; // shortcut
  13889. var wmask = s.w_mask;
  13890. var prev = s.prev;
  13891. /* Stop when cur_match becomes <= limit. To simplify the code,
  13892. * we prevent matches with the string of window index 0.
  13893. */
  13894. var strend = s.strstart + MAX_MATCH;
  13895. var scan_end1 = _win[scan + best_len - 1];
  13896. var scan_end = _win[scan + best_len];
  13897. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  13898. * It is easy to get rid of this optimization if necessary.
  13899. */
  13900. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  13901. /* Do not waste too much time if we already have a good match: */
  13902. if (s.prev_length >= s.good_match) {
  13903. chain_length >>= 2;
  13904. }
  13905. /* Do not look for matches beyond the end of the input. This is necessary
  13906. * to make deflate deterministic.
  13907. */
  13908. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  13909. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  13910. do {
  13911. // Assert(cur_match < s->strstart, "no future");
  13912. match = cur_match;
  13913. /* Skip to next match if the match length cannot increase
  13914. * or if the match length is less than 2. Note that the checks below
  13915. * for insufficient lookahead only occur occasionally for performance
  13916. * reasons. Therefore uninitialized memory will be accessed, and
  13917. * conditional jumps will be made that depend on those values.
  13918. * However the length of the match is limited to the lookahead, so
  13919. * the output of deflate is not affected by the uninitialized values.
  13920. */
  13921. if (_win[match + best_len] !== scan_end ||
  13922. _win[match + best_len - 1] !== scan_end1 ||
  13923. _win[match] !== _win[scan] ||
  13924. _win[++match] !== _win[scan + 1]) {
  13925. continue;
  13926. }
  13927. /* The check at best_len-1 can be removed because it will be made
  13928. * again later. (This heuristic is not always a win.)
  13929. * It is not necessary to compare scan[2] and match[2] since they
  13930. * are always equal when the other bytes match, given that
  13931. * the hash keys are equal and that HASH_BITS >= 8.
  13932. */
  13933. scan += 2;
  13934. match++;
  13935. // Assert(*scan == *match, "match[2]?");
  13936. /* We check for insufficient lookahead only every 8th comparison;
  13937. * the 256th check will be made at strstart+258.
  13938. */
  13939. do {
  13940. /*jshint noempty:false*/
  13941. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13942. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13943. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13944. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13945. scan < strend);
  13946. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  13947. len = MAX_MATCH - (strend - scan);
  13948. scan = strend - MAX_MATCH;
  13949. if (len > best_len) {
  13950. s.match_start = cur_match;
  13951. best_len = len;
  13952. if (len >= nice_match) {
  13953. break;
  13954. }
  13955. scan_end1 = _win[scan + best_len - 1];
  13956. scan_end = _win[scan + best_len];
  13957. }
  13958. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  13959. if (best_len <= s.lookahead) {
  13960. return best_len;
  13961. }
  13962. return s.lookahead;
  13963. }
  13964. /* ===========================================================================
  13965. * Fill the window when the lookahead becomes insufficient.
  13966. * Updates strstart and lookahead.
  13967. *
  13968. * IN assertion: lookahead < MIN_LOOKAHEAD
  13969. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  13970. * At least one byte has been read, or avail_in == 0; reads are
  13971. * performed for at least two bytes (required for the zip translate_eol
  13972. * option -- not supported here).
  13973. */
  13974. function fill_window(s) {
  13975. var _w_size = s.w_size;
  13976. var p, n, m, more, str;
  13977. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  13978. do {
  13979. more = s.window_size - s.lookahead - s.strstart;
  13980. // JS ints have 32 bit, block below not needed
  13981. /* Deal with !@#$% 64K limit: */
  13982. //if (sizeof(int) <= 2) {
  13983. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  13984. // more = wsize;
  13985. //
  13986. // } else if (more == (unsigned)(-1)) {
  13987. // /* Very unlikely, but possible on 16 bit machine if
  13988. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  13989. // */
  13990. // more--;
  13991. // }
  13992. //}
  13993. /* If the window is almost full and there is insufficient lookahead,
  13994. * move the upper half to the lower one to make room in the upper half.
  13995. */
  13996. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  13997. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  13998. s.match_start -= _w_size;
  13999. s.strstart -= _w_size;
  14000. /* we now have strstart >= MAX_DIST */
  14001. s.block_start -= _w_size;
  14002. /* Slide the hash table (could be avoided with 32 bit values
  14003. at the expense of memory usage). We slide even when level == 0
  14004. to keep the hash table consistent if we switch back to level > 0
  14005. later. (Using level 0 permanently is not an optimal usage of
  14006. zlib, so we don't care about this pathological case.)
  14007. */
  14008. n = s.hash_size;
  14009. p = n;
  14010. do {
  14011. m = s.head[--p];
  14012. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14013. } while (--n);
  14014. n = _w_size;
  14015. p = n;
  14016. do {
  14017. m = s.prev[--p];
  14018. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14019. /* If n is not on any hash chain, prev[n] is garbage but
  14020. * its value will never be used.
  14021. */
  14022. } while (--n);
  14023. more += _w_size;
  14024. }
  14025. if (s.strm.avail_in === 0) {
  14026. break;
  14027. }
  14028. /* If there was no sliding:
  14029. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14030. * more == window_size - lookahead - strstart
  14031. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14032. * => more >= window_size - 2*WSIZE + 2
  14033. * In the BIG_MEM or MMAP case (not yet supported),
  14034. * window_size == input_size + MIN_LOOKAHEAD &&
  14035. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14036. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14037. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14038. */
  14039. //Assert(more >= 2, "more < 2");
  14040. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14041. s.lookahead += n;
  14042. /* Initialize the hash value now that we have some input: */
  14043. if (s.lookahead + s.insert >= MIN_MATCH) {
  14044. str = s.strstart - s.insert;
  14045. s.ins_h = s.window[str];
  14046. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14047. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14048. //#if MIN_MATCH != 3
  14049. // Call update_hash() MIN_MATCH-3 more times
  14050. //#endif
  14051. while (s.insert) {
  14052. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14053. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  14054. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14055. s.head[s.ins_h] = str;
  14056. str++;
  14057. s.insert--;
  14058. if (s.lookahead + s.insert < MIN_MATCH) {
  14059. break;
  14060. }
  14061. }
  14062. }
  14063. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14064. * but this is not important since only literal bytes will be emitted.
  14065. */
  14066. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14067. /* If the WIN_INIT bytes after the end of the current data have never been
  14068. * written, then zero those bytes in order to avoid memory check reports of
  14069. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14070. * the longest match routines. Update the high water mark for the next
  14071. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14072. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14073. */
  14074. // if (s.high_water < s.window_size) {
  14075. // var curr = s.strstart + s.lookahead;
  14076. // var init = 0;
  14077. //
  14078. // if (s.high_water < curr) {
  14079. // /* Previous high water mark below current data -- zero WIN_INIT
  14080. // * bytes or up to end of window, whichever is less.
  14081. // */
  14082. // init = s.window_size - curr;
  14083. // if (init > WIN_INIT)
  14084. // init = WIN_INIT;
  14085. // zmemzero(s->window + curr, (unsigned)init);
  14086. // s->high_water = curr + init;
  14087. // }
  14088. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14089. // /* High water mark at or above current data, but below current data
  14090. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14091. // * to end of window, whichever is less.
  14092. // */
  14093. // init = (ulg)curr + WIN_INIT - s->high_water;
  14094. // if (init > s->window_size - s->high_water)
  14095. // init = s->window_size - s->high_water;
  14096. // zmemzero(s->window + s->high_water, (unsigned)init);
  14097. // s->high_water += init;
  14098. // }
  14099. // }
  14100. //
  14101. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  14102. // "not enough room for search");
  14103. }
  14104. /* ===========================================================================
  14105. * Copy without compression as much as possible from the input stream, return
  14106. * the current block state.
  14107. * This function does not insert new strings in the dictionary since
  14108. * uncompressible data is probably not useful. This function is used
  14109. * only for the level=0 compression option.
  14110. * NOTE: this function should be optimized to avoid extra copying from
  14111. * window to pending_buf.
  14112. */
  14113. function deflate_stored(s, flush) {
  14114. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  14115. * to pending_buf_size, and each stored block has a 5 byte header:
  14116. */
  14117. var max_block_size = 0xffff;
  14118. if (max_block_size > s.pending_buf_size - 5) {
  14119. max_block_size = s.pending_buf_size - 5;
  14120. }
  14121. /* Copy as much as possible from input to output: */
  14122. for (;;) {
  14123. /* Fill the window as much as possible: */
  14124. if (s.lookahead <= 1) {
  14125. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  14126. // s->block_start >= (long)s->w_size, "slide too late");
  14127. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  14128. // s.block_start >= s.w_size)) {
  14129. // throw new Error("slide too late");
  14130. // }
  14131. fill_window(s);
  14132. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  14133. return BS_NEED_MORE;
  14134. }
  14135. if (s.lookahead === 0) {
  14136. break;
  14137. }
  14138. /* flush the current block */
  14139. }
  14140. //Assert(s->block_start >= 0L, "block gone");
  14141. // if (s.block_start < 0) throw new Error("block gone");
  14142. s.strstart += s.lookahead;
  14143. s.lookahead = 0;
  14144. /* Emit a stored block if pending_buf will be full: */
  14145. var max_start = s.block_start + max_block_size;
  14146. if (s.strstart === 0 || s.strstart >= max_start) {
  14147. /* strstart == 0 is possible when wraparound on 16-bit machine */
  14148. s.lookahead = s.strstart - max_start;
  14149. s.strstart = max_start;
  14150. /*** FLUSH_BLOCK(s, 0); ***/
  14151. flush_block_only(s, false);
  14152. if (s.strm.avail_out === 0) {
  14153. return BS_NEED_MORE;
  14154. }
  14155. /***/
  14156. }
  14157. /* Flush if we may have to slide, otherwise block_start may become
  14158. * negative and the data will be gone:
  14159. */
  14160. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  14161. /*** FLUSH_BLOCK(s, 0); ***/
  14162. flush_block_only(s, false);
  14163. if (s.strm.avail_out === 0) {
  14164. return BS_NEED_MORE;
  14165. }
  14166. /***/
  14167. }
  14168. }
  14169. s.insert = 0;
  14170. if (flush === Z_FINISH) {
  14171. /*** FLUSH_BLOCK(s, 1); ***/
  14172. flush_block_only(s, true);
  14173. if (s.strm.avail_out === 0) {
  14174. return BS_FINISH_STARTED;
  14175. }
  14176. /***/
  14177. return BS_FINISH_DONE;
  14178. }
  14179. if (s.strstart > s.block_start) {
  14180. /*** FLUSH_BLOCK(s, 0); ***/
  14181. flush_block_only(s, false);
  14182. if (s.strm.avail_out === 0) {
  14183. return BS_NEED_MORE;
  14184. }
  14185. /***/
  14186. }
  14187. return BS_NEED_MORE;
  14188. }
  14189. /* ===========================================================================
  14190. * Compress as much as possible from the input stream, return the current
  14191. * block state.
  14192. * This function does not perform lazy evaluation of matches and inserts
  14193. * new strings in the dictionary only for unmatched strings or for short
  14194. * matches. It is used only for the fast compression options.
  14195. */
  14196. function deflate_fast(s, flush) {
  14197. var hash_head; /* head of the hash chain */
  14198. var bflush; /* set if current block must be flushed */
  14199. for (;;) {
  14200. /* Make sure that we always have enough lookahead, except
  14201. * at the end of the input file. We need MAX_MATCH bytes
  14202. * for the next match, plus MIN_MATCH bytes to insert the
  14203. * string following the next match.
  14204. */
  14205. if (s.lookahead < MIN_LOOKAHEAD) {
  14206. fill_window(s);
  14207. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14208. return BS_NEED_MORE;
  14209. }
  14210. if (s.lookahead === 0) {
  14211. break; /* flush the current block */
  14212. }
  14213. }
  14214. /* Insert the string window[strstart .. strstart+2] in the
  14215. * dictionary, and set hash_head to the head of the hash chain:
  14216. */
  14217. hash_head = 0/*NIL*/;
  14218. if (s.lookahead >= MIN_MATCH) {
  14219. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14220. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14221. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14222. s.head[s.ins_h] = s.strstart;
  14223. /***/
  14224. }
  14225. /* Find the longest match, discarding those <= prev_length.
  14226. * At this point we have always match_length < MIN_MATCH
  14227. */
  14228. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14229. /* To simplify the code, we prevent matches with the string
  14230. * of window index 0 (in particular we have to avoid a match
  14231. * of the string with itself at the start of the input file).
  14232. */
  14233. s.match_length = longest_match(s, hash_head);
  14234. /* longest_match() sets match_start */
  14235. }
  14236. if (s.match_length >= MIN_MATCH) {
  14237. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14238. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14239. s.match_length - MIN_MATCH, bflush); ***/
  14240. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14241. s.lookahead -= s.match_length;
  14242. /* Insert new strings in the hash table only if the match length
  14243. * is not too large. This saves time but degrades compression.
  14244. */
  14245. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14246. s.match_length--; /* string at strstart already in table */
  14247. do {
  14248. s.strstart++;
  14249. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14250. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14251. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14252. s.head[s.ins_h] = s.strstart;
  14253. /***/
  14254. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14255. * always MIN_MATCH bytes ahead.
  14256. */
  14257. } while (--s.match_length !== 0);
  14258. s.strstart++;
  14259. } else
  14260. {
  14261. s.strstart += s.match_length;
  14262. s.match_length = 0;
  14263. s.ins_h = s.window[s.strstart];
  14264. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14265. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14266. //#if MIN_MATCH != 3
  14267. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14268. //#endif
  14269. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14270. * matter since it will be recomputed at next deflate call.
  14271. */
  14272. }
  14273. } else {
  14274. /* No match, output a literal byte */
  14275. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14276. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14277. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14278. s.lookahead--;
  14279. s.strstart++;
  14280. }
  14281. if (bflush) {
  14282. /*** FLUSH_BLOCK(s, 0); ***/
  14283. flush_block_only(s, false);
  14284. if (s.strm.avail_out === 0) {
  14285. return BS_NEED_MORE;
  14286. }
  14287. /***/
  14288. }
  14289. }
  14290. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  14291. if (flush === Z_FINISH) {
  14292. /*** FLUSH_BLOCK(s, 1); ***/
  14293. flush_block_only(s, true);
  14294. if (s.strm.avail_out === 0) {
  14295. return BS_FINISH_STARTED;
  14296. }
  14297. /***/
  14298. return BS_FINISH_DONE;
  14299. }
  14300. if (s.last_lit) {
  14301. /*** FLUSH_BLOCK(s, 0); ***/
  14302. flush_block_only(s, false);
  14303. if (s.strm.avail_out === 0) {
  14304. return BS_NEED_MORE;
  14305. }
  14306. /***/
  14307. }
  14308. return BS_BLOCK_DONE;
  14309. }
  14310. /* ===========================================================================
  14311. * Same as above, but achieves better compression. We use a lazy
  14312. * evaluation for matches: a match is finally adopted only if there is
  14313. * no better match at the next window position.
  14314. */
  14315. function deflate_slow(s, flush) {
  14316. var hash_head; /* head of hash chain */
  14317. var bflush; /* set if current block must be flushed */
  14318. var max_insert;
  14319. /* Process the input block. */
  14320. for (;;) {
  14321. /* Make sure that we always have enough lookahead, except
  14322. * at the end of the input file. We need MAX_MATCH bytes
  14323. * for the next match, plus MIN_MATCH bytes to insert the
  14324. * string following the next match.
  14325. */
  14326. if (s.lookahead < MIN_LOOKAHEAD) {
  14327. fill_window(s);
  14328. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14329. return BS_NEED_MORE;
  14330. }
  14331. if (s.lookahead === 0) { break; } /* flush the current block */
  14332. }
  14333. /* Insert the string window[strstart .. strstart+2] in the
  14334. * dictionary, and set hash_head to the head of the hash chain:
  14335. */
  14336. hash_head = 0/*NIL*/;
  14337. if (s.lookahead >= MIN_MATCH) {
  14338. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14339. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14340. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14341. s.head[s.ins_h] = s.strstart;
  14342. /***/
  14343. }
  14344. /* Find the longest match, discarding those <= prev_length.
  14345. */
  14346. s.prev_length = s.match_length;
  14347. s.prev_match = s.match_start;
  14348. s.match_length = MIN_MATCH-1;
  14349. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  14350. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  14351. /* To simplify the code, we prevent matches with the string
  14352. * of window index 0 (in particular we have to avoid a match
  14353. * of the string with itself at the start of the input file).
  14354. */
  14355. s.match_length = longest_match(s, hash_head);
  14356. /* longest_match() sets match_start */
  14357. if (s.match_length <= 5 &&
  14358. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  14359. /* If prev_match is also MIN_MATCH, match_start is garbage
  14360. * but we will ignore the current match anyway.
  14361. */
  14362. s.match_length = MIN_MATCH-1;
  14363. }
  14364. }
  14365. /* If there was a match at the previous step and the current
  14366. * match is not better, output the previous match:
  14367. */
  14368. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  14369. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  14370. /* Do not insert strings in hash table beyond this. */
  14371. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  14372. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  14373. s.prev_length - MIN_MATCH, bflush);***/
  14374. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  14375. /* Insert in hash table all strings up to the end of the match.
  14376. * strstart-1 and strstart are already inserted. If there is not
  14377. * enough lookahead, the last two strings are not inserted in
  14378. * the hash table.
  14379. */
  14380. s.lookahead -= s.prev_length-1;
  14381. s.prev_length -= 2;
  14382. do {
  14383. if (++s.strstart <= max_insert) {
  14384. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14385. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14386. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14387. s.head[s.ins_h] = s.strstart;
  14388. /***/
  14389. }
  14390. } while (--s.prev_length !== 0);
  14391. s.match_available = 0;
  14392. s.match_length = MIN_MATCH-1;
  14393. s.strstart++;
  14394. if (bflush) {
  14395. /*** FLUSH_BLOCK(s, 0); ***/
  14396. flush_block_only(s, false);
  14397. if (s.strm.avail_out === 0) {
  14398. return BS_NEED_MORE;
  14399. }
  14400. /***/
  14401. }
  14402. } else if (s.match_available) {
  14403. /* If there was no match at the previous position, output a
  14404. * single literal. If there was a match but the current match
  14405. * is longer, truncate the previous match to a single literal.
  14406. */
  14407. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14408. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14409. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14410. if (bflush) {
  14411. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  14412. flush_block_only(s, false);
  14413. /***/
  14414. }
  14415. s.strstart++;
  14416. s.lookahead--;
  14417. if (s.strm.avail_out === 0) {
  14418. return BS_NEED_MORE;
  14419. }
  14420. } else {
  14421. /* There is no previous match to compare with, wait for
  14422. * the next step to decide.
  14423. */
  14424. s.match_available = 1;
  14425. s.strstart++;
  14426. s.lookahead--;
  14427. }
  14428. }
  14429. //Assert (flush != Z_NO_FLUSH, "no flush?");
  14430. if (s.match_available) {
  14431. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14432. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14433. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14434. s.match_available = 0;
  14435. }
  14436. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  14437. if (flush === Z_FINISH) {
  14438. /*** FLUSH_BLOCK(s, 1); ***/
  14439. flush_block_only(s, true);
  14440. if (s.strm.avail_out === 0) {
  14441. return BS_FINISH_STARTED;
  14442. }
  14443. /***/
  14444. return BS_FINISH_DONE;
  14445. }
  14446. if (s.last_lit) {
  14447. /*** FLUSH_BLOCK(s, 0); ***/
  14448. flush_block_only(s, false);
  14449. if (s.strm.avail_out === 0) {
  14450. return BS_NEED_MORE;
  14451. }
  14452. /***/
  14453. }
  14454. return BS_BLOCK_DONE;
  14455. }
  14456. /* ===========================================================================
  14457. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  14458. * one. Do not maintain a hash table. (It will be regenerated if this run of
  14459. * deflate switches away from Z_RLE.)
  14460. */
  14461. function deflate_rle(s, flush) {
  14462. var bflush; /* set if current block must be flushed */
  14463. var prev; /* byte at distance one to match */
  14464. var scan, strend; /* scan goes up to strend for length of run */
  14465. var _win = s.window;
  14466. for (;;) {
  14467. /* Make sure that we always have enough lookahead, except
  14468. * at the end of the input file. We need MAX_MATCH bytes
  14469. * for the longest run, plus one for the unrolled loop.
  14470. */
  14471. if (s.lookahead <= MAX_MATCH) {
  14472. fill_window(s);
  14473. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  14474. return BS_NEED_MORE;
  14475. }
  14476. if (s.lookahead === 0) { break; } /* flush the current block */
  14477. }
  14478. /* See how many times the previous byte repeats */
  14479. s.match_length = 0;
  14480. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  14481. scan = s.strstart - 1;
  14482. prev = _win[scan];
  14483. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  14484. strend = s.strstart + MAX_MATCH;
  14485. do {
  14486. /*jshint noempty:false*/
  14487. } while (prev === _win[++scan] && prev === _win[++scan] &&
  14488. prev === _win[++scan] && prev === _win[++scan] &&
  14489. prev === _win[++scan] && prev === _win[++scan] &&
  14490. prev === _win[++scan] && prev === _win[++scan] &&
  14491. scan < strend);
  14492. s.match_length = MAX_MATCH - (strend - scan);
  14493. if (s.match_length > s.lookahead) {
  14494. s.match_length = s.lookahead;
  14495. }
  14496. }
  14497. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  14498. }
  14499. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  14500. if (s.match_length >= MIN_MATCH) {
  14501. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  14502. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  14503. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  14504. s.lookahead -= s.match_length;
  14505. s.strstart += s.match_length;
  14506. s.match_length = 0;
  14507. } else {
  14508. /* No match, output a literal byte */
  14509. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14510. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14511. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14512. s.lookahead--;
  14513. s.strstart++;
  14514. }
  14515. if (bflush) {
  14516. /*** FLUSH_BLOCK(s, 0); ***/
  14517. flush_block_only(s, false);
  14518. if (s.strm.avail_out === 0) {
  14519. return BS_NEED_MORE;
  14520. }
  14521. /***/
  14522. }
  14523. }
  14524. s.insert = 0;
  14525. if (flush === Z_FINISH) {
  14526. /*** FLUSH_BLOCK(s, 1); ***/
  14527. flush_block_only(s, true);
  14528. if (s.strm.avail_out === 0) {
  14529. return BS_FINISH_STARTED;
  14530. }
  14531. /***/
  14532. return BS_FINISH_DONE;
  14533. }
  14534. if (s.last_lit) {
  14535. /*** FLUSH_BLOCK(s, 0); ***/
  14536. flush_block_only(s, false);
  14537. if (s.strm.avail_out === 0) {
  14538. return BS_NEED_MORE;
  14539. }
  14540. /***/
  14541. }
  14542. return BS_BLOCK_DONE;
  14543. }
  14544. /* ===========================================================================
  14545. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  14546. * (It will be regenerated if this run of deflate switches away from Huffman.)
  14547. */
  14548. function deflate_huff(s, flush) {
  14549. var bflush; /* set if current block must be flushed */
  14550. for (;;) {
  14551. /* Make sure that we have a literal to write. */
  14552. if (s.lookahead === 0) {
  14553. fill_window(s);
  14554. if (s.lookahead === 0) {
  14555. if (flush === Z_NO_FLUSH) {
  14556. return BS_NEED_MORE;
  14557. }
  14558. break; /* flush the current block */
  14559. }
  14560. }
  14561. /* Output a literal byte */
  14562. s.match_length = 0;
  14563. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14564. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14565. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14566. s.lookahead--;
  14567. s.strstart++;
  14568. if (bflush) {
  14569. /*** FLUSH_BLOCK(s, 0); ***/
  14570. flush_block_only(s, false);
  14571. if (s.strm.avail_out === 0) {
  14572. return BS_NEED_MORE;
  14573. }
  14574. /***/
  14575. }
  14576. }
  14577. s.insert = 0;
  14578. if (flush === Z_FINISH) {
  14579. /*** FLUSH_BLOCK(s, 1); ***/
  14580. flush_block_only(s, true);
  14581. if (s.strm.avail_out === 0) {
  14582. return BS_FINISH_STARTED;
  14583. }
  14584. /***/
  14585. return BS_FINISH_DONE;
  14586. }
  14587. if (s.last_lit) {
  14588. /*** FLUSH_BLOCK(s, 0); ***/
  14589. flush_block_only(s, false);
  14590. if (s.strm.avail_out === 0) {
  14591. return BS_NEED_MORE;
  14592. }
  14593. /***/
  14594. }
  14595. return BS_BLOCK_DONE;
  14596. }
  14597. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  14598. * the desired pack level (0..9). The values given below have been tuned to
  14599. * exclude worst case performance for pathological files. Better values may be
  14600. * found for specific files.
  14601. */
  14602. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  14603. this.good_length = good_length;
  14604. this.max_lazy = max_lazy;
  14605. this.nice_length = nice_length;
  14606. this.max_chain = max_chain;
  14607. this.func = func;
  14608. };
  14609. var configuration_table;
  14610. configuration_table = [
  14611. /* good lazy nice chain */
  14612. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  14613. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  14614. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  14615. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  14616. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  14617. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  14618. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  14619. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  14620. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  14621. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  14622. ];
  14623. /* ===========================================================================
  14624. * Initialize the "longest match" routines for a new zlib stream
  14625. */
  14626. function lm_init(s) {
  14627. s.window_size = 2 * s.w_size;
  14628. /*** CLEAR_HASH(s); ***/
  14629. zero(s.head); // Fill with NIL (= 0);
  14630. /* Set the default configuration parameters:
  14631. */
  14632. s.max_lazy_match = configuration_table[s.level].max_lazy;
  14633. s.good_match = configuration_table[s.level].good_length;
  14634. s.nice_match = configuration_table[s.level].nice_length;
  14635. s.max_chain_length = configuration_table[s.level].max_chain;
  14636. s.strstart = 0;
  14637. s.block_start = 0;
  14638. s.lookahead = 0;
  14639. s.insert = 0;
  14640. s.match_length = s.prev_length = MIN_MATCH - 1;
  14641. s.match_available = 0;
  14642. s.ins_h = 0;
  14643. }
  14644. function DeflateState() {
  14645. this.strm = null; /* pointer back to this zlib stream */
  14646. this.status = 0; /* as the name implies */
  14647. this.pending_buf = null; /* output still pending */
  14648. this.pending_buf_size = 0; /* size of pending_buf */
  14649. this.pending_out = 0; /* next pending byte to output to the stream */
  14650. this.pending = 0; /* nb of bytes in the pending buffer */
  14651. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14652. this.gzhead = null; /* gzip header information to write */
  14653. this.gzindex = 0; /* where in extra, name, or comment */
  14654. this.method = Z_DEFLATED; /* can only be DEFLATED */
  14655. this.last_flush = -1; /* value of flush param for previous deflate call */
  14656. this.w_size = 0; /* LZ77 window size (32K by default) */
  14657. this.w_bits = 0; /* log2(w_size) (8..16) */
  14658. this.w_mask = 0; /* w_size - 1 */
  14659. this.window = null;
  14660. /* Sliding window. Input bytes are read into the second half of the window,
  14661. * and move to the first half later to keep a dictionary of at least wSize
  14662. * bytes. With this organization, matches are limited to a distance of
  14663. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  14664. * performed with a length multiple of the block size.
  14665. */
  14666. this.window_size = 0;
  14667. /* Actual size of window: 2*wSize, except when the user input buffer
  14668. * is directly used as sliding window.
  14669. */
  14670. this.prev = null;
  14671. /* Link to older string with same hash index. To limit the size of this
  14672. * array to 64K, this link is maintained only for the last 32K strings.
  14673. * An index in this array is thus a window index modulo 32K.
  14674. */
  14675. this.head = null; /* Heads of the hash chains or NIL. */
  14676. this.ins_h = 0; /* hash index of string to be inserted */
  14677. this.hash_size = 0; /* number of elements in hash table */
  14678. this.hash_bits = 0; /* log2(hash_size) */
  14679. this.hash_mask = 0; /* hash_size-1 */
  14680. this.hash_shift = 0;
  14681. /* Number of bits by which ins_h must be shifted at each input
  14682. * step. It must be such that after MIN_MATCH steps, the oldest
  14683. * byte no longer takes part in the hash key, that is:
  14684. * hash_shift * MIN_MATCH >= hash_bits
  14685. */
  14686. this.block_start = 0;
  14687. /* Window position at the beginning of the current output block. Gets
  14688. * negative when the window is moved backwards.
  14689. */
  14690. this.match_length = 0; /* length of best match */
  14691. this.prev_match = 0; /* previous match */
  14692. this.match_available = 0; /* set if previous match exists */
  14693. this.strstart = 0; /* start of string to insert */
  14694. this.match_start = 0; /* start of matching string */
  14695. this.lookahead = 0; /* number of valid bytes ahead in window */
  14696. this.prev_length = 0;
  14697. /* Length of the best match at previous step. Matches not greater than this
  14698. * are discarded. This is used in the lazy match evaluation.
  14699. */
  14700. this.max_chain_length = 0;
  14701. /* To speed up deflation, hash chains are never searched beyond this
  14702. * length. A higher limit improves compression ratio but degrades the
  14703. * speed.
  14704. */
  14705. this.max_lazy_match = 0;
  14706. /* Attempt to find a better match only when the current match is strictly
  14707. * smaller than this value. This mechanism is used only for compression
  14708. * levels >= 4.
  14709. */
  14710. // That's alias to max_lazy_match, don't use directly
  14711. //this.max_insert_length = 0;
  14712. /* Insert new strings in the hash table only if the match length is not
  14713. * greater than this length. This saves time but degrades compression.
  14714. * max_insert_length is used only for compression levels <= 3.
  14715. */
  14716. this.level = 0; /* compression level (1..9) */
  14717. this.strategy = 0; /* favor or force Huffman coding*/
  14718. this.good_match = 0;
  14719. /* Use a faster search when the previous match is longer than this */
  14720. this.nice_match = 0; /* Stop searching when current match exceeds this */
  14721. /* used by trees.c: */
  14722. /* Didn't use ct_data typedef below to suppress compiler warning */
  14723. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  14724. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  14725. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  14726. // Use flat array of DOUBLE size, with interleaved fata,
  14727. // because JS does not support effective
  14728. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  14729. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  14730. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  14731. zero(this.dyn_ltree);
  14732. zero(this.dyn_dtree);
  14733. zero(this.bl_tree);
  14734. this.l_desc = null; /* desc. for literal tree */
  14735. this.d_desc = null; /* desc. for distance tree */
  14736. this.bl_desc = null; /* desc. for bit length tree */
  14737. //ush bl_count[MAX_BITS+1];
  14738. this.bl_count = new utils.Buf16(MAX_BITS+1);
  14739. /* number of codes at each bit length for an optimal tree */
  14740. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  14741. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  14742. zero(this.heap);
  14743. this.heap_len = 0; /* number of elements in the heap */
  14744. this.heap_max = 0; /* element of largest frequency */
  14745. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  14746. * The same heap array is used to build all trees.
  14747. */
  14748. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  14749. zero(this.depth);
  14750. /* Depth of each subtree used as tie breaker for trees of equal frequency
  14751. */
  14752. this.l_buf = 0; /* buffer index for literals or lengths */
  14753. this.lit_bufsize = 0;
  14754. /* Size of match buffer for literals/lengths. There are 4 reasons for
  14755. * limiting lit_bufsize to 64K:
  14756. * - frequencies can be kept in 16 bit counters
  14757. * - if compression is not successful for the first block, all input
  14758. * data is still in the window so we can still emit a stored block even
  14759. * when input comes from standard input. (This can also be done for
  14760. * all blocks if lit_bufsize is not greater than 32K.)
  14761. * - if compression is not successful for a file smaller than 64K, we can
  14762. * even emit a stored file instead of a stored block (saving 5 bytes).
  14763. * This is applicable only for zip (not gzip or zlib).
  14764. * - creating new Huffman trees less frequently may not provide fast
  14765. * adaptation to changes in the input data statistics. (Take for
  14766. * example a binary file with poorly compressible code followed by
  14767. * a highly compressible string table.) Smaller buffer sizes give
  14768. * fast adaptation but have of course the overhead of transmitting
  14769. * trees more frequently.
  14770. * - I can't count above 4
  14771. */
  14772. this.last_lit = 0; /* running index in l_buf */
  14773. this.d_buf = 0;
  14774. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  14775. * the same number of elements. To use different lengths, an extra flag
  14776. * array would be necessary.
  14777. */
  14778. this.opt_len = 0; /* bit length of current block with optimal trees */
  14779. this.static_len = 0; /* bit length of current block with static trees */
  14780. this.matches = 0; /* number of string matches in current block */
  14781. this.insert = 0; /* bytes at end of window left to insert */
  14782. this.bi_buf = 0;
  14783. /* Output buffer. bits are inserted starting at the bottom (least
  14784. * significant bits).
  14785. */
  14786. this.bi_valid = 0;
  14787. /* Number of valid bits in bi_buf. All bits above the last valid bit
  14788. * are always zero.
  14789. */
  14790. // Used for window memory init. We safely ignore it for JS. That makes
  14791. // sense only for pointers and memory check tools.
  14792. //this.high_water = 0;
  14793. /* High water mark offset in window for initialized bytes -- bytes above
  14794. * this are set to zero in order to avoid memory check warnings when
  14795. * longest match routines access bytes past the input. This is then
  14796. * updated to the new high water mark.
  14797. */
  14798. }
  14799. function deflateResetKeep(strm) {
  14800. var s;
  14801. if (!strm || !strm.state) {
  14802. return err(strm, Z_STREAM_ERROR);
  14803. }
  14804. strm.total_in = strm.total_out = 0;
  14805. strm.data_type = Z_UNKNOWN;
  14806. s = strm.state;
  14807. s.pending = 0;
  14808. s.pending_out = 0;
  14809. if (s.wrap < 0) {
  14810. s.wrap = -s.wrap;
  14811. /* was made negative by deflate(..., Z_FINISH); */
  14812. }
  14813. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  14814. strm.adler = (s.wrap === 2) ?
  14815. 0 // crc32(0, Z_NULL, 0)
  14816. :
  14817. 1; // adler32(0, Z_NULL, 0)
  14818. s.last_flush = Z_NO_FLUSH;
  14819. trees._tr_init(s);
  14820. return Z_OK;
  14821. }
  14822. function deflateReset(strm) {
  14823. var ret = deflateResetKeep(strm);
  14824. if (ret === Z_OK) {
  14825. lm_init(strm.state);
  14826. }
  14827. return ret;
  14828. }
  14829. function deflateSetHeader(strm, head) {
  14830. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14831. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  14832. strm.state.gzhead = head;
  14833. return Z_OK;
  14834. }
  14835. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  14836. if (!strm) { // === Z_NULL
  14837. return Z_STREAM_ERROR;
  14838. }
  14839. var wrap = 1;
  14840. if (level === Z_DEFAULT_COMPRESSION) {
  14841. level = 6;
  14842. }
  14843. if (windowBits < 0) { /* suppress zlib wrapper */
  14844. wrap = 0;
  14845. windowBits = -windowBits;
  14846. }
  14847. else if (windowBits > 15) {
  14848. wrap = 2; /* write gzip wrapper instead */
  14849. windowBits -= 16;
  14850. }
  14851. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  14852. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  14853. strategy < 0 || strategy > Z_FIXED) {
  14854. return err(strm, Z_STREAM_ERROR);
  14855. }
  14856. if (windowBits === 8) {
  14857. windowBits = 9;
  14858. }
  14859. /* until 256-byte window bug fixed */
  14860. var s = new DeflateState();
  14861. strm.state = s;
  14862. s.strm = strm;
  14863. s.wrap = wrap;
  14864. s.gzhead = null;
  14865. s.w_bits = windowBits;
  14866. s.w_size = 1 << s.w_bits;
  14867. s.w_mask = s.w_size - 1;
  14868. s.hash_bits = memLevel + 7;
  14869. s.hash_size = 1 << s.hash_bits;
  14870. s.hash_mask = s.hash_size - 1;
  14871. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  14872. s.window = new utils.Buf8(s.w_size * 2);
  14873. s.head = new utils.Buf16(s.hash_size);
  14874. s.prev = new utils.Buf16(s.w_size);
  14875. // Don't need mem init magic for JS.
  14876. //s.high_water = 0; /* nothing written to s->window yet */
  14877. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  14878. s.pending_buf_size = s.lit_bufsize * 4;
  14879. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  14880. s.d_buf = s.lit_bufsize >> 1;
  14881. s.l_buf = (1 + 2) * s.lit_bufsize;
  14882. s.level = level;
  14883. s.strategy = strategy;
  14884. s.method = method;
  14885. return deflateReset(strm);
  14886. }
  14887. function deflateInit(strm, level) {
  14888. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  14889. }
  14890. function deflate(strm, flush) {
  14891. var old_flush, s;
  14892. var beg, val; // for gzip header write only
  14893. if (!strm || !strm.state ||
  14894. flush > Z_BLOCK || flush < 0) {
  14895. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  14896. }
  14897. s = strm.state;
  14898. if (!strm.output ||
  14899. (!strm.input && strm.avail_in !== 0) ||
  14900. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  14901. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  14902. }
  14903. s.strm = strm; /* just in case */
  14904. old_flush = s.last_flush;
  14905. s.last_flush = flush;
  14906. /* Write the header */
  14907. if (s.status === INIT_STATE) {
  14908. if (s.wrap === 2) { // GZIP header
  14909. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14910. put_byte(s, 31);
  14911. put_byte(s, 139);
  14912. put_byte(s, 8);
  14913. if (!s.gzhead) { // s->gzhead == Z_NULL
  14914. put_byte(s, 0);
  14915. put_byte(s, 0);
  14916. put_byte(s, 0);
  14917. put_byte(s, 0);
  14918. put_byte(s, 0);
  14919. put_byte(s, s.level === 9 ? 2 :
  14920. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14921. 4 : 0));
  14922. put_byte(s, OS_CODE);
  14923. s.status = BUSY_STATE;
  14924. }
  14925. else {
  14926. put_byte(s, (s.gzhead.text ? 1 : 0) +
  14927. (s.gzhead.hcrc ? 2 : 0) +
  14928. (!s.gzhead.extra ? 0 : 4) +
  14929. (!s.gzhead.name ? 0 : 8) +
  14930. (!s.gzhead.comment ? 0 : 16)
  14931. );
  14932. put_byte(s, s.gzhead.time & 0xff);
  14933. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  14934. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  14935. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  14936. put_byte(s, s.level === 9 ? 2 :
  14937. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14938. 4 : 0));
  14939. put_byte(s, s.gzhead.os & 0xff);
  14940. if (s.gzhead.extra && s.gzhead.extra.length) {
  14941. put_byte(s, s.gzhead.extra.length & 0xff);
  14942. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  14943. }
  14944. if (s.gzhead.hcrc) {
  14945. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  14946. }
  14947. s.gzindex = 0;
  14948. s.status = EXTRA_STATE;
  14949. }
  14950. }
  14951. else // DEFLATE header
  14952. {
  14953. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  14954. var level_flags = -1;
  14955. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  14956. level_flags = 0;
  14957. } else if (s.level < 6) {
  14958. level_flags = 1;
  14959. } else if (s.level === 6) {
  14960. level_flags = 2;
  14961. } else {
  14962. level_flags = 3;
  14963. }
  14964. header |= (level_flags << 6);
  14965. if (s.strstart !== 0) { header |= PRESET_DICT; }
  14966. header += 31 - (header % 31);
  14967. s.status = BUSY_STATE;
  14968. putShortMSB(s, header);
  14969. /* Save the adler32 of the preset dictionary: */
  14970. if (s.strstart !== 0) {
  14971. putShortMSB(s, strm.adler >>> 16);
  14972. putShortMSB(s, strm.adler & 0xffff);
  14973. }
  14974. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  14975. }
  14976. }
  14977. //#ifdef GZIP
  14978. if (s.status === EXTRA_STATE) {
  14979. if (s.gzhead.extra/* != Z_NULL*/) {
  14980. beg = s.pending; /* start of bytes to update crc */
  14981. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  14982. if (s.pending === s.pending_buf_size) {
  14983. if (s.gzhead.hcrc && s.pending > beg) {
  14984. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14985. }
  14986. flush_pending(strm);
  14987. beg = s.pending;
  14988. if (s.pending === s.pending_buf_size) {
  14989. break;
  14990. }
  14991. }
  14992. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  14993. s.gzindex++;
  14994. }
  14995. if (s.gzhead.hcrc && s.pending > beg) {
  14996. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14997. }
  14998. if (s.gzindex === s.gzhead.extra.length) {
  14999. s.gzindex = 0;
  15000. s.status = NAME_STATE;
  15001. }
  15002. }
  15003. else {
  15004. s.status = NAME_STATE;
  15005. }
  15006. }
  15007. if (s.status === NAME_STATE) {
  15008. if (s.gzhead.name/* != Z_NULL*/) {
  15009. beg = s.pending; /* start of bytes to update crc */
  15010. //int val;
  15011. do {
  15012. if (s.pending === s.pending_buf_size) {
  15013. if (s.gzhead.hcrc && s.pending > beg) {
  15014. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15015. }
  15016. flush_pending(strm);
  15017. beg = s.pending;
  15018. if (s.pending === s.pending_buf_size) {
  15019. val = 1;
  15020. break;
  15021. }
  15022. }
  15023. // JS specific: little magic to add zero terminator to end of string
  15024. if (s.gzindex < s.gzhead.name.length) {
  15025. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15026. } else {
  15027. val = 0;
  15028. }
  15029. put_byte(s, val);
  15030. } while (val !== 0);
  15031. if (s.gzhead.hcrc && s.pending > beg) {
  15032. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15033. }
  15034. if (val === 0) {
  15035. s.gzindex = 0;
  15036. s.status = COMMENT_STATE;
  15037. }
  15038. }
  15039. else {
  15040. s.status = COMMENT_STATE;
  15041. }
  15042. }
  15043. if (s.status === COMMENT_STATE) {
  15044. if (s.gzhead.comment/* != Z_NULL*/) {
  15045. beg = s.pending; /* start of bytes to update crc */
  15046. //int val;
  15047. do {
  15048. if (s.pending === s.pending_buf_size) {
  15049. if (s.gzhead.hcrc && s.pending > beg) {
  15050. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15051. }
  15052. flush_pending(strm);
  15053. beg = s.pending;
  15054. if (s.pending === s.pending_buf_size) {
  15055. val = 1;
  15056. break;
  15057. }
  15058. }
  15059. // JS specific: little magic to add zero terminator to end of string
  15060. if (s.gzindex < s.gzhead.comment.length) {
  15061. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15062. } else {
  15063. val = 0;
  15064. }
  15065. put_byte(s, val);
  15066. } while (val !== 0);
  15067. if (s.gzhead.hcrc && s.pending > beg) {
  15068. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15069. }
  15070. if (val === 0) {
  15071. s.status = HCRC_STATE;
  15072. }
  15073. }
  15074. else {
  15075. s.status = HCRC_STATE;
  15076. }
  15077. }
  15078. if (s.status === HCRC_STATE) {
  15079. if (s.gzhead.hcrc) {
  15080. if (s.pending + 2 > s.pending_buf_size) {
  15081. flush_pending(strm);
  15082. }
  15083. if (s.pending + 2 <= s.pending_buf_size) {
  15084. put_byte(s, strm.adler & 0xff);
  15085. put_byte(s, (strm.adler >> 8) & 0xff);
  15086. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15087. s.status = BUSY_STATE;
  15088. }
  15089. }
  15090. else {
  15091. s.status = BUSY_STATE;
  15092. }
  15093. }
  15094. //#endif
  15095. /* Flush as much pending output as possible */
  15096. if (s.pending !== 0) {
  15097. flush_pending(strm);
  15098. if (strm.avail_out === 0) {
  15099. /* Since avail_out is 0, deflate will be called again with
  15100. * more output space, but possibly with both pending and
  15101. * avail_in equal to zero. There won't be anything to do,
  15102. * but this is not an error situation so make sure we
  15103. * return OK instead of BUF_ERROR at next call of deflate:
  15104. */
  15105. s.last_flush = -1;
  15106. return Z_OK;
  15107. }
  15108. /* Make sure there is something to do and avoid duplicate consecutive
  15109. * flushes. For repeated and useless calls with Z_FINISH, we keep
  15110. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  15111. */
  15112. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  15113. flush !== Z_FINISH) {
  15114. return err(strm, Z_BUF_ERROR);
  15115. }
  15116. /* User must not provide more input after the first FINISH: */
  15117. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  15118. return err(strm, Z_BUF_ERROR);
  15119. }
  15120. /* Start a new block or continue the current one.
  15121. */
  15122. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  15123. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  15124. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  15125. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  15126. configuration_table[s.level].func(s, flush));
  15127. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  15128. s.status = FINISH_STATE;
  15129. }
  15130. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  15131. if (strm.avail_out === 0) {
  15132. s.last_flush = -1;
  15133. /* avoid BUF_ERROR next call, see above */
  15134. }
  15135. return Z_OK;
  15136. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  15137. * of deflate should use the same flush parameter to make sure
  15138. * that the flush is complete. So we don't have to output an
  15139. * empty block here, this will be done at next call. This also
  15140. * ensures that for a very small output buffer, we emit at most
  15141. * one empty block.
  15142. */
  15143. }
  15144. if (bstate === BS_BLOCK_DONE) {
  15145. if (flush === Z_PARTIAL_FLUSH) {
  15146. trees._tr_align(s);
  15147. }
  15148. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  15149. trees._tr_stored_block(s, 0, 0, false);
  15150. /* For a full flush, this empty block will be recognized
  15151. * as a special marker by inflate_sync().
  15152. */
  15153. if (flush === Z_FULL_FLUSH) {
  15154. /*** CLEAR_HASH(s); ***/ /* forget history */
  15155. zero(s.head); // Fill with NIL (= 0);
  15156. if (s.lookahead === 0) {
  15157. s.strstart = 0;
  15158. s.block_start = 0;
  15159. s.insert = 0;
  15160. }
  15161. }
  15162. }
  15163. flush_pending(strm);
  15164. if (strm.avail_out === 0) {
  15165. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  15166. return Z_OK;
  15167. }
  15168. }
  15169. }
  15170. //Assert(strm->avail_out > 0, "bug2");
  15171. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  15172. if (flush !== Z_FINISH) { return Z_OK; }
  15173. if (s.wrap <= 0) { return Z_STREAM_END; }
  15174. /* Write the trailer */
  15175. if (s.wrap === 2) {
  15176. put_byte(s, strm.adler & 0xff);
  15177. put_byte(s, (strm.adler >> 8) & 0xff);
  15178. put_byte(s, (strm.adler >> 16) & 0xff);
  15179. put_byte(s, (strm.adler >> 24) & 0xff);
  15180. put_byte(s, strm.total_in & 0xff);
  15181. put_byte(s, (strm.total_in >> 8) & 0xff);
  15182. put_byte(s, (strm.total_in >> 16) & 0xff);
  15183. put_byte(s, (strm.total_in >> 24) & 0xff);
  15184. }
  15185. else
  15186. {
  15187. putShortMSB(s, strm.adler >>> 16);
  15188. putShortMSB(s, strm.adler & 0xffff);
  15189. }
  15190. flush_pending(strm);
  15191. /* If avail_out is zero, the application will call deflate again
  15192. * to flush the rest.
  15193. */
  15194. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15195. /* write the trailer only once! */
  15196. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15197. }
  15198. function deflateEnd(strm) {
  15199. var status;
  15200. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15201. return Z_STREAM_ERROR;
  15202. }
  15203. status = strm.state.status;
  15204. if (status !== INIT_STATE &&
  15205. status !== EXTRA_STATE &&
  15206. status !== NAME_STATE &&
  15207. status !== COMMENT_STATE &&
  15208. status !== HCRC_STATE &&
  15209. status !== BUSY_STATE &&
  15210. status !== FINISH_STATE
  15211. ) {
  15212. return err(strm, Z_STREAM_ERROR);
  15213. }
  15214. strm.state = null;
  15215. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15216. }
  15217. /* =========================================================================
  15218. * Copy the source state to the destination state
  15219. */
  15220. //function deflateCopy(dest, source) {
  15221. //
  15222. //}
  15223. exports.deflateInit = deflateInit;
  15224. exports.deflateInit2 = deflateInit2;
  15225. exports.deflateReset = deflateReset;
  15226. exports.deflateResetKeep = deflateResetKeep;
  15227. exports.deflateSetHeader = deflateSetHeader;
  15228. exports.deflate = deflate;
  15229. exports.deflateEnd = deflateEnd;
  15230. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15231. /* Not implemented
  15232. exports.deflateBound = deflateBound;
  15233. exports.deflateCopy = deflateCopy;
  15234. exports.deflateSetDictionary = deflateSetDictionary;
  15235. exports.deflateParams = deflateParams;
  15236. exports.deflatePending = deflatePending;
  15237. exports.deflatePrime = deflatePrime;
  15238. exports.deflateTune = deflateTune;
  15239. */
  15240. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./messages":61,"./trees":62}],57:[function(require,module,exports){
  15241. 'use strict';
  15242. function GZheader() {
  15243. /* true if compressed data believed to be text */
  15244. this.text = 0;
  15245. /* modification time */
  15246. this.time = 0;
  15247. /* extra flags (not used when writing a gzip file) */
  15248. this.xflags = 0;
  15249. /* operating system */
  15250. this.os = 0;
  15251. /* pointer to extra field or Z_NULL if none */
  15252. this.extra = null;
  15253. /* extra field length (valid if extra != Z_NULL) */
  15254. this.extra_len = 0; // Actually, we don't need it in JS,
  15255. // but leave for few code modifications
  15256. //
  15257. // Setup limits is not necessary because in js we should not preallocate memory
  15258. // for inflate use constant limit in 65536 bytes
  15259. //
  15260. /* space at extra (only when reading header) */
  15261. // this.extra_max = 0;
  15262. /* pointer to zero-terminated file name or Z_NULL */
  15263. this.name = '';
  15264. /* space at name (only when reading header) */
  15265. // this.name_max = 0;
  15266. /* pointer to zero-terminated comment or Z_NULL */
  15267. this.comment = '';
  15268. /* space at comment (only when reading header) */
  15269. // this.comm_max = 0;
  15270. /* true if there was or will be a header crc */
  15271. this.hcrc = 0;
  15272. /* true when done reading gzip header (not used when writing a gzip file) */
  15273. this.done = false;
  15274. }
  15275. module.exports = GZheader;
  15276. },{}],58:[function(require,module,exports){
  15277. 'use strict';
  15278. // See state defs from inflate.js
  15279. var BAD = 30; /* got a data error -- remain here until reset */
  15280. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15281. /*
  15282. Decode literal, length, and distance codes and write out the resulting
  15283. literal and match bytes until either not enough input or output is
  15284. available, an end-of-block is encountered, or a data error is encountered.
  15285. When large enough input and output buffers are supplied to inflate(), for
  15286. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  15287. inflate execution time is spent in this routine.
  15288. Entry assumptions:
  15289. state.mode === LEN
  15290. strm.avail_in >= 6
  15291. strm.avail_out >= 258
  15292. start >= strm.avail_out
  15293. state.bits < 8
  15294. On return, state.mode is one of:
  15295. LEN -- ran out of enough output space or enough available input
  15296. TYPE -- reached end of block code, inflate() to interpret next block
  15297. BAD -- error in block data
  15298. Notes:
  15299. - The maximum input bits used by a length/distance pair is 15 bits for the
  15300. length code, 5 bits for the length extra, 15 bits for the distance code,
  15301. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  15302. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  15303. checking for available input while decoding.
  15304. - The maximum bytes that a single length/distance pair can output is 258
  15305. bytes, which is the maximum length that can be coded. inflate_fast()
  15306. requires strm.avail_out >= 258 for each loop to avoid checking for
  15307. output space.
  15308. */
  15309. module.exports = function inflate_fast(strm, start) {
  15310. var state;
  15311. var _in; /* local strm.input */
  15312. var last; /* have enough input while in < last */
  15313. var _out; /* local strm.output */
  15314. var beg; /* inflate()'s initial strm.output */
  15315. var end; /* while out < end, enough space available */
  15316. //#ifdef INFLATE_STRICT
  15317. var dmax; /* maximum distance from zlib header */
  15318. //#endif
  15319. var wsize; /* window size or zero if not using window */
  15320. var whave; /* valid bytes in the window */
  15321. var wnext; /* window write index */
  15322. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  15323. var s_window; /* allocated sliding window, if wsize != 0 */
  15324. var hold; /* local strm.hold */
  15325. var bits; /* local strm.bits */
  15326. var lcode; /* local strm.lencode */
  15327. var dcode; /* local strm.distcode */
  15328. var lmask; /* mask for first level of length codes */
  15329. var dmask; /* mask for first level of distance codes */
  15330. var here; /* retrieved table entry */
  15331. var op; /* code bits, operation, extra bits, or */
  15332. /* window position, window bytes to copy */
  15333. var len; /* match length, unused bytes */
  15334. var dist; /* match distance */
  15335. var from; /* where to copy match from */
  15336. var from_source;
  15337. var input, output; // JS specific, because we have no pointers
  15338. /* copy state to local variables */
  15339. state = strm.state;
  15340. //here = state.here;
  15341. _in = strm.next_in;
  15342. input = strm.input;
  15343. last = _in + (strm.avail_in - 5);
  15344. _out = strm.next_out;
  15345. output = strm.output;
  15346. beg = _out - (start - strm.avail_out);
  15347. end = _out + (strm.avail_out - 257);
  15348. //#ifdef INFLATE_STRICT
  15349. dmax = state.dmax;
  15350. //#endif
  15351. wsize = state.wsize;
  15352. whave = state.whave;
  15353. wnext = state.wnext;
  15354. s_window = state.window;
  15355. hold = state.hold;
  15356. bits = state.bits;
  15357. lcode = state.lencode;
  15358. dcode = state.distcode;
  15359. lmask = (1 << state.lenbits) - 1;
  15360. dmask = (1 << state.distbits) - 1;
  15361. /* decode literals and length/distances until end-of-block or not enough
  15362. input data or output space */
  15363. top:
  15364. do {
  15365. if (bits < 15) {
  15366. hold += input[_in++] << bits;
  15367. bits += 8;
  15368. hold += input[_in++] << bits;
  15369. bits += 8;
  15370. }
  15371. here = lcode[hold & lmask];
  15372. dolen:
  15373. for (;;) { // Goto emulation
  15374. op = here >>> 24/*here.bits*/;
  15375. hold >>>= op;
  15376. bits -= op;
  15377. op = (here >>> 16) & 0xff/*here.op*/;
  15378. if (op === 0) { /* literal */
  15379. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15380. // "inflate: literal '%c'\n" :
  15381. // "inflate: literal 0x%02x\n", here.val));
  15382. output[_out++] = here & 0xffff/*here.val*/;
  15383. }
  15384. else if (op & 16) { /* length base */
  15385. len = here & 0xffff/*here.val*/;
  15386. op &= 15; /* number of extra bits */
  15387. if (op) {
  15388. if (bits < op) {
  15389. hold += input[_in++] << bits;
  15390. bits += 8;
  15391. }
  15392. len += hold & ((1 << op) - 1);
  15393. hold >>>= op;
  15394. bits -= op;
  15395. }
  15396. //Tracevv((stderr, "inflate: length %u\n", len));
  15397. if (bits < 15) {
  15398. hold += input[_in++] << bits;
  15399. bits += 8;
  15400. hold += input[_in++] << bits;
  15401. bits += 8;
  15402. }
  15403. here = dcode[hold & dmask];
  15404. dodist:
  15405. for (;;) { // goto emulation
  15406. op = here >>> 24/*here.bits*/;
  15407. hold >>>= op;
  15408. bits -= op;
  15409. op = (here >>> 16) & 0xff/*here.op*/;
  15410. if (op & 16) { /* distance base */
  15411. dist = here & 0xffff/*here.val*/;
  15412. op &= 15; /* number of extra bits */
  15413. if (bits < op) {
  15414. hold += input[_in++] << bits;
  15415. bits += 8;
  15416. if (bits < op) {
  15417. hold += input[_in++] << bits;
  15418. bits += 8;
  15419. }
  15420. }
  15421. dist += hold & ((1 << op) - 1);
  15422. //#ifdef INFLATE_STRICT
  15423. if (dist > dmax) {
  15424. strm.msg = 'invalid distance too far back';
  15425. state.mode = BAD;
  15426. break top;
  15427. }
  15428. //#endif
  15429. hold >>>= op;
  15430. bits -= op;
  15431. //Tracevv((stderr, "inflate: distance %u\n", dist));
  15432. op = _out - beg; /* max distance in output */
  15433. if (dist > op) { /* see if copy from window */
  15434. op = dist - op; /* distance back in window */
  15435. if (op > whave) {
  15436. if (state.sane) {
  15437. strm.msg = 'invalid distance too far back';
  15438. state.mode = BAD;
  15439. break top;
  15440. }
  15441. // (!) This block is disabled in zlib defailts,
  15442. // don't enable it for binary compatibility
  15443. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15444. // if (len <= op - whave) {
  15445. // do {
  15446. // output[_out++] = 0;
  15447. // } while (--len);
  15448. // continue top;
  15449. // }
  15450. // len -= op - whave;
  15451. // do {
  15452. // output[_out++] = 0;
  15453. // } while (--op > whave);
  15454. // if (op === 0) {
  15455. // from = _out - dist;
  15456. // do {
  15457. // output[_out++] = output[from++];
  15458. // } while (--len);
  15459. // continue top;
  15460. // }
  15461. //#endif
  15462. }
  15463. from = 0; // window index
  15464. from_source = s_window;
  15465. if (wnext === 0) { /* very common case */
  15466. from += wsize - op;
  15467. if (op < len) { /* some from window */
  15468. len -= op;
  15469. do {
  15470. output[_out++] = s_window[from++];
  15471. } while (--op);
  15472. from = _out - dist; /* rest from output */
  15473. from_source = output;
  15474. }
  15475. }
  15476. else if (wnext < op) { /* wrap around window */
  15477. from += wsize + wnext - op;
  15478. op -= wnext;
  15479. if (op < len) { /* some from end of window */
  15480. len -= op;
  15481. do {
  15482. output[_out++] = s_window[from++];
  15483. } while (--op);
  15484. from = 0;
  15485. if (wnext < len) { /* some from start of window */
  15486. op = wnext;
  15487. len -= op;
  15488. do {
  15489. output[_out++] = s_window[from++];
  15490. } while (--op);
  15491. from = _out - dist; /* rest from output */
  15492. from_source = output;
  15493. }
  15494. }
  15495. }
  15496. else { /* contiguous in window */
  15497. from += wnext - op;
  15498. if (op < len) { /* some from window */
  15499. len -= op;
  15500. do {
  15501. output[_out++] = s_window[from++];
  15502. } while (--op);
  15503. from = _out - dist; /* rest from output */
  15504. from_source = output;
  15505. }
  15506. }
  15507. while (len > 2) {
  15508. output[_out++] = from_source[from++];
  15509. output[_out++] = from_source[from++];
  15510. output[_out++] = from_source[from++];
  15511. len -= 3;
  15512. }
  15513. if (len) {
  15514. output[_out++] = from_source[from++];
  15515. if (len > 1) {
  15516. output[_out++] = from_source[from++];
  15517. }
  15518. }
  15519. }
  15520. else {
  15521. from = _out - dist; /* copy direct from output */
  15522. do { /* minimum length is three */
  15523. output[_out++] = output[from++];
  15524. output[_out++] = output[from++];
  15525. output[_out++] = output[from++];
  15526. len -= 3;
  15527. } while (len > 2);
  15528. if (len) {
  15529. output[_out++] = output[from++];
  15530. if (len > 1) {
  15531. output[_out++] = output[from++];
  15532. }
  15533. }
  15534. }
  15535. }
  15536. else if ((op & 64) === 0) { /* 2nd level distance code */
  15537. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15538. continue dodist;
  15539. }
  15540. else {
  15541. strm.msg = 'invalid distance code';
  15542. state.mode = BAD;
  15543. break top;
  15544. }
  15545. break; // need to emulate goto via "continue"
  15546. }
  15547. }
  15548. else if ((op & 64) === 0) { /* 2nd level length code */
  15549. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15550. continue dolen;
  15551. }
  15552. else if (op & 32) { /* end-of-block */
  15553. //Tracevv((stderr, "inflate: end of block\n"));
  15554. state.mode = TYPE;
  15555. break top;
  15556. }
  15557. else {
  15558. strm.msg = 'invalid literal/length code';
  15559. state.mode = BAD;
  15560. break top;
  15561. }
  15562. break; // need to emulate goto via "continue"
  15563. }
  15564. } while (_in < last && _out < end);
  15565. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  15566. len = bits >> 3;
  15567. _in -= len;
  15568. bits -= len << 3;
  15569. hold &= (1 << bits) - 1;
  15570. /* update state and return */
  15571. strm.next_in = _in;
  15572. strm.next_out = _out;
  15573. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  15574. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  15575. state.hold = hold;
  15576. state.bits = bits;
  15577. return;
  15578. };
  15579. },{}],59:[function(require,module,exports){
  15580. 'use strict';
  15581. var utils = require('../utils/common');
  15582. var adler32 = require('./adler32');
  15583. var crc32 = require('./crc32');
  15584. var inflate_fast = require('./inffast');
  15585. var inflate_table = require('./inftrees');
  15586. var CODES = 0;
  15587. var LENS = 1;
  15588. var DISTS = 2;
  15589. /* Public constants ==========================================================*/
  15590. /* ===========================================================================*/
  15591. /* Allowed flush values; see deflate() and inflate() below for details */
  15592. //var Z_NO_FLUSH = 0;
  15593. //var Z_PARTIAL_FLUSH = 1;
  15594. //var Z_SYNC_FLUSH = 2;
  15595. //var Z_FULL_FLUSH = 3;
  15596. var Z_FINISH = 4;
  15597. var Z_BLOCK = 5;
  15598. var Z_TREES = 6;
  15599. /* Return codes for the compression/decompression functions. Negative values
  15600. * are errors, positive values are used for special but normal events.
  15601. */
  15602. var Z_OK = 0;
  15603. var Z_STREAM_END = 1;
  15604. var Z_NEED_DICT = 2;
  15605. //var Z_ERRNO = -1;
  15606. var Z_STREAM_ERROR = -2;
  15607. var Z_DATA_ERROR = -3;
  15608. var Z_MEM_ERROR = -4;
  15609. var Z_BUF_ERROR = -5;
  15610. //var Z_VERSION_ERROR = -6;
  15611. /* The deflate compression method */
  15612. var Z_DEFLATED = 8;
  15613. /* STATES ====================================================================*/
  15614. /* ===========================================================================*/
  15615. var HEAD = 1; /* i: waiting for magic header */
  15616. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  15617. var TIME = 3; /* i: waiting for modification time (gzip) */
  15618. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  15619. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  15620. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  15621. var NAME = 7; /* i: waiting for end of file name (gzip) */
  15622. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  15623. var HCRC = 9; /* i: waiting for header crc (gzip) */
  15624. var DICTID = 10; /* i: waiting for dictionary check value */
  15625. var DICT = 11; /* waiting for inflateSetDictionary() call */
  15626. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15627. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  15628. var STORED = 14; /* i: waiting for stored size (length and complement) */
  15629. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  15630. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  15631. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  15632. var LENLENS = 18; /* i: waiting for code length code lengths */
  15633. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  15634. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  15635. var LEN = 21; /* i: waiting for length/lit/eob code */
  15636. var LENEXT = 22; /* i: waiting for length extra bits */
  15637. var DIST = 23; /* i: waiting for distance code */
  15638. var DISTEXT = 24; /* i: waiting for distance extra bits */
  15639. var MATCH = 25; /* o: waiting for output space to copy string */
  15640. var LIT = 26; /* o: waiting for output space to write literal */
  15641. var CHECK = 27; /* i: waiting for 32-bit check value */
  15642. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  15643. var DONE = 29; /* finished check, done -- remain here until reset */
  15644. var BAD = 30; /* got a data error -- remain here until reset */
  15645. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  15646. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  15647. /* ===========================================================================*/
  15648. var ENOUGH_LENS = 852;
  15649. var ENOUGH_DISTS = 592;
  15650. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15651. var MAX_WBITS = 15;
  15652. /* 32K LZ77 window */
  15653. var DEF_WBITS = MAX_WBITS;
  15654. function ZSWAP32(q) {
  15655. return (((q >>> 24) & 0xff) +
  15656. ((q >>> 8) & 0xff00) +
  15657. ((q & 0xff00) << 8) +
  15658. ((q & 0xff) << 24));
  15659. }
  15660. function InflateState() {
  15661. this.mode = 0; /* current inflate mode */
  15662. this.last = false; /* true if processing last block */
  15663. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15664. this.havedict = false; /* true if dictionary provided */
  15665. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  15666. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  15667. this.check = 0; /* protected copy of check value */
  15668. this.total = 0; /* protected copy of output count */
  15669. // TODO: may be {}
  15670. this.head = null; /* where to save gzip header information */
  15671. /* sliding window */
  15672. this.wbits = 0; /* log base 2 of requested window size */
  15673. this.wsize = 0; /* window size or zero if not using window */
  15674. this.whave = 0; /* valid bytes in the window */
  15675. this.wnext = 0; /* window write index */
  15676. this.window = null; /* allocated sliding window, if needed */
  15677. /* bit accumulator */
  15678. this.hold = 0; /* input bit accumulator */
  15679. this.bits = 0; /* number of bits in "in" */
  15680. /* for string and stored block copying */
  15681. this.length = 0; /* literal or length of data to copy */
  15682. this.offset = 0; /* distance back to copy string from */
  15683. /* for table and code decoding */
  15684. this.extra = 0; /* extra bits needed */
  15685. /* fixed and dynamic code tables */
  15686. this.lencode = null; /* starting table for length/literal codes */
  15687. this.distcode = null; /* starting table for distance codes */
  15688. this.lenbits = 0; /* index bits for lencode */
  15689. this.distbits = 0; /* index bits for distcode */
  15690. /* dynamic table building */
  15691. this.ncode = 0; /* number of code length code lengths */
  15692. this.nlen = 0; /* number of length code lengths */
  15693. this.ndist = 0; /* number of distance code lengths */
  15694. this.have = 0; /* number of code lengths in lens[] */
  15695. this.next = null; /* next available space in codes[] */
  15696. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  15697. this.work = new utils.Buf16(288); /* work area for code table building */
  15698. /*
  15699. because we don't have pointers in js, we use lencode and distcode directly
  15700. as buffers so we don't need codes
  15701. */
  15702. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  15703. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  15704. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  15705. this.sane = 0; /* if false, allow invalid distance too far */
  15706. this.back = 0; /* bits back of last unprocessed length/lit */
  15707. this.was = 0; /* initial length of match */
  15708. }
  15709. function inflateResetKeep(strm) {
  15710. var state;
  15711. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15712. state = strm.state;
  15713. strm.total_in = strm.total_out = state.total = 0;
  15714. strm.msg = ''; /*Z_NULL*/
  15715. if (state.wrap) { /* to support ill-conceived Java test suite */
  15716. strm.adler = state.wrap & 1;
  15717. }
  15718. state.mode = HEAD;
  15719. state.last = 0;
  15720. state.havedict = 0;
  15721. state.dmax = 32768;
  15722. state.head = null/*Z_NULL*/;
  15723. state.hold = 0;
  15724. state.bits = 0;
  15725. //state.lencode = state.distcode = state.next = state.codes;
  15726. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  15727. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  15728. state.sane = 1;
  15729. state.back = -1;
  15730. //Tracev((stderr, "inflate: reset\n"));
  15731. return Z_OK;
  15732. }
  15733. function inflateReset(strm) {
  15734. var state;
  15735. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15736. state = strm.state;
  15737. state.wsize = 0;
  15738. state.whave = 0;
  15739. state.wnext = 0;
  15740. return inflateResetKeep(strm);
  15741. }
  15742. function inflateReset2(strm, windowBits) {
  15743. var wrap;
  15744. var state;
  15745. /* get the state */
  15746. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15747. state = strm.state;
  15748. /* extract wrap request from windowBits parameter */
  15749. if (windowBits < 0) {
  15750. wrap = 0;
  15751. windowBits = -windowBits;
  15752. }
  15753. else {
  15754. wrap = (windowBits >> 4) + 1;
  15755. if (windowBits < 48) {
  15756. windowBits &= 15;
  15757. }
  15758. }
  15759. /* set number of window bits, free window if different */
  15760. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  15761. return Z_STREAM_ERROR;
  15762. }
  15763. if (state.window !== null && state.wbits !== windowBits) {
  15764. state.window = null;
  15765. }
  15766. /* update state and reset the rest of it */
  15767. state.wrap = wrap;
  15768. state.wbits = windowBits;
  15769. return inflateReset(strm);
  15770. }
  15771. function inflateInit2(strm, windowBits) {
  15772. var ret;
  15773. var state;
  15774. if (!strm) { return Z_STREAM_ERROR; }
  15775. //strm.msg = Z_NULL; /* in case we return an error */
  15776. state = new InflateState();
  15777. //if (state === Z_NULL) return Z_MEM_ERROR;
  15778. //Tracev((stderr, "inflate: allocated\n"));
  15779. strm.state = state;
  15780. state.window = null/*Z_NULL*/;
  15781. ret = inflateReset2(strm, windowBits);
  15782. if (ret !== Z_OK) {
  15783. strm.state = null/*Z_NULL*/;
  15784. }
  15785. return ret;
  15786. }
  15787. function inflateInit(strm) {
  15788. return inflateInit2(strm, DEF_WBITS);
  15789. }
  15790. /*
  15791. Return state with length and distance decoding tables and index sizes set to
  15792. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  15793. If BUILDFIXED is defined, then instead this routine builds the tables the
  15794. first time it's called, and returns those tables the first time and
  15795. thereafter. This reduces the size of the code by about 2K bytes, in
  15796. exchange for a little execution time. However, BUILDFIXED should not be
  15797. used for threaded applications, since the rewriting of the tables and virgin
  15798. may not be thread-safe.
  15799. */
  15800. var virgin = true;
  15801. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  15802. function fixedtables(state) {
  15803. /* build fixed huffman tables if first call (may not be thread safe) */
  15804. if (virgin) {
  15805. var sym;
  15806. lenfix = new utils.Buf32(512);
  15807. distfix = new utils.Buf32(32);
  15808. /* literal/length table */
  15809. sym = 0;
  15810. while (sym < 144) { state.lens[sym++] = 8; }
  15811. while (sym < 256) { state.lens[sym++] = 9; }
  15812. while (sym < 280) { state.lens[sym++] = 7; }
  15813. while (sym < 288) { state.lens[sym++] = 8; }
  15814. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  15815. /* distance table */
  15816. sym = 0;
  15817. while (sym < 32) { state.lens[sym++] = 5; }
  15818. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  15819. /* do this just once */
  15820. virgin = false;
  15821. }
  15822. state.lencode = lenfix;
  15823. state.lenbits = 9;
  15824. state.distcode = distfix;
  15825. state.distbits = 5;
  15826. }
  15827. /*
  15828. Update the window with the last wsize (normally 32K) bytes written before
  15829. returning. If window does not exist yet, create it. This is only called
  15830. when a window is already in use, or when output has been written during this
  15831. inflate call, but the end of the deflate stream has not been reached yet.
  15832. It is also called to create a window for dictionary data when a dictionary
  15833. is loaded.
  15834. Providing output buffers larger than 32K to inflate() should provide a speed
  15835. advantage, since only the last 32K of output is copied to the sliding window
  15836. upon return from inflate(), and since all distances after the first 32K of
  15837. output will fall in the output data, making match copies simpler and faster.
  15838. The advantage may be dependent on the size of the processor's data caches.
  15839. */
  15840. function updatewindow(strm, src, end, copy) {
  15841. var dist;
  15842. var state = strm.state;
  15843. /* if it hasn't been done already, allocate space for the window */
  15844. if (state.window === null) {
  15845. state.wsize = 1 << state.wbits;
  15846. state.wnext = 0;
  15847. state.whave = 0;
  15848. state.window = new utils.Buf8(state.wsize);
  15849. }
  15850. /* copy state->wsize or less output bytes into the circular window */
  15851. if (copy >= state.wsize) {
  15852. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  15853. state.wnext = 0;
  15854. state.whave = state.wsize;
  15855. }
  15856. else {
  15857. dist = state.wsize - state.wnext;
  15858. if (dist > copy) {
  15859. dist = copy;
  15860. }
  15861. //zmemcpy(state->window + state->wnext, end - copy, dist);
  15862. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  15863. copy -= dist;
  15864. if (copy) {
  15865. //zmemcpy(state->window, end - copy, copy);
  15866. utils.arraySet(state.window,src, end - copy, copy, 0);
  15867. state.wnext = copy;
  15868. state.whave = state.wsize;
  15869. }
  15870. else {
  15871. state.wnext += dist;
  15872. if (state.wnext === state.wsize) { state.wnext = 0; }
  15873. if (state.whave < state.wsize) { state.whave += dist; }
  15874. }
  15875. }
  15876. return 0;
  15877. }
  15878. function inflate(strm, flush) {
  15879. var state;
  15880. var input, output; // input/output buffers
  15881. var next; /* next input INDEX */
  15882. var put; /* next output INDEX */
  15883. var have, left; /* available input and output */
  15884. var hold; /* bit buffer */
  15885. var bits; /* bits in bit buffer */
  15886. var _in, _out; /* save starting available input and output */
  15887. var copy; /* number of stored or match bytes to copy */
  15888. var from; /* where to copy match bytes from */
  15889. var from_source;
  15890. var here = 0; /* current decoding table entry */
  15891. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  15892. //var last; /* parent table entry */
  15893. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  15894. var len; /* length to copy for repeats, bits to drop */
  15895. var ret; /* return code */
  15896. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  15897. var opts;
  15898. var n; // temporary var for NEED_BITS
  15899. var order = /* permutation of code lengths */
  15900. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  15901. if (!strm || !strm.state || !strm.output ||
  15902. (!strm.input && strm.avail_in !== 0)) {
  15903. return Z_STREAM_ERROR;
  15904. }
  15905. state = strm.state;
  15906. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  15907. //--- LOAD() ---
  15908. put = strm.next_out;
  15909. output = strm.output;
  15910. left = strm.avail_out;
  15911. next = strm.next_in;
  15912. input = strm.input;
  15913. have = strm.avail_in;
  15914. hold = state.hold;
  15915. bits = state.bits;
  15916. //---
  15917. _in = have;
  15918. _out = left;
  15919. ret = Z_OK;
  15920. inf_leave: // goto emulation
  15921. for (;;) {
  15922. switch (state.mode) {
  15923. case HEAD:
  15924. if (state.wrap === 0) {
  15925. state.mode = TYPEDO;
  15926. break;
  15927. }
  15928. //=== NEEDBITS(16);
  15929. while (bits < 16) {
  15930. if (have === 0) { break inf_leave; }
  15931. have--;
  15932. hold += input[next++] << bits;
  15933. bits += 8;
  15934. }
  15935. //===//
  15936. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  15937. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  15938. //=== CRC2(state.check, hold);
  15939. hbuf[0] = hold & 0xff;
  15940. hbuf[1] = (hold >>> 8) & 0xff;
  15941. state.check = crc32(state.check, hbuf, 2, 0);
  15942. //===//
  15943. //=== INITBITS();
  15944. hold = 0;
  15945. bits = 0;
  15946. //===//
  15947. state.mode = FLAGS;
  15948. break;
  15949. }
  15950. state.flags = 0; /* expect zlib header */
  15951. if (state.head) {
  15952. state.head.done = false;
  15953. }
  15954. if (!(state.wrap & 1) || /* check if zlib header allowed */
  15955. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  15956. strm.msg = 'incorrect header check';
  15957. state.mode = BAD;
  15958. break;
  15959. }
  15960. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  15961. strm.msg = 'unknown compression method';
  15962. state.mode = BAD;
  15963. break;
  15964. }
  15965. //--- DROPBITS(4) ---//
  15966. hold >>>= 4;
  15967. bits -= 4;
  15968. //---//
  15969. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  15970. if (state.wbits === 0) {
  15971. state.wbits = len;
  15972. }
  15973. else if (len > state.wbits) {
  15974. strm.msg = 'invalid window size';
  15975. state.mode = BAD;
  15976. break;
  15977. }
  15978. state.dmax = 1 << len;
  15979. //Tracev((stderr, "inflate: zlib header ok\n"));
  15980. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  15981. state.mode = hold & 0x200 ? DICTID : TYPE;
  15982. //=== INITBITS();
  15983. hold = 0;
  15984. bits = 0;
  15985. //===//
  15986. break;
  15987. case FLAGS:
  15988. //=== NEEDBITS(16); */
  15989. while (bits < 16) {
  15990. if (have === 0) { break inf_leave; }
  15991. have--;
  15992. hold += input[next++] << bits;
  15993. bits += 8;
  15994. }
  15995. //===//
  15996. state.flags = hold;
  15997. if ((state.flags & 0xff) !== Z_DEFLATED) {
  15998. strm.msg = 'unknown compression method';
  15999. state.mode = BAD;
  16000. break;
  16001. }
  16002. if (state.flags & 0xe000) {
  16003. strm.msg = 'unknown header flags set';
  16004. state.mode = BAD;
  16005. break;
  16006. }
  16007. if (state.head) {
  16008. state.head.text = ((hold >> 8) & 1);
  16009. }
  16010. if (state.flags & 0x0200) {
  16011. //=== CRC2(state.check, hold);
  16012. hbuf[0] = hold & 0xff;
  16013. hbuf[1] = (hold >>> 8) & 0xff;
  16014. state.check = crc32(state.check, hbuf, 2, 0);
  16015. //===//
  16016. }
  16017. //=== INITBITS();
  16018. hold = 0;
  16019. bits = 0;
  16020. //===//
  16021. state.mode = TIME;
  16022. /* falls through */
  16023. case TIME:
  16024. //=== NEEDBITS(32); */
  16025. while (bits < 32) {
  16026. if (have === 0) { break inf_leave; }
  16027. have--;
  16028. hold += input[next++] << bits;
  16029. bits += 8;
  16030. }
  16031. //===//
  16032. if (state.head) {
  16033. state.head.time = hold;
  16034. }
  16035. if (state.flags & 0x0200) {
  16036. //=== CRC4(state.check, hold)
  16037. hbuf[0] = hold & 0xff;
  16038. hbuf[1] = (hold >>> 8) & 0xff;
  16039. hbuf[2] = (hold >>> 16) & 0xff;
  16040. hbuf[3] = (hold >>> 24) & 0xff;
  16041. state.check = crc32(state.check, hbuf, 4, 0);
  16042. //===
  16043. }
  16044. //=== INITBITS();
  16045. hold = 0;
  16046. bits = 0;
  16047. //===//
  16048. state.mode = OS;
  16049. /* falls through */
  16050. case OS:
  16051. //=== NEEDBITS(16); */
  16052. while (bits < 16) {
  16053. if (have === 0) { break inf_leave; }
  16054. have--;
  16055. hold += input[next++] << bits;
  16056. bits += 8;
  16057. }
  16058. //===//
  16059. if (state.head) {
  16060. state.head.xflags = (hold & 0xff);
  16061. state.head.os = (hold >> 8);
  16062. }
  16063. if (state.flags & 0x0200) {
  16064. //=== CRC2(state.check, hold);
  16065. hbuf[0] = hold & 0xff;
  16066. hbuf[1] = (hold >>> 8) & 0xff;
  16067. state.check = crc32(state.check, hbuf, 2, 0);
  16068. //===//
  16069. }
  16070. //=== INITBITS();
  16071. hold = 0;
  16072. bits = 0;
  16073. //===//
  16074. state.mode = EXLEN;
  16075. /* falls through */
  16076. case EXLEN:
  16077. if (state.flags & 0x0400) {
  16078. //=== NEEDBITS(16); */
  16079. while (bits < 16) {
  16080. if (have === 0) { break inf_leave; }
  16081. have--;
  16082. hold += input[next++] << bits;
  16083. bits += 8;
  16084. }
  16085. //===//
  16086. state.length = hold;
  16087. if (state.head) {
  16088. state.head.extra_len = hold;
  16089. }
  16090. if (state.flags & 0x0200) {
  16091. //=== CRC2(state.check, hold);
  16092. hbuf[0] = hold & 0xff;
  16093. hbuf[1] = (hold >>> 8) & 0xff;
  16094. state.check = crc32(state.check, hbuf, 2, 0);
  16095. //===//
  16096. }
  16097. //=== INITBITS();
  16098. hold = 0;
  16099. bits = 0;
  16100. //===//
  16101. }
  16102. else if (state.head) {
  16103. state.head.extra = null/*Z_NULL*/;
  16104. }
  16105. state.mode = EXTRA;
  16106. /* falls through */
  16107. case EXTRA:
  16108. if (state.flags & 0x0400) {
  16109. copy = state.length;
  16110. if (copy > have) { copy = have; }
  16111. if (copy) {
  16112. if (state.head) {
  16113. len = state.head.extra_len - state.length;
  16114. if (!state.head.extra) {
  16115. // Use untyped array for more conveniend processing later
  16116. state.head.extra = new Array(state.head.extra_len);
  16117. }
  16118. utils.arraySet(
  16119. state.head.extra,
  16120. input,
  16121. next,
  16122. // extra field is limited to 65536 bytes
  16123. // - no need for additional size check
  16124. copy,
  16125. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  16126. len
  16127. );
  16128. //zmemcpy(state.head.extra + len, next,
  16129. // len + copy > state.head.extra_max ?
  16130. // state.head.extra_max - len : copy);
  16131. }
  16132. if (state.flags & 0x0200) {
  16133. state.check = crc32(state.check, input, copy, next);
  16134. }
  16135. have -= copy;
  16136. next += copy;
  16137. state.length -= copy;
  16138. }
  16139. if (state.length) { break inf_leave; }
  16140. }
  16141. state.length = 0;
  16142. state.mode = NAME;
  16143. /* falls through */
  16144. case NAME:
  16145. if (state.flags & 0x0800) {
  16146. if (have === 0) { break inf_leave; }
  16147. copy = 0;
  16148. do {
  16149. // TODO: 2 or 1 bytes?
  16150. len = input[next + copy++];
  16151. /* use constant limit because in js we should not preallocate memory */
  16152. if (state.head && len &&
  16153. (state.length < 65536 /*state.head.name_max*/)) {
  16154. state.head.name += String.fromCharCode(len);
  16155. }
  16156. } while (len && copy < have);
  16157. if (state.flags & 0x0200) {
  16158. state.check = crc32(state.check, input, copy, next);
  16159. }
  16160. have -= copy;
  16161. next += copy;
  16162. if (len) { break inf_leave; }
  16163. }
  16164. else if (state.head) {
  16165. state.head.name = null;
  16166. }
  16167. state.length = 0;
  16168. state.mode = COMMENT;
  16169. /* falls through */
  16170. case COMMENT:
  16171. if (state.flags & 0x1000) {
  16172. if (have === 0) { break inf_leave; }
  16173. copy = 0;
  16174. do {
  16175. len = input[next + copy++];
  16176. /* use constant limit because in js we should not preallocate memory */
  16177. if (state.head && len &&
  16178. (state.length < 65536 /*state.head.comm_max*/)) {
  16179. state.head.comment += String.fromCharCode(len);
  16180. }
  16181. } while (len && copy < have);
  16182. if (state.flags & 0x0200) {
  16183. state.check = crc32(state.check, input, copy, next);
  16184. }
  16185. have -= copy;
  16186. next += copy;
  16187. if (len) { break inf_leave; }
  16188. }
  16189. else if (state.head) {
  16190. state.head.comment = null;
  16191. }
  16192. state.mode = HCRC;
  16193. /* falls through */
  16194. case HCRC:
  16195. if (state.flags & 0x0200) {
  16196. //=== NEEDBITS(16); */
  16197. while (bits < 16) {
  16198. if (have === 0) { break inf_leave; }
  16199. have--;
  16200. hold += input[next++] << bits;
  16201. bits += 8;
  16202. }
  16203. //===//
  16204. if (hold !== (state.check & 0xffff)) {
  16205. strm.msg = 'header crc mismatch';
  16206. state.mode = BAD;
  16207. break;
  16208. }
  16209. //=== INITBITS();
  16210. hold = 0;
  16211. bits = 0;
  16212. //===//
  16213. }
  16214. if (state.head) {
  16215. state.head.hcrc = ((state.flags >> 9) & 1);
  16216. state.head.done = true;
  16217. }
  16218. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16219. state.mode = TYPE;
  16220. break;
  16221. case DICTID:
  16222. //=== NEEDBITS(32); */
  16223. while (bits < 32) {
  16224. if (have === 0) { break inf_leave; }
  16225. have--;
  16226. hold += input[next++] << bits;
  16227. bits += 8;
  16228. }
  16229. //===//
  16230. strm.adler = state.check = ZSWAP32(hold);
  16231. //=== INITBITS();
  16232. hold = 0;
  16233. bits = 0;
  16234. //===//
  16235. state.mode = DICT;
  16236. /* falls through */
  16237. case DICT:
  16238. if (state.havedict === 0) {
  16239. //--- RESTORE() ---
  16240. strm.next_out = put;
  16241. strm.avail_out = left;
  16242. strm.next_in = next;
  16243. strm.avail_in = have;
  16244. state.hold = hold;
  16245. state.bits = bits;
  16246. //---
  16247. return Z_NEED_DICT;
  16248. }
  16249. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16250. state.mode = TYPE;
  16251. /* falls through */
  16252. case TYPE:
  16253. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16254. /* falls through */
  16255. case TYPEDO:
  16256. if (state.last) {
  16257. //--- BYTEBITS() ---//
  16258. hold >>>= bits & 7;
  16259. bits -= bits & 7;
  16260. //---//
  16261. state.mode = CHECK;
  16262. break;
  16263. }
  16264. //=== NEEDBITS(3); */
  16265. while (bits < 3) {
  16266. if (have === 0) { break inf_leave; }
  16267. have--;
  16268. hold += input[next++] << bits;
  16269. bits += 8;
  16270. }
  16271. //===//
  16272. state.last = (hold & 0x01)/*BITS(1)*/;
  16273. //--- DROPBITS(1) ---//
  16274. hold >>>= 1;
  16275. bits -= 1;
  16276. //---//
  16277. switch ((hold & 0x03)/*BITS(2)*/) {
  16278. case 0: /* stored block */
  16279. //Tracev((stderr, "inflate: stored block%s\n",
  16280. // state.last ? " (last)" : ""));
  16281. state.mode = STORED;
  16282. break;
  16283. case 1: /* fixed block */
  16284. fixedtables(state);
  16285. //Tracev((stderr, "inflate: fixed codes block%s\n",
  16286. // state.last ? " (last)" : ""));
  16287. state.mode = LEN_; /* decode codes */
  16288. if (flush === Z_TREES) {
  16289. //--- DROPBITS(2) ---//
  16290. hold >>>= 2;
  16291. bits -= 2;
  16292. //---//
  16293. break inf_leave;
  16294. }
  16295. break;
  16296. case 2: /* dynamic block */
  16297. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  16298. // state.last ? " (last)" : ""));
  16299. state.mode = TABLE;
  16300. break;
  16301. case 3:
  16302. strm.msg = 'invalid block type';
  16303. state.mode = BAD;
  16304. }
  16305. //--- DROPBITS(2) ---//
  16306. hold >>>= 2;
  16307. bits -= 2;
  16308. //---//
  16309. break;
  16310. case STORED:
  16311. //--- BYTEBITS() ---// /* go to byte boundary */
  16312. hold >>>= bits & 7;
  16313. bits -= bits & 7;
  16314. //---//
  16315. //=== NEEDBITS(32); */
  16316. while (bits < 32) {
  16317. if (have === 0) { break inf_leave; }
  16318. have--;
  16319. hold += input[next++] << bits;
  16320. bits += 8;
  16321. }
  16322. //===//
  16323. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  16324. strm.msg = 'invalid stored block lengths';
  16325. state.mode = BAD;
  16326. break;
  16327. }
  16328. state.length = hold & 0xffff;
  16329. //Tracev((stderr, "inflate: stored length %u\n",
  16330. // state.length));
  16331. //=== INITBITS();
  16332. hold = 0;
  16333. bits = 0;
  16334. //===//
  16335. state.mode = COPY_;
  16336. if (flush === Z_TREES) { break inf_leave; }
  16337. /* falls through */
  16338. case COPY_:
  16339. state.mode = COPY;
  16340. /* falls through */
  16341. case COPY:
  16342. copy = state.length;
  16343. if (copy) {
  16344. if (copy > have) { copy = have; }
  16345. if (copy > left) { copy = left; }
  16346. if (copy === 0) { break inf_leave; }
  16347. //--- zmemcpy(put, next, copy); ---
  16348. utils.arraySet(output, input, next, copy, put);
  16349. //---//
  16350. have -= copy;
  16351. next += copy;
  16352. left -= copy;
  16353. put += copy;
  16354. state.length -= copy;
  16355. break;
  16356. }
  16357. //Tracev((stderr, "inflate: stored end\n"));
  16358. state.mode = TYPE;
  16359. break;
  16360. case TABLE:
  16361. //=== NEEDBITS(14); */
  16362. while (bits < 14) {
  16363. if (have === 0) { break inf_leave; }
  16364. have--;
  16365. hold += input[next++] << bits;
  16366. bits += 8;
  16367. }
  16368. //===//
  16369. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  16370. //--- DROPBITS(5) ---//
  16371. hold >>>= 5;
  16372. bits -= 5;
  16373. //---//
  16374. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  16375. //--- DROPBITS(5) ---//
  16376. hold >>>= 5;
  16377. bits -= 5;
  16378. //---//
  16379. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  16380. //--- DROPBITS(4) ---//
  16381. hold >>>= 4;
  16382. bits -= 4;
  16383. //---//
  16384. //#ifndef PKZIP_BUG_WORKAROUND
  16385. if (state.nlen > 286 || state.ndist > 30) {
  16386. strm.msg = 'too many length or distance symbols';
  16387. state.mode = BAD;
  16388. break;
  16389. }
  16390. //#endif
  16391. //Tracev((stderr, "inflate: table sizes ok\n"));
  16392. state.have = 0;
  16393. state.mode = LENLENS;
  16394. /* falls through */
  16395. case LENLENS:
  16396. while (state.have < state.ncode) {
  16397. //=== NEEDBITS(3);
  16398. while (bits < 3) {
  16399. if (have === 0) { break inf_leave; }
  16400. have--;
  16401. hold += input[next++] << bits;
  16402. bits += 8;
  16403. }
  16404. //===//
  16405. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  16406. //--- DROPBITS(3) ---//
  16407. hold >>>= 3;
  16408. bits -= 3;
  16409. //---//
  16410. }
  16411. while (state.have < 19) {
  16412. state.lens[order[state.have++]] = 0;
  16413. }
  16414. // We have separate tables & no pointers. 2 commented lines below not needed.
  16415. //state.next = state.codes;
  16416. //state.lencode = state.next;
  16417. // Switch to use dynamic table
  16418. state.lencode = state.lendyn;
  16419. state.lenbits = 7;
  16420. opts = {bits: state.lenbits};
  16421. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  16422. state.lenbits = opts.bits;
  16423. if (ret) {
  16424. strm.msg = 'invalid code lengths set';
  16425. state.mode = BAD;
  16426. break;
  16427. }
  16428. //Tracev((stderr, "inflate: code lengths ok\n"));
  16429. state.have = 0;
  16430. state.mode = CODELENS;
  16431. /* falls through */
  16432. case CODELENS:
  16433. while (state.have < state.nlen + state.ndist) {
  16434. for (;;) {
  16435. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  16436. here_bits = here >>> 24;
  16437. here_op = (here >>> 16) & 0xff;
  16438. here_val = here & 0xffff;
  16439. if ((here_bits) <= bits) { break; }
  16440. //--- PULLBYTE() ---//
  16441. if (have === 0) { break inf_leave; }
  16442. have--;
  16443. hold += input[next++] << bits;
  16444. bits += 8;
  16445. //---//
  16446. }
  16447. if (here_val < 16) {
  16448. //--- DROPBITS(here.bits) ---//
  16449. hold >>>= here_bits;
  16450. bits -= here_bits;
  16451. //---//
  16452. state.lens[state.have++] = here_val;
  16453. }
  16454. else {
  16455. if (here_val === 16) {
  16456. //=== NEEDBITS(here.bits + 2);
  16457. n = here_bits + 2;
  16458. while (bits < n) {
  16459. if (have === 0) { break inf_leave; }
  16460. have--;
  16461. hold += input[next++] << bits;
  16462. bits += 8;
  16463. }
  16464. //===//
  16465. //--- DROPBITS(here.bits) ---//
  16466. hold >>>= here_bits;
  16467. bits -= here_bits;
  16468. //---//
  16469. if (state.have === 0) {
  16470. strm.msg = 'invalid bit length repeat';
  16471. state.mode = BAD;
  16472. break;
  16473. }
  16474. len = state.lens[state.have - 1];
  16475. copy = 3 + (hold & 0x03);//BITS(2);
  16476. //--- DROPBITS(2) ---//
  16477. hold >>>= 2;
  16478. bits -= 2;
  16479. //---//
  16480. }
  16481. else if (here_val === 17) {
  16482. //=== NEEDBITS(here.bits + 3);
  16483. n = here_bits + 3;
  16484. while (bits < n) {
  16485. if (have === 0) { break inf_leave; }
  16486. have--;
  16487. hold += input[next++] << bits;
  16488. bits += 8;
  16489. }
  16490. //===//
  16491. //--- DROPBITS(here.bits) ---//
  16492. hold >>>= here_bits;
  16493. bits -= here_bits;
  16494. //---//
  16495. len = 0;
  16496. copy = 3 + (hold & 0x07);//BITS(3);
  16497. //--- DROPBITS(3) ---//
  16498. hold >>>= 3;
  16499. bits -= 3;
  16500. //---//
  16501. }
  16502. else {
  16503. //=== NEEDBITS(here.bits + 7);
  16504. n = here_bits + 7;
  16505. while (bits < n) {
  16506. if (have === 0) { break inf_leave; }
  16507. have--;
  16508. hold += input[next++] << bits;
  16509. bits += 8;
  16510. }
  16511. //===//
  16512. //--- DROPBITS(here.bits) ---//
  16513. hold >>>= here_bits;
  16514. bits -= here_bits;
  16515. //---//
  16516. len = 0;
  16517. copy = 11 + (hold & 0x7f);//BITS(7);
  16518. //--- DROPBITS(7) ---//
  16519. hold >>>= 7;
  16520. bits -= 7;
  16521. //---//
  16522. }
  16523. if (state.have + copy > state.nlen + state.ndist) {
  16524. strm.msg = 'invalid bit length repeat';
  16525. state.mode = BAD;
  16526. break;
  16527. }
  16528. while (copy--) {
  16529. state.lens[state.have++] = len;
  16530. }
  16531. }
  16532. }
  16533. /* handle error breaks in while */
  16534. if (state.mode === BAD) { break; }
  16535. /* check for end-of-block code (better have one) */
  16536. if (state.lens[256] === 0) {
  16537. strm.msg = 'invalid code -- missing end-of-block';
  16538. state.mode = BAD;
  16539. break;
  16540. }
  16541. /* build code tables -- note: do not change the lenbits or distbits
  16542. values here (9 and 6) without reading the comments in inftrees.h
  16543. concerning the ENOUGH constants, which depend on those values */
  16544. state.lenbits = 9;
  16545. opts = {bits: state.lenbits};
  16546. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  16547. // We have separate tables & no pointers. 2 commented lines below not needed.
  16548. // state.next_index = opts.table_index;
  16549. state.lenbits = opts.bits;
  16550. // state.lencode = state.next;
  16551. if (ret) {
  16552. strm.msg = 'invalid literal/lengths set';
  16553. state.mode = BAD;
  16554. break;
  16555. }
  16556. state.distbits = 6;
  16557. //state.distcode.copy(state.codes);
  16558. // Switch to use dynamic table
  16559. state.distcode = state.distdyn;
  16560. opts = {bits: state.distbits};
  16561. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  16562. // We have separate tables & no pointers. 2 commented lines below not needed.
  16563. // state.next_index = opts.table_index;
  16564. state.distbits = opts.bits;
  16565. // state.distcode = state.next;
  16566. if (ret) {
  16567. strm.msg = 'invalid distances set';
  16568. state.mode = BAD;
  16569. break;
  16570. }
  16571. //Tracev((stderr, 'inflate: codes ok\n'));
  16572. state.mode = LEN_;
  16573. if (flush === Z_TREES) { break inf_leave; }
  16574. /* falls through */
  16575. case LEN_:
  16576. state.mode = LEN;
  16577. /* falls through */
  16578. case LEN:
  16579. if (have >= 6 && left >= 258) {
  16580. //--- RESTORE() ---
  16581. strm.next_out = put;
  16582. strm.avail_out = left;
  16583. strm.next_in = next;
  16584. strm.avail_in = have;
  16585. state.hold = hold;
  16586. state.bits = bits;
  16587. //---
  16588. inflate_fast(strm, _out);
  16589. //--- LOAD() ---
  16590. put = strm.next_out;
  16591. output = strm.output;
  16592. left = strm.avail_out;
  16593. next = strm.next_in;
  16594. input = strm.input;
  16595. have = strm.avail_in;
  16596. hold = state.hold;
  16597. bits = state.bits;
  16598. //---
  16599. if (state.mode === TYPE) {
  16600. state.back = -1;
  16601. }
  16602. break;
  16603. }
  16604. state.back = 0;
  16605. for (;;) {
  16606. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  16607. here_bits = here >>> 24;
  16608. here_op = (here >>> 16) & 0xff;
  16609. here_val = here & 0xffff;
  16610. if (here_bits <= bits) { break; }
  16611. //--- PULLBYTE() ---//
  16612. if (have === 0) { break inf_leave; }
  16613. have--;
  16614. hold += input[next++] << bits;
  16615. bits += 8;
  16616. //---//
  16617. }
  16618. if (here_op && (here_op & 0xf0) === 0) {
  16619. last_bits = here_bits;
  16620. last_op = here_op;
  16621. last_val = here_val;
  16622. for (;;) {
  16623. here = state.lencode[last_val +
  16624. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16625. here_bits = here >>> 24;
  16626. here_op = (here >>> 16) & 0xff;
  16627. here_val = here & 0xffff;
  16628. if ((last_bits + here_bits) <= bits) { break; }
  16629. //--- PULLBYTE() ---//
  16630. if (have === 0) { break inf_leave; }
  16631. have--;
  16632. hold += input[next++] << bits;
  16633. bits += 8;
  16634. //---//
  16635. }
  16636. //--- DROPBITS(last.bits) ---//
  16637. hold >>>= last_bits;
  16638. bits -= last_bits;
  16639. //---//
  16640. state.back += last_bits;
  16641. }
  16642. //--- DROPBITS(here.bits) ---//
  16643. hold >>>= here_bits;
  16644. bits -= here_bits;
  16645. //---//
  16646. state.back += here_bits;
  16647. state.length = here_val;
  16648. if (here_op === 0) {
  16649. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16650. // "inflate: literal '%c'\n" :
  16651. // "inflate: literal 0x%02x\n", here.val));
  16652. state.mode = LIT;
  16653. break;
  16654. }
  16655. if (here_op & 32) {
  16656. //Tracevv((stderr, "inflate: end of block\n"));
  16657. state.back = -1;
  16658. state.mode = TYPE;
  16659. break;
  16660. }
  16661. if (here_op & 64) {
  16662. strm.msg = 'invalid literal/length code';
  16663. state.mode = BAD;
  16664. break;
  16665. }
  16666. state.extra = here_op & 15;
  16667. state.mode = LENEXT;
  16668. /* falls through */
  16669. case LENEXT:
  16670. if (state.extra) {
  16671. //=== NEEDBITS(state.extra);
  16672. n = state.extra;
  16673. while (bits < n) {
  16674. if (have === 0) { break inf_leave; }
  16675. have--;
  16676. hold += input[next++] << bits;
  16677. bits += 8;
  16678. }
  16679. //===//
  16680. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16681. //--- DROPBITS(state.extra) ---//
  16682. hold >>>= state.extra;
  16683. bits -= state.extra;
  16684. //---//
  16685. state.back += state.extra;
  16686. }
  16687. //Tracevv((stderr, "inflate: length %u\n", state.length));
  16688. state.was = state.length;
  16689. state.mode = DIST;
  16690. /* falls through */
  16691. case DIST:
  16692. for (;;) {
  16693. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  16694. here_bits = here >>> 24;
  16695. here_op = (here >>> 16) & 0xff;
  16696. here_val = here & 0xffff;
  16697. if ((here_bits) <= bits) { break; }
  16698. //--- PULLBYTE() ---//
  16699. if (have === 0) { break inf_leave; }
  16700. have--;
  16701. hold += input[next++] << bits;
  16702. bits += 8;
  16703. //---//
  16704. }
  16705. if ((here_op & 0xf0) === 0) {
  16706. last_bits = here_bits;
  16707. last_op = here_op;
  16708. last_val = here_val;
  16709. for (;;) {
  16710. here = state.distcode[last_val +
  16711. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16712. here_bits = here >>> 24;
  16713. here_op = (here >>> 16) & 0xff;
  16714. here_val = here & 0xffff;
  16715. if ((last_bits + here_bits) <= bits) { break; }
  16716. //--- PULLBYTE() ---//
  16717. if (have === 0) { break inf_leave; }
  16718. have--;
  16719. hold += input[next++] << bits;
  16720. bits += 8;
  16721. //---//
  16722. }
  16723. //--- DROPBITS(last.bits) ---//
  16724. hold >>>= last_bits;
  16725. bits -= last_bits;
  16726. //---//
  16727. state.back += last_bits;
  16728. }
  16729. //--- DROPBITS(here.bits) ---//
  16730. hold >>>= here_bits;
  16731. bits -= here_bits;
  16732. //---//
  16733. state.back += here_bits;
  16734. if (here_op & 64) {
  16735. strm.msg = 'invalid distance code';
  16736. state.mode = BAD;
  16737. break;
  16738. }
  16739. state.offset = here_val;
  16740. state.extra = (here_op) & 15;
  16741. state.mode = DISTEXT;
  16742. /* falls through */
  16743. case DISTEXT:
  16744. if (state.extra) {
  16745. //=== NEEDBITS(state.extra);
  16746. n = state.extra;
  16747. while (bits < n) {
  16748. if (have === 0) { break inf_leave; }
  16749. have--;
  16750. hold += input[next++] << bits;
  16751. bits += 8;
  16752. }
  16753. //===//
  16754. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16755. //--- DROPBITS(state.extra) ---//
  16756. hold >>>= state.extra;
  16757. bits -= state.extra;
  16758. //---//
  16759. state.back += state.extra;
  16760. }
  16761. //#ifdef INFLATE_STRICT
  16762. if (state.offset > state.dmax) {
  16763. strm.msg = 'invalid distance too far back';
  16764. state.mode = BAD;
  16765. break;
  16766. }
  16767. //#endif
  16768. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  16769. state.mode = MATCH;
  16770. /* falls through */
  16771. case MATCH:
  16772. if (left === 0) { break inf_leave; }
  16773. copy = _out - left;
  16774. if (state.offset > copy) { /* copy from window */
  16775. copy = state.offset - copy;
  16776. if (copy > state.whave) {
  16777. if (state.sane) {
  16778. strm.msg = 'invalid distance too far back';
  16779. state.mode = BAD;
  16780. break;
  16781. }
  16782. // (!) This block is disabled in zlib defailts,
  16783. // don't enable it for binary compatibility
  16784. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16785. // Trace((stderr, "inflate.c too far\n"));
  16786. // copy -= state.whave;
  16787. // if (copy > state.length) { copy = state.length; }
  16788. // if (copy > left) { copy = left; }
  16789. // left -= copy;
  16790. // state.length -= copy;
  16791. // do {
  16792. // output[put++] = 0;
  16793. // } while (--copy);
  16794. // if (state.length === 0) { state.mode = LEN; }
  16795. // break;
  16796. //#endif
  16797. }
  16798. if (copy > state.wnext) {
  16799. copy -= state.wnext;
  16800. from = state.wsize - copy;
  16801. }
  16802. else {
  16803. from = state.wnext - copy;
  16804. }
  16805. if (copy > state.length) { copy = state.length; }
  16806. from_source = state.window;
  16807. }
  16808. else { /* copy from output */
  16809. from_source = output;
  16810. from = put - state.offset;
  16811. copy = state.length;
  16812. }
  16813. if (copy > left) { copy = left; }
  16814. left -= copy;
  16815. state.length -= copy;
  16816. do {
  16817. output[put++] = from_source[from++];
  16818. } while (--copy);
  16819. if (state.length === 0) { state.mode = LEN; }
  16820. break;
  16821. case LIT:
  16822. if (left === 0) { break inf_leave; }
  16823. output[put++] = state.length;
  16824. left--;
  16825. state.mode = LEN;
  16826. break;
  16827. case CHECK:
  16828. if (state.wrap) {
  16829. //=== NEEDBITS(32);
  16830. while (bits < 32) {
  16831. if (have === 0) { break inf_leave; }
  16832. have--;
  16833. // Use '|' insdead of '+' to make sure that result is signed
  16834. hold |= input[next++] << bits;
  16835. bits += 8;
  16836. }
  16837. //===//
  16838. _out -= left;
  16839. strm.total_out += _out;
  16840. state.total += _out;
  16841. if (_out) {
  16842. strm.adler = state.check =
  16843. /*UPDATE(state.check, put - _out, _out);*/
  16844. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  16845. }
  16846. _out = left;
  16847. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  16848. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  16849. strm.msg = 'incorrect data check';
  16850. state.mode = BAD;
  16851. break;
  16852. }
  16853. //=== INITBITS();
  16854. hold = 0;
  16855. bits = 0;
  16856. //===//
  16857. //Tracev((stderr, "inflate: check matches trailer\n"));
  16858. }
  16859. state.mode = LENGTH;
  16860. /* falls through */
  16861. case LENGTH:
  16862. if (state.wrap && state.flags) {
  16863. //=== NEEDBITS(32);
  16864. while (bits < 32) {
  16865. if (have === 0) { break inf_leave; }
  16866. have--;
  16867. hold += input[next++] << bits;
  16868. bits += 8;
  16869. }
  16870. //===//
  16871. if (hold !== (state.total & 0xffffffff)) {
  16872. strm.msg = 'incorrect length check';
  16873. state.mode = BAD;
  16874. break;
  16875. }
  16876. //=== INITBITS();
  16877. hold = 0;
  16878. bits = 0;
  16879. //===//
  16880. //Tracev((stderr, "inflate: length matches trailer\n"));
  16881. }
  16882. state.mode = DONE;
  16883. /* falls through */
  16884. case DONE:
  16885. ret = Z_STREAM_END;
  16886. break inf_leave;
  16887. case BAD:
  16888. ret = Z_DATA_ERROR;
  16889. break inf_leave;
  16890. case MEM:
  16891. return Z_MEM_ERROR;
  16892. case SYNC:
  16893. /* falls through */
  16894. default:
  16895. return Z_STREAM_ERROR;
  16896. }
  16897. }
  16898. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  16899. /*
  16900. Return from inflate(), updating the total counts and the check value.
  16901. If there was no progress during the inflate() call, return a buffer
  16902. error. Call updatewindow() to create and/or update the window state.
  16903. Note: a memory error from inflate() is non-recoverable.
  16904. */
  16905. //--- RESTORE() ---
  16906. strm.next_out = put;
  16907. strm.avail_out = left;
  16908. strm.next_in = next;
  16909. strm.avail_in = have;
  16910. state.hold = hold;
  16911. state.bits = bits;
  16912. //---
  16913. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  16914. (state.mode < CHECK || flush !== Z_FINISH))) {
  16915. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  16916. state.mode = MEM;
  16917. return Z_MEM_ERROR;
  16918. }
  16919. }
  16920. _in -= strm.avail_in;
  16921. _out -= strm.avail_out;
  16922. strm.total_in += _in;
  16923. strm.total_out += _out;
  16924. state.total += _out;
  16925. if (state.wrap && _out) {
  16926. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  16927. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  16928. }
  16929. strm.data_type = state.bits + (state.last ? 64 : 0) +
  16930. (state.mode === TYPE ? 128 : 0) +
  16931. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  16932. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  16933. ret = Z_BUF_ERROR;
  16934. }
  16935. return ret;
  16936. }
  16937. function inflateEnd(strm) {
  16938. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  16939. return Z_STREAM_ERROR;
  16940. }
  16941. var state = strm.state;
  16942. if (state.window) {
  16943. state.window = null;
  16944. }
  16945. strm.state = null;
  16946. return Z_OK;
  16947. }
  16948. function inflateGetHeader(strm, head) {
  16949. var state;
  16950. /* check state */
  16951. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16952. state = strm.state;
  16953. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  16954. /* save header structure */
  16955. state.head = head;
  16956. head.done = false;
  16957. return Z_OK;
  16958. }
  16959. exports.inflateReset = inflateReset;
  16960. exports.inflateReset2 = inflateReset2;
  16961. exports.inflateResetKeep = inflateResetKeep;
  16962. exports.inflateInit = inflateInit;
  16963. exports.inflateInit2 = inflateInit2;
  16964. exports.inflate = inflate;
  16965. exports.inflateEnd = inflateEnd;
  16966. exports.inflateGetHeader = inflateGetHeader;
  16967. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  16968. /* Not implemented
  16969. exports.inflateCopy = inflateCopy;
  16970. exports.inflateGetDictionary = inflateGetDictionary;
  16971. exports.inflateMark = inflateMark;
  16972. exports.inflatePrime = inflatePrime;
  16973. exports.inflateSetDictionary = inflateSetDictionary;
  16974. exports.inflateSync = inflateSync;
  16975. exports.inflateSyncPoint = inflateSyncPoint;
  16976. exports.inflateUndermine = inflateUndermine;
  16977. */
  16978. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./inffast":58,"./inftrees":60}],60:[function(require,module,exports){
  16979. 'use strict';
  16980. var utils = require('../utils/common');
  16981. var MAXBITS = 15;
  16982. var ENOUGH_LENS = 852;
  16983. var ENOUGH_DISTS = 592;
  16984. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16985. var CODES = 0;
  16986. var LENS = 1;
  16987. var DISTS = 2;
  16988. var lbase = [ /* Length codes 257..285 base */
  16989. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  16990. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  16991. ];
  16992. var lext = [ /* Length codes 257..285 extra */
  16993. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  16994. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  16995. ];
  16996. var dbase = [ /* Distance codes 0..29 base */
  16997. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  16998. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  16999. 8193, 12289, 16385, 24577, 0, 0
  17000. ];
  17001. var dext = [ /* Distance codes 0..29 extra */
  17002. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17003. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17004. 28, 28, 29, 29, 64, 64
  17005. ];
  17006. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17007. {
  17008. var bits = opts.bits;
  17009. //here = opts.here; /* table entry for duplication */
  17010. var len = 0; /* a code's length in bits */
  17011. var sym = 0; /* index of code symbols */
  17012. var min = 0, max = 0; /* minimum and maximum code lengths */
  17013. var root = 0; /* number of index bits for root table */
  17014. var curr = 0; /* number of index bits for current table */
  17015. var drop = 0; /* code bits to drop for sub-table */
  17016. var left = 0; /* number of prefix codes available */
  17017. var used = 0; /* code entries in table used */
  17018. var huff = 0; /* Huffman code */
  17019. var incr; /* for incrementing code, index */
  17020. var fill; /* index for replicating entries */
  17021. var low; /* low bits for current root entry */
  17022. var mask; /* mask for low root bits */
  17023. var next; /* next available space in table */
  17024. var base = null; /* base value table to use */
  17025. var base_index = 0;
  17026. // var shoextra; /* extra bits table to use */
  17027. var end; /* use base and extra for symbol > end */
  17028. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  17029. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  17030. var extra = null;
  17031. var extra_index = 0;
  17032. var here_bits, here_op, here_val;
  17033. /*
  17034. Process a set of code lengths to create a canonical Huffman code. The
  17035. code lengths are lens[0..codes-1]. Each length corresponds to the
  17036. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17037. symbols by length from short to long, and retaining the symbol order
  17038. for codes with equal lengths. Then the code starts with all zero bits
  17039. for the first code of the shortest length, and the codes are integer
  17040. increments for the same length, and zeros are appended as the length
  17041. increases. For the deflate format, these bits are stored backwards
  17042. from their more natural integer increment ordering, and so when the
  17043. decoding tables are built in the large loop below, the integer codes
  17044. are incremented backwards.
  17045. This routine assumes, but does not check, that all of the entries in
  17046. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17047. 1..MAXBITS is interpreted as that code length. zero means that that
  17048. symbol does not occur in this code.
  17049. The codes are sorted by computing a count of codes for each length,
  17050. creating from that a table of starting indices for each length in the
  17051. sorted table, and then entering the symbols in order in the sorted
  17052. table. The sorted table is work[], with that space being provided by
  17053. the caller.
  17054. The length counts are used for other purposes as well, i.e. finding
  17055. the minimum and maximum length codes, determining if there are any
  17056. codes at all, checking for a valid set of lengths, and looking ahead
  17057. at length counts to determine sub-table sizes when building the
  17058. decoding tables.
  17059. */
  17060. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17061. for (len = 0; len <= MAXBITS; len++) {
  17062. count[len] = 0;
  17063. }
  17064. for (sym = 0; sym < codes; sym++) {
  17065. count[lens[lens_index + sym]]++;
  17066. }
  17067. /* bound code lengths, force root to be within code lengths */
  17068. root = bits;
  17069. for (max = MAXBITS; max >= 1; max--) {
  17070. if (count[max] !== 0) { break; }
  17071. }
  17072. if (root > max) {
  17073. root = max;
  17074. }
  17075. if (max === 0) { /* no symbols to code at all */
  17076. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17077. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17078. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17079. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17080. //table.op[opts.table_index] = 64;
  17081. //table.bits[opts.table_index] = 1;
  17082. //table.val[opts.table_index++] = 0;
  17083. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17084. opts.bits = 1;
  17085. return 0; /* no symbols, but wait for decoding to report error */
  17086. }
  17087. for (min = 1; min < max; min++) {
  17088. if (count[min] !== 0) { break; }
  17089. }
  17090. if (root < min) {
  17091. root = min;
  17092. }
  17093. /* check for an over-subscribed or incomplete set of lengths */
  17094. left = 1;
  17095. for (len = 1; len <= MAXBITS; len++) {
  17096. left <<= 1;
  17097. left -= count[len];
  17098. if (left < 0) {
  17099. return -1;
  17100. } /* over-subscribed */
  17101. }
  17102. if (left > 0 && (type === CODES || max !== 1)) {
  17103. return -1; /* incomplete set */
  17104. }
  17105. /* generate offsets into symbol table for each length for sorting */
  17106. offs[1] = 0;
  17107. for (len = 1; len < MAXBITS; len++) {
  17108. offs[len + 1] = offs[len] + count[len];
  17109. }
  17110. /* sort symbols by length, by symbol order within each length */
  17111. for (sym = 0; sym < codes; sym++) {
  17112. if (lens[lens_index + sym] !== 0) {
  17113. work[offs[lens[lens_index + sym]]++] = sym;
  17114. }
  17115. }
  17116. /*
  17117. Create and fill in decoding tables. In this loop, the table being
  17118. filled is at next and has curr index bits. The code being used is huff
  17119. with length len. That code is converted to an index by dropping drop
  17120. bits off of the bottom. For codes where len is less than drop + curr,
  17121. those top drop + curr - len bits are incremented through all values to
  17122. fill the table with replicated entries.
  17123. root is the number of index bits for the root table. When len exceeds
  17124. root, sub-tables are created pointed to by the root entry with an index
  17125. of the low root bits of huff. This is saved in low to check for when a
  17126. new sub-table should be started. drop is zero when the root table is
  17127. being filled, and drop is root when sub-tables are being filled.
  17128. When a new sub-table is needed, it is necessary to look ahead in the
  17129. code lengths to determine what size sub-table is needed. The length
  17130. counts are used for this, and so count[] is decremented as codes are
  17131. entered in the tables.
  17132. used keeps track of how many table entries have been allocated from the
  17133. provided *table space. It is checked for LENS and DIST tables against
  17134. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  17135. the initial root table size constants. See the comments in inftrees.h
  17136. for more information.
  17137. sym increments through all symbols, and the loop terminates when
  17138. all codes of length max, i.e. all codes, have been processed. This
  17139. routine permits incomplete codes, so another loop after this one fills
  17140. in the rest of the decoding tables with invalid code markers.
  17141. */
  17142. /* set up for code type */
  17143. // poor man optimization - use if-else instead of switch,
  17144. // to avoid deopts in old v8
  17145. if (type === CODES) {
  17146. base = extra = work; /* dummy value--not used */
  17147. end = 19;
  17148. } else if (type === LENS) {
  17149. base = lbase;
  17150. base_index -= 257;
  17151. extra = lext;
  17152. extra_index -= 257;
  17153. end = 256;
  17154. } else { /* DISTS */
  17155. base = dbase;
  17156. extra = dext;
  17157. end = -1;
  17158. }
  17159. /* initialize opts for loop */
  17160. huff = 0; /* starting code */
  17161. sym = 0; /* starting code symbol */
  17162. len = min; /* starting code length */
  17163. next = table_index; /* current table to fill in */
  17164. curr = root; /* current table index bits */
  17165. drop = 0; /* current bits to drop from code for index */
  17166. low = -1; /* trigger new sub-table when len > root */
  17167. used = 1 << root; /* use root table entries */
  17168. mask = used - 1; /* mask for comparing low */
  17169. /* check available table space */
  17170. if ((type === LENS && used > ENOUGH_LENS) ||
  17171. (type === DISTS && used > ENOUGH_DISTS)) {
  17172. return 1;
  17173. }
  17174. var i=0;
  17175. /* process all codes and make table entries */
  17176. for (;;) {
  17177. i++;
  17178. /* create table entry */
  17179. here_bits = len - drop;
  17180. if (work[sym] < end) {
  17181. here_op = 0;
  17182. here_val = work[sym];
  17183. }
  17184. else if (work[sym] > end) {
  17185. here_op = extra[extra_index + work[sym]];
  17186. here_val = base[base_index + work[sym]];
  17187. }
  17188. else {
  17189. here_op = 32 + 64; /* end of block */
  17190. here_val = 0;
  17191. }
  17192. /* replicate for those indices with low len bits equal to huff */
  17193. incr = 1 << (len - drop);
  17194. fill = 1 << curr;
  17195. min = fill; /* save offset to next table */
  17196. do {
  17197. fill -= incr;
  17198. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17199. } while (fill !== 0);
  17200. /* backwards increment the len-bit code huff */
  17201. incr = 1 << (len - 1);
  17202. while (huff & incr) {
  17203. incr >>= 1;
  17204. }
  17205. if (incr !== 0) {
  17206. huff &= incr - 1;
  17207. huff += incr;
  17208. } else {
  17209. huff = 0;
  17210. }
  17211. /* go to next symbol, update count, len */
  17212. sym++;
  17213. if (--count[len] === 0) {
  17214. if (len === max) { break; }
  17215. len = lens[lens_index + work[sym]];
  17216. }
  17217. /* create new sub-table if needed */
  17218. if (len > root && (huff & mask) !== low) {
  17219. /* if first time, transition to sub-tables */
  17220. if (drop === 0) {
  17221. drop = root;
  17222. }
  17223. /* increment past last table */
  17224. next += min; /* here min is 1 << curr */
  17225. /* determine length of next table */
  17226. curr = len - drop;
  17227. left = 1 << curr;
  17228. while (curr + drop < max) {
  17229. left -= count[curr + drop];
  17230. if (left <= 0) { break; }
  17231. curr++;
  17232. left <<= 1;
  17233. }
  17234. /* check for enough space */
  17235. used += 1 << curr;
  17236. if ((type === LENS && used > ENOUGH_LENS) ||
  17237. (type === DISTS && used > ENOUGH_DISTS)) {
  17238. return 1;
  17239. }
  17240. /* point entry in root table to sub-table */
  17241. low = huff & mask;
  17242. /*table.op[low] = curr;
  17243. table.bits[low] = root;
  17244. table.val[low] = next - opts.table_index;*/
  17245. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17246. }
  17247. }
  17248. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17249. at most one remaining entry, since if the code is incomplete, the
  17250. maximum code length that was allowed to get this far is one bit) */
  17251. if (huff !== 0) {
  17252. //table.op[next + huff] = 64; /* invalid code marker */
  17253. //table.bits[next + huff] = len - drop;
  17254. //table.val[next + huff] = 0;
  17255. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17256. }
  17257. /* set return parameters */
  17258. //opts.table_index += used;
  17259. opts.bits = root;
  17260. return 0;
  17261. };
  17262. },{"../utils/common":51}],61:[function(require,module,exports){
  17263. 'use strict';
  17264. module.exports = {
  17265. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  17266. '1': 'stream end', /* Z_STREAM_END 1 */
  17267. '0': '', /* Z_OK 0 */
  17268. '-1': 'file error', /* Z_ERRNO (-1) */
  17269. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17270. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17271. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17272. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17273. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17274. };
  17275. },{}],62:[function(require,module,exports){
  17276. 'use strict';
  17277. var utils = require('../utils/common');
  17278. /* Public constants ==========================================================*/
  17279. /* ===========================================================================*/
  17280. //var Z_FILTERED = 1;
  17281. //var Z_HUFFMAN_ONLY = 2;
  17282. //var Z_RLE = 3;
  17283. var Z_FIXED = 4;
  17284. //var Z_DEFAULT_STRATEGY = 0;
  17285. /* Possible values of the data_type field (though see inflate()) */
  17286. var Z_BINARY = 0;
  17287. var Z_TEXT = 1;
  17288. //var Z_ASCII = 1; // = Z_TEXT
  17289. var Z_UNKNOWN = 2;
  17290. /*============================================================================*/
  17291. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17292. // From zutil.h
  17293. var STORED_BLOCK = 0;
  17294. var STATIC_TREES = 1;
  17295. var DYN_TREES = 2;
  17296. /* The three kinds of block type */
  17297. var MIN_MATCH = 3;
  17298. var MAX_MATCH = 258;
  17299. /* The minimum and maximum match lengths */
  17300. // From deflate.h
  17301. /* ===========================================================================
  17302. * Internal compression state.
  17303. */
  17304. var LENGTH_CODES = 29;
  17305. /* number of length codes, not counting the special END_BLOCK code */
  17306. var LITERALS = 256;
  17307. /* number of literal bytes 0..255 */
  17308. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17309. /* number of Literal or Length codes, including the END_BLOCK code */
  17310. var D_CODES = 30;
  17311. /* number of distance codes */
  17312. var BL_CODES = 19;
  17313. /* number of codes used to transfer the bit lengths */
  17314. var HEAP_SIZE = 2*L_CODES + 1;
  17315. /* maximum heap size */
  17316. var MAX_BITS = 15;
  17317. /* All codes must not exceed MAX_BITS bits */
  17318. var Buf_size = 16;
  17319. /* size of bit buffer in bi_buf */
  17320. /* ===========================================================================
  17321. * Constants
  17322. */
  17323. var MAX_BL_BITS = 7;
  17324. /* Bit length codes must not exceed MAX_BL_BITS bits */
  17325. var END_BLOCK = 256;
  17326. /* end of block literal code */
  17327. var REP_3_6 = 16;
  17328. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  17329. var REPZ_3_10 = 17;
  17330. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  17331. var REPZ_11_138 = 18;
  17332. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  17333. var extra_lbits = /* extra bits for each length code */
  17334. [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];
  17335. var extra_dbits = /* extra bits for each distance code */
  17336. [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];
  17337. var extra_blbits = /* extra bits for each bit length code */
  17338. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  17339. var bl_order =
  17340. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  17341. /* The lengths of the bit length codes are sent in order of decreasing
  17342. * probability, to avoid transmitting the lengths for unused bit length codes.
  17343. */
  17344. /* ===========================================================================
  17345. * Local data. These are initialized only once.
  17346. */
  17347. // We pre-fill arrays with 0 to avoid uninitialized gaps
  17348. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  17349. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  17350. var static_ltree = new Array((L_CODES+2) * 2);
  17351. zero(static_ltree);
  17352. /* The static literal tree. Since the bit lengths are imposed, there is no
  17353. * need for the L_CODES extra codes used during heap construction. However
  17354. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  17355. * below).
  17356. */
  17357. var static_dtree = new Array(D_CODES * 2);
  17358. zero(static_dtree);
  17359. /* The static distance tree. (Actually a trivial tree since all codes use
  17360. * 5 bits.)
  17361. */
  17362. var _dist_code = new Array(DIST_CODE_LEN);
  17363. zero(_dist_code);
  17364. /* Distance codes. The first 256 values correspond to the distances
  17365. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  17366. * the 15 bit distances.
  17367. */
  17368. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  17369. zero(_length_code);
  17370. /* length code for each normalized match length (0 == MIN_MATCH) */
  17371. var base_length = new Array(LENGTH_CODES);
  17372. zero(base_length);
  17373. /* First normalized length for each code (0 = MIN_MATCH) */
  17374. var base_dist = new Array(D_CODES);
  17375. zero(base_dist);
  17376. /* First normalized distance for each code (0 = distance of 1) */
  17377. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  17378. this.static_tree = static_tree; /* static tree or NULL */
  17379. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  17380. this.extra_base = extra_base; /* base index for extra_bits */
  17381. this.elems = elems; /* max number of elements in the tree */
  17382. this.max_length = max_length; /* max bit length for the codes */
  17383. // show if `static_tree` has data or dummy - needed for monomorphic objects
  17384. this.has_stree = static_tree && static_tree.length;
  17385. };
  17386. var static_l_desc;
  17387. var static_d_desc;
  17388. var static_bl_desc;
  17389. var TreeDesc = function(dyn_tree, stat_desc) {
  17390. this.dyn_tree = dyn_tree; /* the dynamic tree */
  17391. this.max_code = 0; /* largest code with non zero frequency */
  17392. this.stat_desc = stat_desc; /* the corresponding static tree */
  17393. };
  17394. function d_code(dist) {
  17395. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17396. }
  17397. /* ===========================================================================
  17398. * Output a short LSB first on the stream.
  17399. * IN assertion: there is enough room in pendingBuf.
  17400. */
  17401. function put_short (s, w) {
  17402. // put_byte(s, (uch)((w) & 0xff));
  17403. // put_byte(s, (uch)((ush)(w) >> 8));
  17404. s.pending_buf[s.pending++] = (w) & 0xff;
  17405. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  17406. }
  17407. /* ===========================================================================
  17408. * Send a value on a given number of bits.
  17409. * IN assertion: length <= 16 and value fits in length bits.
  17410. */
  17411. function send_bits(s, value, length) {
  17412. if (s.bi_valid > (Buf_size - length)) {
  17413. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17414. put_short(s, s.bi_buf);
  17415. s.bi_buf = value >> (Buf_size - s.bi_valid);
  17416. s.bi_valid += length - Buf_size;
  17417. } else {
  17418. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17419. s.bi_valid += length;
  17420. }
  17421. }
  17422. function send_code(s, c, tree) {
  17423. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  17424. }
  17425. /* ===========================================================================
  17426. * Reverse the first len bits of a code, using straightforward code (a faster
  17427. * method would use a table)
  17428. * IN assertion: 1 <= len <= 15
  17429. */
  17430. function bi_reverse(code, len) {
  17431. var res = 0;
  17432. do {
  17433. res |= code & 1;
  17434. code >>>= 1;
  17435. res <<= 1;
  17436. } while (--len > 0);
  17437. return res >>> 1;
  17438. }
  17439. /* ===========================================================================
  17440. * Flush the bit buffer, keeping at most 7 bits in it.
  17441. */
  17442. function bi_flush(s) {
  17443. if (s.bi_valid === 16) {
  17444. put_short(s, s.bi_buf);
  17445. s.bi_buf = 0;
  17446. s.bi_valid = 0;
  17447. } else if (s.bi_valid >= 8) {
  17448. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  17449. s.bi_buf >>= 8;
  17450. s.bi_valid -= 8;
  17451. }
  17452. }
  17453. /* ===========================================================================
  17454. * Compute the optimal bit lengths for a tree and update the total bit length
  17455. * for the current block.
  17456. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  17457. * above are the tree nodes sorted by increasing frequency.
  17458. * OUT assertions: the field len is set to the optimal bit length, the
  17459. * array bl_count contains the frequencies for each bit length.
  17460. * The length opt_len is updated; static_len is also updated if stree is
  17461. * not null.
  17462. */
  17463. function gen_bitlen(s, desc)
  17464. // deflate_state *s;
  17465. // tree_desc *desc; /* the tree descriptor */
  17466. {
  17467. var tree = desc.dyn_tree;
  17468. var max_code = desc.max_code;
  17469. var stree = desc.stat_desc.static_tree;
  17470. var has_stree = desc.stat_desc.has_stree;
  17471. var extra = desc.stat_desc.extra_bits;
  17472. var base = desc.stat_desc.extra_base;
  17473. var max_length = desc.stat_desc.max_length;
  17474. var h; /* heap index */
  17475. var n, m; /* iterate over the tree elements */
  17476. var bits; /* bit length */
  17477. var xbits; /* extra bits */
  17478. var f; /* frequency */
  17479. var overflow = 0; /* number of elements with bit length too large */
  17480. for (bits = 0; bits <= MAX_BITS; bits++) {
  17481. s.bl_count[bits] = 0;
  17482. }
  17483. /* In a first pass, compute the optimal bit lengths (which may
  17484. * overflow in the case of the bit length tree).
  17485. */
  17486. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  17487. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  17488. n = s.heap[h];
  17489. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  17490. if (bits > max_length) {
  17491. bits = max_length;
  17492. overflow++;
  17493. }
  17494. tree[n*2 + 1]/*.Len*/ = bits;
  17495. /* We overwrite tree[n].Dad which is no longer needed */
  17496. if (n > max_code) { continue; } /* not a leaf node */
  17497. s.bl_count[bits]++;
  17498. xbits = 0;
  17499. if (n >= base) {
  17500. xbits = extra[n-base];
  17501. }
  17502. f = tree[n * 2]/*.Freq*/;
  17503. s.opt_len += f * (bits + xbits);
  17504. if (has_stree) {
  17505. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  17506. }
  17507. }
  17508. if (overflow === 0) { return; }
  17509. // Trace((stderr,"\nbit length overflow\n"));
  17510. /* This happens for example on obj2 and pic of the Calgary corpus */
  17511. /* Find the first bit length which could increase: */
  17512. do {
  17513. bits = max_length-1;
  17514. while (s.bl_count[bits] === 0) { bits--; }
  17515. s.bl_count[bits]--; /* move one leaf down the tree */
  17516. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  17517. s.bl_count[max_length]--;
  17518. /* The brother of the overflow item also moves one step up,
  17519. * but this does not affect bl_count[max_length]
  17520. */
  17521. overflow -= 2;
  17522. } while (overflow > 0);
  17523. /* Now recompute all bit lengths, scanning in increasing frequency.
  17524. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  17525. * lengths instead of fixing only the wrong ones. This idea is taken
  17526. * from 'ar' written by Haruhiko Okumura.)
  17527. */
  17528. for (bits = max_length; bits !== 0; bits--) {
  17529. n = s.bl_count[bits];
  17530. while (n !== 0) {
  17531. m = s.heap[--h];
  17532. if (m > max_code) { continue; }
  17533. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  17534. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  17535. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  17536. tree[m*2 + 1]/*.Len*/ = bits;
  17537. }
  17538. n--;
  17539. }
  17540. }
  17541. }
  17542. /* ===========================================================================
  17543. * Generate the codes for a given tree and bit counts (which need not be
  17544. * optimal).
  17545. * IN assertion: the array bl_count contains the bit length statistics for
  17546. * the given tree and the field len is set for all tree elements.
  17547. * OUT assertion: the field code is set for all tree elements of non
  17548. * zero code length.
  17549. */
  17550. function gen_codes(tree, max_code, bl_count)
  17551. // ct_data *tree; /* the tree to decorate */
  17552. // int max_code; /* largest code with non zero frequency */
  17553. // ushf *bl_count; /* number of codes at each bit length */
  17554. {
  17555. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  17556. var code = 0; /* running code value */
  17557. var bits; /* bit index */
  17558. var n; /* code index */
  17559. /* The distribution counts are first used to generate the code values
  17560. * without bit reversal.
  17561. */
  17562. for (bits = 1; bits <= MAX_BITS; bits++) {
  17563. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  17564. }
  17565. /* Check that the bit counts in bl_count are consistent. The last code
  17566. * must be all ones.
  17567. */
  17568. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17569. // "inconsistent bit counts");
  17570. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17571. for (n = 0; n <= max_code; n++) {
  17572. var len = tree[n*2 + 1]/*.Len*/;
  17573. if (len === 0) { continue; }
  17574. /* Now reverse the bits */
  17575. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  17576. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  17577. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  17578. }
  17579. }
  17580. /* ===========================================================================
  17581. * Initialize the various 'constant' tables.
  17582. */
  17583. function tr_static_init() {
  17584. var n; /* iterates over tree elements */
  17585. var bits; /* bit counter */
  17586. var length; /* length value */
  17587. var code; /* code value */
  17588. var dist; /* distance index */
  17589. var bl_count = new Array(MAX_BITS+1);
  17590. /* number of codes at each bit length for an optimal tree */
  17591. // do check in _tr_init()
  17592. //if (static_init_done) return;
  17593. /* For some embedded targets, global variables are not initialized: */
  17594. /*#ifdef NO_INIT_GLOBAL_POINTERS
  17595. static_l_desc.static_tree = static_ltree;
  17596. static_l_desc.extra_bits = extra_lbits;
  17597. static_d_desc.static_tree = static_dtree;
  17598. static_d_desc.extra_bits = extra_dbits;
  17599. static_bl_desc.extra_bits = extra_blbits;
  17600. #endif*/
  17601. /* Initialize the mapping length (0..255) -> length code (0..28) */
  17602. length = 0;
  17603. for (code = 0; code < LENGTH_CODES-1; code++) {
  17604. base_length[code] = length;
  17605. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  17606. _length_code[length++] = code;
  17607. }
  17608. }
  17609. //Assert (length == 256, "tr_static_init: length != 256");
  17610. /* Note that the length 255 (match length 258) can be represented
  17611. * in two different ways: code 284 + 5 bits or code 285, so we
  17612. * overwrite length_code[255] to use the best encoding:
  17613. */
  17614. _length_code[length-1] = code;
  17615. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  17616. dist = 0;
  17617. for (code = 0 ; code < 16; code++) {
  17618. base_dist[code] = dist;
  17619. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  17620. _dist_code[dist++] = code;
  17621. }
  17622. }
  17623. //Assert (dist == 256, "tr_static_init: dist != 256");
  17624. dist >>= 7; /* from now on, all distances are divided by 128 */
  17625. for (; code < D_CODES; code++) {
  17626. base_dist[code] = dist << 7;
  17627. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  17628. _dist_code[256 + dist++] = code;
  17629. }
  17630. }
  17631. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  17632. /* Construct the codes of the static literal tree */
  17633. for (bits = 0; bits <= MAX_BITS; bits++) {
  17634. bl_count[bits] = 0;
  17635. }
  17636. n = 0;
  17637. while (n <= 143) {
  17638. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17639. n++;
  17640. bl_count[8]++;
  17641. }
  17642. while (n <= 255) {
  17643. static_ltree[n*2 + 1]/*.Len*/ = 9;
  17644. n++;
  17645. bl_count[9]++;
  17646. }
  17647. while (n <= 279) {
  17648. static_ltree[n*2 + 1]/*.Len*/ = 7;
  17649. n++;
  17650. bl_count[7]++;
  17651. }
  17652. while (n <= 287) {
  17653. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17654. n++;
  17655. bl_count[8]++;
  17656. }
  17657. /* Codes 286 and 287 do not exist, but we must include them in the
  17658. * tree construction to get a canonical Huffman tree (longest code
  17659. * all ones)
  17660. */
  17661. gen_codes(static_ltree, L_CODES+1, bl_count);
  17662. /* The static distance tree is trivial: */
  17663. for (n = 0; n < D_CODES; n++) {
  17664. static_dtree[n*2 + 1]/*.Len*/ = 5;
  17665. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  17666. }
  17667. // Now data ready and we can init static trees
  17668. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  17669. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  17670. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  17671. //static_init_done = true;
  17672. }
  17673. /* ===========================================================================
  17674. * Initialize a new block.
  17675. */
  17676. function init_block(s) {
  17677. var n; /* iterates over tree elements */
  17678. /* Initialize the trees. */
  17679. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  17680. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  17681. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  17682. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  17683. s.opt_len = s.static_len = 0;
  17684. s.last_lit = s.matches = 0;
  17685. }
  17686. /* ===========================================================================
  17687. * Flush the bit buffer and align the output on a byte boundary
  17688. */
  17689. function bi_windup(s)
  17690. {
  17691. if (s.bi_valid > 8) {
  17692. put_short(s, s.bi_buf);
  17693. } else if (s.bi_valid > 0) {
  17694. //put_byte(s, (Byte)s->bi_buf);
  17695. s.pending_buf[s.pending++] = s.bi_buf;
  17696. }
  17697. s.bi_buf = 0;
  17698. s.bi_valid = 0;
  17699. }
  17700. /* ===========================================================================
  17701. * Copy a stored block, storing first the length and its
  17702. * one's complement if requested.
  17703. */
  17704. function copy_block(s, buf, len, header)
  17705. //DeflateState *s;
  17706. //charf *buf; /* the input data */
  17707. //unsigned len; /* its length */
  17708. //int header; /* true if block header must be written */
  17709. {
  17710. bi_windup(s); /* align on byte boundary */
  17711. if (header) {
  17712. put_short(s, len);
  17713. put_short(s, ~len);
  17714. }
  17715. // while (len--) {
  17716. // put_byte(s, *buf++);
  17717. // }
  17718. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  17719. s.pending += len;
  17720. }
  17721. /* ===========================================================================
  17722. * Compares to subtrees, using the tree depth as tie breaker when
  17723. * the subtrees have equal frequency. This minimizes the worst case length.
  17724. */
  17725. function smaller(tree, n, m, depth) {
  17726. var _n2 = n*2;
  17727. var _m2 = m*2;
  17728. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  17729. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  17730. }
  17731. /* ===========================================================================
  17732. * Restore the heap property by moving down the tree starting at node k,
  17733. * exchanging a node with the smallest of its two sons if necessary, stopping
  17734. * when the heap property is re-established (each father smaller than its
  17735. * two sons).
  17736. */
  17737. function pqdownheap(s, tree, k)
  17738. // deflate_state *s;
  17739. // ct_data *tree; /* the tree to restore */
  17740. // int k; /* node to move down */
  17741. {
  17742. var v = s.heap[k];
  17743. var j = k << 1; /* left son of k */
  17744. while (j <= s.heap_len) {
  17745. /* Set j to the smallest of the two sons: */
  17746. if (j < s.heap_len &&
  17747. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  17748. j++;
  17749. }
  17750. /* Exit if v is smaller than both sons */
  17751. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  17752. /* Exchange v with the smallest son */
  17753. s.heap[k] = s.heap[j];
  17754. k = j;
  17755. /* And continue down the tree, setting j to the left son of k */
  17756. j <<= 1;
  17757. }
  17758. s.heap[k] = v;
  17759. }
  17760. // inlined manually
  17761. // var SMALLEST = 1;
  17762. /* ===========================================================================
  17763. * Send the block data compressed using the given Huffman trees
  17764. */
  17765. function compress_block(s, ltree, dtree)
  17766. // deflate_state *s;
  17767. // const ct_data *ltree; /* literal tree */
  17768. // const ct_data *dtree; /* distance tree */
  17769. {
  17770. var dist; /* distance of matched string */
  17771. var lc; /* match length or unmatched char (if dist == 0) */
  17772. var lx = 0; /* running index in l_buf */
  17773. var code; /* the code to send */
  17774. var extra; /* number of extra bits to send */
  17775. if (s.last_lit !== 0) {
  17776. do {
  17777. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  17778. lc = s.pending_buf[s.l_buf + lx];
  17779. lx++;
  17780. if (dist === 0) {
  17781. send_code(s, lc, ltree); /* send a literal byte */
  17782. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  17783. } else {
  17784. /* Here, lc is the match length - MIN_MATCH */
  17785. code = _length_code[lc];
  17786. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  17787. extra = extra_lbits[code];
  17788. if (extra !== 0) {
  17789. lc -= base_length[code];
  17790. send_bits(s, lc, extra); /* send the extra length bits */
  17791. }
  17792. dist--; /* dist is now the match distance - 1 */
  17793. code = d_code(dist);
  17794. //Assert (code < D_CODES, "bad d_code");
  17795. send_code(s, code, dtree); /* send the distance code */
  17796. extra = extra_dbits[code];
  17797. if (extra !== 0) {
  17798. dist -= base_dist[code];
  17799. send_bits(s, dist, extra); /* send the extra distance bits */
  17800. }
  17801. } /* literal or match pair ? */
  17802. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  17803. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  17804. // "pendingBuf overflow");
  17805. } while (lx < s.last_lit);
  17806. }
  17807. send_code(s, END_BLOCK, ltree);
  17808. }
  17809. /* ===========================================================================
  17810. * Construct one Huffman tree and assigns the code bit strings and lengths.
  17811. * Update the total bit length for the current block.
  17812. * IN assertion: the field freq is set for all tree elements.
  17813. * OUT assertions: the fields len and code are set to the optimal bit length
  17814. * and corresponding code. The length opt_len is updated; static_len is
  17815. * also updated if stree is not null. The field max_code is set.
  17816. */
  17817. function build_tree(s, desc)
  17818. // deflate_state *s;
  17819. // tree_desc *desc; /* the tree descriptor */
  17820. {
  17821. var tree = desc.dyn_tree;
  17822. var stree = desc.stat_desc.static_tree;
  17823. var has_stree = desc.stat_desc.has_stree;
  17824. var elems = desc.stat_desc.elems;
  17825. var n, m; /* iterate over heap elements */
  17826. var max_code = -1; /* largest code with non zero frequency */
  17827. var node; /* new node being created */
  17828. /* Construct the initial heap, with least frequent element in
  17829. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  17830. * heap[0] is not used.
  17831. */
  17832. s.heap_len = 0;
  17833. s.heap_max = HEAP_SIZE;
  17834. for (n = 0; n < elems; n++) {
  17835. if (tree[n * 2]/*.Freq*/ !== 0) {
  17836. s.heap[++s.heap_len] = max_code = n;
  17837. s.depth[n] = 0;
  17838. } else {
  17839. tree[n*2 + 1]/*.Len*/ = 0;
  17840. }
  17841. }
  17842. /* The pkzip format requires that at least one distance code exists,
  17843. * and that at least one bit should be sent even if there is only one
  17844. * possible code. So to avoid special checks later on we force at least
  17845. * two codes of non zero frequency.
  17846. */
  17847. while (s.heap_len < 2) {
  17848. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  17849. tree[node * 2]/*.Freq*/ = 1;
  17850. s.depth[node] = 0;
  17851. s.opt_len--;
  17852. if (has_stree) {
  17853. s.static_len -= stree[node*2 + 1]/*.Len*/;
  17854. }
  17855. /* node is 0 or 1 so it does not have extra bits */
  17856. }
  17857. desc.max_code = max_code;
  17858. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  17859. * establish sub-heaps of increasing lengths:
  17860. */
  17861. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  17862. /* Construct the Huffman tree by repeatedly combining the least two
  17863. * frequent nodes.
  17864. */
  17865. node = elems; /* next internal node of the tree */
  17866. do {
  17867. //pqremove(s, tree, n); /* n = node of least frequency */
  17868. /*** pqremove ***/
  17869. n = s.heap[1/*SMALLEST*/];
  17870. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  17871. pqdownheap(s, tree, 1/*SMALLEST*/);
  17872. /***/
  17873. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  17874. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  17875. s.heap[--s.heap_max] = m;
  17876. /* Create a new node father of n and m */
  17877. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  17878. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  17879. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  17880. /* and insert the new node in the heap */
  17881. s.heap[1/*SMALLEST*/] = node++;
  17882. pqdownheap(s, tree, 1/*SMALLEST*/);
  17883. } while (s.heap_len >= 2);
  17884. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  17885. /* At this point, the fields freq and dad are set. We can now
  17886. * generate the bit lengths.
  17887. */
  17888. gen_bitlen(s, desc);
  17889. /* The field len is now set, we can generate the bit codes */
  17890. gen_codes(tree, max_code, s.bl_count);
  17891. }
  17892. /* ===========================================================================
  17893. * Scan a literal or distance tree to determine the frequencies of the codes
  17894. * in the bit length tree.
  17895. */
  17896. function scan_tree(s, tree, max_code)
  17897. // deflate_state *s;
  17898. // ct_data *tree; /* the tree to be scanned */
  17899. // int max_code; /* and its largest code of non zero frequency */
  17900. {
  17901. var n; /* iterates over all tree elements */
  17902. var prevlen = -1; /* last emitted length */
  17903. var curlen; /* length of current code */
  17904. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17905. var count = 0; /* repeat count of the current code */
  17906. var max_count = 7; /* max repeat count */
  17907. var min_count = 4; /* min repeat count */
  17908. if (nextlen === 0) {
  17909. max_count = 138;
  17910. min_count = 3;
  17911. }
  17912. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  17913. for (n = 0; n <= max_code; n++) {
  17914. curlen = nextlen;
  17915. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17916. if (++count < max_count && curlen === nextlen) {
  17917. continue;
  17918. } else if (count < min_count) {
  17919. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  17920. } else if (curlen !== 0) {
  17921. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  17922. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  17923. } else if (count <= 10) {
  17924. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  17925. } else {
  17926. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  17927. }
  17928. count = 0;
  17929. prevlen = curlen;
  17930. if (nextlen === 0) {
  17931. max_count = 138;
  17932. min_count = 3;
  17933. } else if (curlen === nextlen) {
  17934. max_count = 6;
  17935. min_count = 3;
  17936. } else {
  17937. max_count = 7;
  17938. min_count = 4;
  17939. }
  17940. }
  17941. }
  17942. /* ===========================================================================
  17943. * Send a literal or distance tree in compressed form, using the codes in
  17944. * bl_tree.
  17945. */
  17946. function send_tree(s, tree, max_code)
  17947. // deflate_state *s;
  17948. // ct_data *tree; /* the tree to be scanned */
  17949. // int max_code; /* and its largest code of non zero frequency */
  17950. {
  17951. var n; /* iterates over all tree elements */
  17952. var prevlen = -1; /* last emitted length */
  17953. var curlen; /* length of current code */
  17954. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17955. var count = 0; /* repeat count of the current code */
  17956. var max_count = 7; /* max repeat count */
  17957. var min_count = 4; /* min repeat count */
  17958. /* tree[max_code+1].Len = -1; */ /* guard already set */
  17959. if (nextlen === 0) {
  17960. max_count = 138;
  17961. min_count = 3;
  17962. }
  17963. for (n = 0; n <= max_code; n++) {
  17964. curlen = nextlen;
  17965. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17966. if (++count < max_count && curlen === nextlen) {
  17967. continue;
  17968. } else if (count < min_count) {
  17969. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  17970. } else if (curlen !== 0) {
  17971. if (curlen !== prevlen) {
  17972. send_code(s, curlen, s.bl_tree);
  17973. count--;
  17974. }
  17975. //Assert(count >= 3 && count <= 6, " 3_6?");
  17976. send_code(s, REP_3_6, s.bl_tree);
  17977. send_bits(s, count-3, 2);
  17978. } else if (count <= 10) {
  17979. send_code(s, REPZ_3_10, s.bl_tree);
  17980. send_bits(s, count-3, 3);
  17981. } else {
  17982. send_code(s, REPZ_11_138, s.bl_tree);
  17983. send_bits(s, count-11, 7);
  17984. }
  17985. count = 0;
  17986. prevlen = curlen;
  17987. if (nextlen === 0) {
  17988. max_count = 138;
  17989. min_count = 3;
  17990. } else if (curlen === nextlen) {
  17991. max_count = 6;
  17992. min_count = 3;
  17993. } else {
  17994. max_count = 7;
  17995. min_count = 4;
  17996. }
  17997. }
  17998. }
  17999. /* ===========================================================================
  18000. * Construct the Huffman tree for the bit lengths and return the index in
  18001. * bl_order of the last bit length code to send.
  18002. */
  18003. function build_bl_tree(s) {
  18004. var max_blindex; /* index of last bit length code of non zero freq */
  18005. /* Determine the bit length frequencies for literal and distance trees */
  18006. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18007. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18008. /* Build the bit length tree: */
  18009. build_tree(s, s.bl_desc);
  18010. /* opt_len now includes the length of the tree representations, except
  18011. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18012. */
  18013. /* Determine the number of bit length codes to send. The pkzip format
  18014. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18015. * 3 but the actual value used is 4.)
  18016. */
  18017. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  18018. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  18019. break;
  18020. }
  18021. }
  18022. /* Update opt_len to include the bit length tree and counts */
  18023. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  18024. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18025. // s->opt_len, s->static_len));
  18026. return max_blindex;
  18027. }
  18028. /* ===========================================================================
  18029. * Send the header for a block using dynamic Huffman trees: the counts, the
  18030. * lengths of the bit length codes, the literal tree and the distance tree.
  18031. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18032. */
  18033. function send_all_trees(s, lcodes, dcodes, blcodes)
  18034. // deflate_state *s;
  18035. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18036. {
  18037. var rank; /* index in bl_order */
  18038. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18039. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18040. // "too many codes");
  18041. //Tracev((stderr, "\nbl counts: "));
  18042. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  18043. send_bits(s, dcodes-1, 5);
  18044. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  18045. for (rank = 0; rank < blcodes; rank++) {
  18046. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18047. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  18048. }
  18049. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18050. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  18051. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18052. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  18053. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18054. }
  18055. /* ===========================================================================
  18056. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18057. * - TEXT if the two conditions below are satisfied:
  18058. * a) There are no non-portable control characters belonging to the
  18059. * "black list" (0..6, 14..25, 28..31).
  18060. * b) There is at least one printable character belonging to the
  18061. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18062. * - BINARY otherwise.
  18063. * - The following partially-portable control characters form a
  18064. * "gray list" that is ignored in this detection algorithm:
  18065. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18066. * IN assertion: the fields Freq of dyn_ltree are set.
  18067. */
  18068. function detect_data_type(s) {
  18069. /* black_mask is the bit mask of black-listed bytes
  18070. * set bits 0..6, 14..25, and 28..31
  18071. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18072. */
  18073. var black_mask = 0xf3ffc07f;
  18074. var n;
  18075. /* Check for non-textual ("black-listed") bytes. */
  18076. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18077. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  18078. return Z_BINARY;
  18079. }
  18080. }
  18081. /* Check for textual ("white-listed") bytes. */
  18082. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18083. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18084. return Z_TEXT;
  18085. }
  18086. for (n = 32; n < LITERALS; n++) {
  18087. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18088. return Z_TEXT;
  18089. }
  18090. }
  18091. /* There are no "black-listed" or "white-listed" bytes:
  18092. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18093. */
  18094. return Z_BINARY;
  18095. }
  18096. var static_init_done = false;
  18097. /* ===========================================================================
  18098. * Initialize the tree data structures for a new zlib stream.
  18099. */
  18100. function _tr_init(s)
  18101. {
  18102. if (!static_init_done) {
  18103. tr_static_init();
  18104. static_init_done = true;
  18105. }
  18106. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  18107. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  18108. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  18109. s.bi_buf = 0;
  18110. s.bi_valid = 0;
  18111. /* Initialize the first block of the first file: */
  18112. init_block(s);
  18113. }
  18114. /* ===========================================================================
  18115. * Send a stored block
  18116. */
  18117. function _tr_stored_block(s, buf, stored_len, last)
  18118. //DeflateState *s;
  18119. //charf *buf; /* input block */
  18120. //ulg stored_len; /* length of input block */
  18121. //int last; /* one if this is the last block for a file */
  18122. {
  18123. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  18124. copy_block(s, buf, stored_len, true); /* with header */
  18125. }
  18126. /* ===========================================================================
  18127. * Send one empty static block to give enough lookahead for inflate.
  18128. * This takes 10 bits, of which 7 may remain in the bit buffer.
  18129. */
  18130. function _tr_align(s) {
  18131. send_bits(s, STATIC_TREES<<1, 3);
  18132. send_code(s, END_BLOCK, static_ltree);
  18133. bi_flush(s);
  18134. }
  18135. /* ===========================================================================
  18136. * Determine the best encoding for the current block: dynamic trees, static
  18137. * trees or store, and output the encoded block to the zip file.
  18138. */
  18139. function _tr_flush_block(s, buf, stored_len, last)
  18140. //DeflateState *s;
  18141. //charf *buf; /* input block, or NULL if too old */
  18142. //ulg stored_len; /* length of input block */
  18143. //int last; /* one if this is the last block for a file */
  18144. {
  18145. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  18146. var max_blindex = 0; /* index of last bit length code of non zero freq */
  18147. /* Build the Huffman trees unless a stored block is forced */
  18148. if (s.level > 0) {
  18149. /* Check if the file is binary or text */
  18150. if (s.strm.data_type === Z_UNKNOWN) {
  18151. s.strm.data_type = detect_data_type(s);
  18152. }
  18153. /* Construct the literal and distance trees */
  18154. build_tree(s, s.l_desc);
  18155. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  18156. // s->static_len));
  18157. build_tree(s, s.d_desc);
  18158. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  18159. // s->static_len));
  18160. /* At this point, opt_len and static_len are the total bit lengths of
  18161. * the compressed block data, excluding the tree representations.
  18162. */
  18163. /* Build the bit length tree for the above two trees, and get the index
  18164. * in bl_order of the last bit length code to send.
  18165. */
  18166. max_blindex = build_bl_tree(s);
  18167. /* Determine the best encoding. Compute the block lengths in bytes. */
  18168. opt_lenb = (s.opt_len+3+7) >>> 3;
  18169. static_lenb = (s.static_len+3+7) >>> 3;
  18170. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  18171. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  18172. // s->last_lit));
  18173. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18174. } else {
  18175. // Assert(buf != (char*)0, "lost buf");
  18176. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18177. }
  18178. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  18179. /* 4: two words for the lengths */
  18180. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18181. * Otherwise we can't have processed more than WSIZE input bytes since
  18182. * the last block flush, because compression would have been
  18183. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18184. * transform a block into a stored block.
  18185. */
  18186. _tr_stored_block(s, buf, stored_len, last);
  18187. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18188. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  18189. compress_block(s, static_ltree, static_dtree);
  18190. } else {
  18191. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  18192. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  18193. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18194. }
  18195. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18196. /* The above check is made mod 2^32, for files larger than 512 MB
  18197. * and uLong implemented on 32 bits.
  18198. */
  18199. init_block(s);
  18200. if (last) {
  18201. bi_windup(s);
  18202. }
  18203. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18204. // s->compressed_len-7*last));
  18205. }
  18206. /* ===========================================================================
  18207. * Save the match info and tally the frequency counts. Return true if
  18208. * the current block must be flushed.
  18209. */
  18210. function _tr_tally(s, dist, lc)
  18211. // deflate_state *s;
  18212. // unsigned dist; /* distance of matched string */
  18213. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18214. {
  18215. //var out_length, in_length, dcode;
  18216. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18217. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18218. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18219. s.last_lit++;
  18220. if (dist === 0) {
  18221. /* lc is the unmatched char */
  18222. s.dyn_ltree[lc*2]/*.Freq*/++;
  18223. } else {
  18224. s.matches++;
  18225. /* Here, lc is the match length - MIN_MATCH */
  18226. dist--; /* dist = match distance - 1 */
  18227. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18228. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18229. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18230. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18231. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18232. }
  18233. // (!) This block is disabled in zlib defailts,
  18234. // don't enable it for binary compatibility
  18235. //#ifdef TRUNCATE_BLOCK
  18236. // /* Try to guess if it is profitable to stop the current block here */
  18237. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18238. // /* Compute an upper bound for the compressed length */
  18239. // out_length = s.last_lit*8;
  18240. // in_length = s.strstart - s.block_start;
  18241. //
  18242. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18243. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18244. // }
  18245. // out_length >>>= 3;
  18246. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18247. // // s->last_lit, in_length, out_length,
  18248. // // 100L - out_length*100L/in_length));
  18249. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18250. // return true;
  18251. // }
  18252. // }
  18253. //#endif
  18254. return (s.last_lit === s.lit_bufsize-1);
  18255. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18256. * on 16 bit machines and because stored blocks are restricted to
  18257. * 64K-1 bytes.
  18258. */
  18259. }
  18260. exports._tr_init = _tr_init;
  18261. exports._tr_stored_block = _tr_stored_block;
  18262. exports._tr_flush_block = _tr_flush_block;
  18263. exports._tr_tally = _tr_tally;
  18264. exports._tr_align = _tr_align;
  18265. },{"../utils/common":51}],63:[function(require,module,exports){
  18266. 'use strict';
  18267. function ZStream() {
  18268. /* next input byte */
  18269. this.input = null; // JS specific, because we have no pointers
  18270. this.next_in = 0;
  18271. /* number of bytes available at input */
  18272. this.avail_in = 0;
  18273. /* total number of input bytes read so far */
  18274. this.total_in = 0;
  18275. /* next output byte should be put there */
  18276. this.output = null; // JS specific, because we have no pointers
  18277. this.next_out = 0;
  18278. /* remaining free space at output */
  18279. this.avail_out = 0;
  18280. /* total number of bytes output so far */
  18281. this.total_out = 0;
  18282. /* last error message, NULL if no error */
  18283. this.msg = ''/*Z_NULL*/;
  18284. /* not visible by applications */
  18285. this.state = null;
  18286. /* best guess about the data type: binary or text */
  18287. this.data_type = 2/*Z_UNKNOWN*/;
  18288. /* adler32 value of the uncompressed data */
  18289. this.adler = 0;
  18290. }
  18291. module.exports = ZStream;
  18292. },{}],64:[function(require,module,exports){
  18293. /* Copyright @ 2015 Atlassian Pty Ltd
  18294. *
  18295. * Licensed under the Apache License, Version 2.0 (the "License");
  18296. * you may not use this file except in compliance with the License.
  18297. * You may obtain a copy of the License at
  18298. *
  18299. * http://www.apache.org/licenses/LICENSE-2.0
  18300. *
  18301. * Unless required by applicable law or agreed to in writing, software
  18302. * distributed under the License is distributed on an "AS IS" BASIS,
  18303. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18304. * See the License for the specific language governing permissions and
  18305. * limitations under the License.
  18306. */
  18307. module.exports = function arrayEquals(array) {
  18308. // if the other array is a falsy value, return
  18309. if (!array)
  18310. return false;
  18311. // compare lengths - can save a lot of time
  18312. if (this.length != array.length)
  18313. return false;
  18314. for (var i = 0, l = this.length; i < l; i++) {
  18315. // Check if we have nested arrays
  18316. if (this[i] instanceof Array && array[i] instanceof Array) {
  18317. // recurse into the nested arrays
  18318. if (!arrayEquals.apply(this[i], [array[i]]))
  18319. return false;
  18320. } else if (this[i] != array[i]) {
  18321. // Warning - two different object instances will never be equal:
  18322. // {x:20} != {x:20}
  18323. return false;
  18324. }
  18325. }
  18326. return true;
  18327. };
  18328. },{}],65:[function(require,module,exports){
  18329. /* Copyright @ 2015 Atlassian Pty Ltd
  18330. *
  18331. * Licensed under the Apache License, Version 2.0 (the "License");
  18332. * you may not use this file except in compliance with the License.
  18333. * You may obtain a copy of the License at
  18334. *
  18335. * http://www.apache.org/licenses/LICENSE-2.0
  18336. *
  18337. * Unless required by applicable law or agreed to in writing, software
  18338. * distributed under the License is distributed on an "AS IS" BASIS,
  18339. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18340. * See the License for the specific language governing permissions and
  18341. * limitations under the License.
  18342. */
  18343. exports.Interop = require('./interop');
  18344. },{"./interop":66}],66:[function(require,module,exports){
  18345. /* Copyright @ 2015 Atlassian Pty Ltd
  18346. *
  18347. * Licensed under the Apache License, Version 2.0 (the "License");
  18348. * you may not use this file except in compliance with the License.
  18349. * You may obtain a copy of the License at
  18350. *
  18351. * http://www.apache.org/licenses/LICENSE-2.0
  18352. *
  18353. * Unless required by applicable law or agreed to in writing, software
  18354. * distributed under the License is distributed on an "AS IS" BASIS,
  18355. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18356. * See the License for the specific language governing permissions and
  18357. * limitations under the License.
  18358. */
  18359. /* global RTCSessionDescription */
  18360. /* jshint -W097 */
  18361. "use strict";
  18362. var transform = require('./transform');
  18363. var arrayEquals = require('./array-equals');
  18364. function Interop() {
  18365. /**
  18366. * This map holds the most recent Unified Plan offer/answer SDP that was
  18367. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  18368. * the SDP string as values.
  18369. *
  18370. * @type {{}}
  18371. */
  18372. this.cache = {};
  18373. }
  18374. module.exports = Interop;
  18375. /**
  18376. * Returns the index of the first m-line with the given media type and with a
  18377. * direction which allows sending, in the last Unified Plan description with
  18378. * type "answer" converted to Plan B. Returns {null} if there is no saved
  18379. * answer, or if none of its m-lines with the given type allow sending.
  18380. * @param type the media type ("audio" or "video").
  18381. * @returns {*}
  18382. */
  18383. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  18384. if (!this.cache.answer) {
  18385. return null;
  18386. }
  18387. var session = transform.parse(this.cache.answer);
  18388. if (session && session.media && Array.isArray(session.media)){
  18389. for (var i = 0; i < session.media.length; i++) {
  18390. if (session.media[i].type == type &&
  18391. (!session.media[i].direction /* default to sendrecv */ ||
  18392. session.media[i].direction === 'sendrecv' ||
  18393. session.media[i].direction === 'sendonly')){
  18394. return i;
  18395. }
  18396. }
  18397. }
  18398. return null;
  18399. };
  18400. /**
  18401. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  18402. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  18403. * application.
  18404. *
  18405. * @param desc
  18406. * @returns {*}
  18407. */
  18408. Interop.prototype.toPlanB = function(desc) {
  18409. var self = this;
  18410. //#region Preliminary input validation.
  18411. if (typeof desc !== 'object' || desc === null ||
  18412. typeof desc.sdp !== 'string') {
  18413. console.warn('An empty description was passed as an argument.');
  18414. return desc;
  18415. }
  18416. // Objectify the SDP for easier manipulation.
  18417. var session = transform.parse(desc.sdp);
  18418. // If the SDP contains no media, there's nothing to transform.
  18419. if (typeof session.media === 'undefined' ||
  18420. !Array.isArray(session.media) || session.media.length === 0) {
  18421. console.warn('The description has no media.');
  18422. return desc;
  18423. }
  18424. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  18425. // SDP has a video, an audio and a data "channel" at most.
  18426. if (session.media.length <= 3 && session.media.every(function(m) {
  18427. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18428. })) {
  18429. console.warn('This description does not look like Unified Plan.');
  18430. return desc;
  18431. }
  18432. //#endregion
  18433. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  18434. var sdp = desc.sdp;
  18435. var rewrite = false;
  18436. for (var i = 0; i < session.media.length; i++) {
  18437. var uLine = session.media[i];
  18438. uLine.rtp.forEach(function(rtp) {
  18439. if (rtp.codec === 'NULL')
  18440. {
  18441. rewrite = true;
  18442. var offer = transform.parse(self.cache['offer']);
  18443. rtp.codec = offer.media[i].rtp[0].codec;
  18444. }
  18445. });
  18446. };
  18447. if (rewrite) {
  18448. sdp = transform.write(session);
  18449. }
  18450. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  18451. // -> Unified Plan transformation.
  18452. this.cache[desc.type] = sdp;
  18453. //#region Convert from Unified Plan to Plan B.
  18454. // We rebuild the session.media array.
  18455. var media = session.media;
  18456. session.media = [];
  18457. // Associative array that maps channel types to channel objects for fast
  18458. // access to channel objects by their type, e.g. type2bl['audio']->channel
  18459. // obj.
  18460. var type2bl = {};
  18461. // Used to build the group:BUNDLE value after the channels construction
  18462. // loop.
  18463. var types = [];
  18464. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  18465. media.forEach(function(uLine) {
  18466. // rtcp-mux is required in the Plan B SDP.
  18467. if ((typeof uLine.rtcpMux !== 'string' ||
  18468. uLine.rtcpMux !== 'rtcp-mux') &&
  18469. uLine.direction !== 'inactive') {
  18470. throw new Error('Cannot convert to Plan B because m-lines ' +
  18471. 'without the rtcp-mux attribute were found.');
  18472. }
  18473. if (uLine.type === 'application') {
  18474. session.media.push(uLine);
  18475. types.push(uLine.mid);
  18476. return;
  18477. }
  18478. // If we don't have a channel for this uLine.type, then use this
  18479. // uLine as the channel basis.
  18480. if (typeof type2bl[uLine.type] === 'undefined') {
  18481. type2bl[uLine.type] = uLine;
  18482. }
  18483. // Add sources to the channel and handle a=msid.
  18484. if (typeof uLine.sources === 'object') {
  18485. Object.keys(uLine.sources).forEach(function(ssrc) {
  18486. if (typeof type2bl[uLine.type].sources !== 'object')
  18487. type2bl[uLine.type].sources = {};
  18488. // Assign the sources to the channel.
  18489. type2bl[uLine.type].sources[ssrc] =
  18490. uLine.sources[ssrc];
  18491. if (typeof uLine.msid !== 'undefined') {
  18492. // In Plan B the msid is an SSRC attribute. Also, we don't
  18493. // care about the obsolete label and mslabel attributes.
  18494. //
  18495. // Note that it is not guaranteed that the uLine will
  18496. // have an msid. recvonly channels in particular don't have
  18497. // one.
  18498. type2bl[uLine.type].sources[ssrc].msid =
  18499. uLine.msid;
  18500. }
  18501. // NOTE ssrcs in ssrc groups will share msids, as
  18502. // draft-uberti-rtcweb-plan-00 mandates.
  18503. });
  18504. }
  18505. // Add ssrc groups to the channel.
  18506. if (typeof uLine.ssrcGroups !== 'undefined' &&
  18507. Array.isArray(uLine.ssrcGroups)) {
  18508. // Create the ssrcGroups array, if it's not defined.
  18509. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  18510. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  18511. type2bl[uLine.type].ssrcGroups = [];
  18512. }
  18513. type2bl[uLine.type].ssrcGroups =
  18514. type2bl[uLine.type].ssrcGroups.concat(
  18515. uLine.ssrcGroups);
  18516. }
  18517. if (type2bl[uLine.type] === uLine) {
  18518. // Copy ICE related stuff from the principal media line.
  18519. uLine.candidates = media[0].candidates;
  18520. uLine.iceUfrag = media[0].iceUfrag;
  18521. uLine.icePwd = media[0].icePwd;
  18522. uLine.fingerprint = media[0].fingerprint;
  18523. // Plan B mids are in ['audio', 'video', 'data']
  18524. uLine.mid = uLine.type;
  18525. // Plan B doesn't support/need the bundle-only attribute.
  18526. delete uLine.bundleOnly;
  18527. // In Plan B the msid is an SSRC attribute.
  18528. delete uLine.msid;
  18529. // Used to build the group:BUNDLE value after this loop.
  18530. types.push(uLine.type);
  18531. // Add the channel to the new media array.
  18532. session.media.push(uLine);
  18533. }
  18534. });
  18535. // We regenerate the BUNDLE group with the new mids.
  18536. session.groups.some(function(group) {
  18537. if (group.type === 'BUNDLE') {
  18538. group.mids = types.join(' ');
  18539. return true;
  18540. }
  18541. });
  18542. // msid semantic
  18543. session.msidSemantic = {
  18544. semantic: 'WMS',
  18545. token: '*'
  18546. };
  18547. var resStr = transform.write(session);
  18548. return new RTCSessionDescription({
  18549. type: desc.type,
  18550. sdp: resStr
  18551. });
  18552. //#endregion
  18553. };
  18554. /**
  18555. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  18556. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  18557. * to FF.
  18558. *
  18559. * @param desc
  18560. * @returns {*}
  18561. */
  18562. Interop.prototype.toUnifiedPlan = function(desc) {
  18563. var self = this;
  18564. //#region Preliminary input validation.
  18565. if (typeof desc !== 'object' || desc === null ||
  18566. typeof desc.sdp !== 'string') {
  18567. console.warn('An empty description was passed as an argument.');
  18568. return desc;
  18569. }
  18570. var session = transform.parse(desc.sdp);
  18571. // If the SDP contains no media, there's nothing to transform.
  18572. if (typeof session.media === 'undefined' ||
  18573. !Array.isArray(session.media) || session.media.length === 0) {
  18574. console.warn('The description has no media.');
  18575. return desc;
  18576. }
  18577. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  18578. // a video, an audio and a data "channel" at most.
  18579. if (session.media.length > 3 || !session.media.every(function(m) {
  18580. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18581. })) {
  18582. console.warn('This description does not look like Plan B.');
  18583. return desc;
  18584. }
  18585. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  18586. var mids = [];
  18587. session.media.forEach(function(m) {
  18588. mids.push(m.mid);
  18589. });
  18590. var hasBundle = false;
  18591. if (typeof session.groups !== 'undefined' &&
  18592. Array.isArray(session.groups)) {
  18593. hasBundle = session.groups.every(function(g) {
  18594. return g.type !== 'BUNDLE' ||
  18595. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  18596. });
  18597. }
  18598. if (!hasBundle) {
  18599. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  18600. " are not bundled were found.");
  18601. }
  18602. //#endregion
  18603. //#region Convert from Plan B to Unified Plan.
  18604. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  18605. // rebuild an equivalent Unified Plan offer/answer.
  18606. //
  18607. // For example, if this is a local answer (in Unified Plan style) that we
  18608. // convert to Plan B prior to handing it over to the application (the
  18609. // PeerConnection wrapper called us, for instance, after a successful
  18610. // createAnswer), we want to remember the m-line at which we've seen the
  18611. // (local) SSRC. That's because when the application wants to do call the
  18612. // SLD method, forcing us to do the inverse transformation (from Plan B to
  18613. // Unified Plan), we need to know to which m-line to assign the (local)
  18614. // SSRC. We also need to know all the other m-lines that the original
  18615. // answer had and include them in the transformed answer as well.
  18616. //
  18617. // Another example is if this is a remote offer that we convert to Plan B
  18618. // prior to giving it to the application, we want to remember the mid at
  18619. // which we've seen the (remote) SSRC.
  18620. //
  18621. // In the iteration that follows, we use the cached Unified Plan (if it
  18622. // exists) to assign mids to ssrcs.
  18623. var cached;
  18624. if (typeof this.cache[desc.type] !== 'undefined') {
  18625. cached = transform.parse(this.cache[desc.type]);
  18626. }
  18627. var recvonlySsrcs = {
  18628. audio: {},
  18629. video: {}
  18630. };
  18631. // A helper map that sends mids to m-line objects. We use it later to
  18632. // rebuild the Unified Plan style session.media array.
  18633. var mid2ul = {};
  18634. session.media.forEach(function(bLine) {
  18635. if ((typeof bLine.rtcpMux !== 'string' ||
  18636. bLine.rtcpMux !== 'rtcp-mux') &&
  18637. bLine.direction !== 'inactive') {
  18638. throw new Error("Cannot convert to Unified Plan because m-lines " +
  18639. "without the rtcp-mux attribute were found.");
  18640. }
  18641. if (bLine.type === 'application') {
  18642. mid2ul[bLine.mid] = bLine;
  18643. return;
  18644. }
  18645. // With rtcp-mux and bundle all the channels should have the same ICE
  18646. // stuff.
  18647. var sources = bLine.sources;
  18648. var ssrcGroups = bLine.ssrcGroups;
  18649. var candidates = bLine.candidates;
  18650. var iceUfrag = bLine.iceUfrag;
  18651. var icePwd = bLine.icePwd;
  18652. var fingerprint = bLine.fingerprint;
  18653. var port = bLine.port;
  18654. // We'll use the "bLine" object as a prototype for each new "mLine"
  18655. // that we create, but first we need to clean it up a bit.
  18656. delete bLine.sources;
  18657. delete bLine.ssrcGroups;
  18658. delete bLine.candidates;
  18659. delete bLine.iceUfrag;
  18660. delete bLine.icePwd;
  18661. delete bLine.fingerprint;
  18662. delete bLine.port;
  18663. delete bLine.mid;
  18664. // inverted ssrc group map
  18665. var ssrc2group = {};
  18666. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  18667. ssrcGroups.forEach(function (ssrcGroup) {
  18668. // TODO(gp) find out how to receive simulcast with FF. For the
  18669. // time being, hide it.
  18670. if (ssrcGroup.semantics === 'SIM') {
  18671. return;
  18672. }
  18673. // XXX This might brake if an SSRC is in more than one group
  18674. // for some reason.
  18675. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18676. Array.isArray(ssrcGroup.ssrcs)) {
  18677. ssrcGroup.ssrcs.forEach(function (ssrc) {
  18678. if (typeof ssrc2group[ssrc] === 'undefined') {
  18679. ssrc2group[ssrc] = [];
  18680. }
  18681. ssrc2group[ssrc].push(ssrcGroup);
  18682. });
  18683. }
  18684. });
  18685. }
  18686. // ssrc to m-line index.
  18687. var ssrc2ml = {};
  18688. if (typeof sources === 'object') {
  18689. // Explode the Plan B channel sources with one m-line per source.
  18690. Object.keys(sources).forEach(function(ssrc) {
  18691. // The (unified) m-line for this SSRC. We either create it from
  18692. // scratch or, if it's a grouped SSRC, we re-use a related
  18693. // mline. In other words, if the source is grouped with another
  18694. // source, put the two together in the same m-line.
  18695. var uLine;
  18696. // We assume here that we are the answerer in the O/A, so any
  18697. // offers which we translate come from the remote side, while
  18698. // answers are local. So the check below is to make that we
  18699. // handle receive-only SSRCs in a special way only if they come
  18700. // from the remote side.
  18701. if (desc.type==='offer') {
  18702. // We want to detect SSRCs which are used by a remote peer
  18703. // in an m-line with direction=recvonly (i.e. they are
  18704. // being used for RTCP only).
  18705. // This information would have gotten lost if the remote
  18706. // peer used Unified Plan and their local description was
  18707. // translated to Plan B. So we use the lack of an MSID
  18708. // attribute to deduce a "receive only" SSRC.
  18709. if (!sources[ssrc].msid) {
  18710. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  18711. // Receive-only SSRCs must not create new m-lines. We
  18712. // will assign them to an existing m-line later.
  18713. return;
  18714. }
  18715. }
  18716. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  18717. Array.isArray(ssrc2group[ssrc])) {
  18718. ssrc2group[ssrc].some(function (ssrcGroup) {
  18719. // ssrcGroup.ssrcs *is* an Array, no need to check
  18720. // again here.
  18721. return ssrcGroup.ssrcs.some(function (related) {
  18722. if (typeof ssrc2ml[related] === 'object') {
  18723. uLine = ssrc2ml[related];
  18724. return true;
  18725. }
  18726. });
  18727. });
  18728. }
  18729. if (typeof uLine === 'object') {
  18730. // the m-line already exists. Just add the source.
  18731. uLine.sources[ssrc] = sources[ssrc];
  18732. delete sources[ssrc].msid;
  18733. } else {
  18734. // Use the "bLine" as a prototype for the "uLine".
  18735. uLine = Object.create(bLine);
  18736. ssrc2ml[ssrc] = uLine;
  18737. if (typeof sources[ssrc].msid !== 'undefined') {
  18738. // Assign the msid of the source to the m-line. Note
  18739. // that it is not guaranteed that the source will have
  18740. // msid. In particular "recvonly" sources don't have an
  18741. // msid. Note that "recvonly" is a term only defined
  18742. // for m-lines.
  18743. uLine.msid = sources[ssrc].msid;
  18744. uLine.direction = 'sendrecv';
  18745. delete sources[ssrc].msid;
  18746. }
  18747. // We assign one SSRC per media line.
  18748. uLine.sources = {};
  18749. uLine.sources[ssrc] = sources[ssrc];
  18750. uLine.ssrcGroups = ssrc2group[ssrc];
  18751. // Use the cached Unified Plan SDP (if it exists) to assign
  18752. // SSRCs to mids.
  18753. if (typeof cached !== 'undefined' &&
  18754. typeof cached.media !== 'undefined' &&
  18755. Array.isArray(cached.media)) {
  18756. cached.media.forEach(function (m) {
  18757. if (typeof m.sources === 'object') {
  18758. Object.keys(m.sources).forEach(function (s) {
  18759. if (s === ssrc) {
  18760. uLine.mid = m.mid;
  18761. }
  18762. });
  18763. }
  18764. });
  18765. }
  18766. if (typeof uLine.mid === 'undefined') {
  18767. // If this is an SSRC that we see for the first time
  18768. // assign it a new mid. This is typically the case when
  18769. // this method is called to transform a remote
  18770. // description for the first time or when there is a
  18771. // new SSRC in the remote description because a new
  18772. // peer has joined the conference. Local SSRCs should
  18773. // have already been added to the map in the toPlanB
  18774. // method.
  18775. //
  18776. // Because FF generates answers in Unified Plan style,
  18777. // we MUST already have a cached answer with all the
  18778. // local SSRCs mapped to some m-line/mid.
  18779. if (desc.type === 'answer') {
  18780. throw new Error("An unmapped SSRC was found.");
  18781. }
  18782. uLine.mid = [bLine.type, '-', ssrc].join('');
  18783. }
  18784. // Include the candidates in the 1st media line.
  18785. uLine.candidates = candidates;
  18786. uLine.iceUfrag = iceUfrag;
  18787. uLine.icePwd = icePwd;
  18788. uLine.fingerprint = fingerprint;
  18789. uLine.port = port;
  18790. mid2ul[uLine.mid] = uLine;
  18791. }
  18792. });
  18793. }
  18794. });
  18795. // Rebuild the media array in the right order and add the missing mLines
  18796. // (missing from the Plan B SDP).
  18797. session.media = [];
  18798. mids = []; // reuse
  18799. if (desc.type === 'answer') {
  18800. // The media lines in the answer must match the media lines in the
  18801. // offer. The order is important too. Here we assume that Firefox is
  18802. // the answerer, so we merely have to use the reconstructed (unified)
  18803. // answer to update the cached (unified) answer accordingly.
  18804. //
  18805. // In the general case, one would have to use the cached (unified)
  18806. // offer to find the m-lines that are missing from the reconstructed
  18807. // answer, potentially grabbing them from the cached (unified) answer.
  18808. // One has to be careful with this approach because inactive m-lines do
  18809. // not always have an mid, making it tricky (impossible?) to find where
  18810. // exactly and which m-lines are missing from the reconstructed answer.
  18811. for (var i = 0; i < cached.media.length; i++) {
  18812. var uLine = cached.media[i];
  18813. if (typeof mid2ul[uLine.mid] === 'undefined') {
  18814. // The mid isn't in the reconstructed (unified) answer.
  18815. // This is either a (unified) m-line containing a remote
  18816. // track only, or a (unified) m-line containing a remote
  18817. // track and a local track that has been removed.
  18818. // In either case, it MUST exist in the cached
  18819. // (unified) answer.
  18820. //
  18821. // In case this is a removed local track, clean-up
  18822. // the (unified) m-line and make sure it's 'recvonly' or
  18823. // 'inactive'.
  18824. delete uLine.msid;
  18825. delete uLine.sources;
  18826. delete uLine.ssrcGroups;
  18827. if (!uLine.direction
  18828. || uLine.direction === 'sendrecv')
  18829. uLine.direction = 'recvonly';
  18830. else if (uLine.direction === 'sendonly')
  18831. uLine.direction = 'inactive';
  18832. } else {
  18833. // This is an (unified) m-line/channel that contains a local
  18834. // track (sendrecv or sendonly channel) or it's a unified
  18835. // recvonly m-line/channel. In either case, since we're
  18836. // going from PlanB -> Unified Plan this m-line MUST
  18837. // exist in the cached answer.
  18838. }
  18839. session.media.push(uLine);
  18840. if (typeof uLine.mid === 'string') {
  18841. // inactive lines don't/may not have an mid.
  18842. mids.push(uLine.mid);
  18843. }
  18844. }
  18845. } else {
  18846. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  18847. // under any circumstances. If we are no longer interested in sending a
  18848. // track, we just remove the msid and ssrc attributes and set it to
  18849. // either a=recvonly (as the reofferer, we must use recvonly if the
  18850. // other side was previously sending on the m-section, but we can also
  18851. // leave the possibility open if it wasn't previously in use), or
  18852. // a=inactive.
  18853. if (typeof cached !== 'undefined' &&
  18854. typeof cached.media !== 'undefined' &&
  18855. Array.isArray(cached.media)) {
  18856. cached.media.forEach(function(uLine) {
  18857. mids.push(uLine.mid);
  18858. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  18859. session.media.push(mid2ul[uLine.mid]);
  18860. } else {
  18861. delete uLine.msid;
  18862. delete uLine.sources;
  18863. delete uLine.ssrcGroups;
  18864. if (!uLine.direction
  18865. || uLine.direction === 'sendrecv')
  18866. uLine.direction = 'recvonly';
  18867. if (!uLine.direction
  18868. || uLine.direction === 'sendonly')
  18869. uLine.direction = 'inactive';
  18870. session.media.push(uLine);
  18871. }
  18872. });
  18873. }
  18874. // Add all the remaining (new) m-lines of the transformed SDP.
  18875. Object.keys(mid2ul).forEach(function(mid) {
  18876. if (mids.indexOf(mid) === -1) {
  18877. mids.push(mid);
  18878. if (mid2ul[mid].direction === 'recvonly') {
  18879. // This is a remote recvonly channel. Add its SSRC to the
  18880. // appropriate sendrecv or sendonly channel.
  18881. // TODO(gp) what if we don't have sendrecv/sendonly
  18882. // channel?
  18883. session.media.some(function (uLine) {
  18884. if ((uLine.direction === 'sendrecv' ||
  18885. uLine.direction === 'sendonly') &&
  18886. uLine.type === mid2ul[mid].type) {
  18887. // mid2ul[mid] shouldn't have any ssrc-groups
  18888. Object.keys(mid2ul[mid].sources).forEach(
  18889. function (ssrc) {
  18890. uLine.sources[ssrc] =
  18891. mid2ul[mid].sources[ssrc];
  18892. });
  18893. return true;
  18894. }
  18895. });
  18896. } else {
  18897. session.media.push(mid2ul[mid]);
  18898. }
  18899. }
  18900. });
  18901. }
  18902. // After we have constructed the Plan Unified m-lines we can figure out
  18903. // where (in which m-line) to place the 'recvonly SSRCs'.
  18904. // Note: we assume here that we are the answerer in the O/A, so any offers
  18905. // which we translate come from the remote side, while answers are local
  18906. // (and so our last local description is cached as an 'answer').
  18907. ["audio", "video"].forEach(function (type) {
  18908. if (!session || !session.media || !Array.isArray(session.media))
  18909. return;
  18910. var idx = null;
  18911. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  18912. idx = self.getFirstSendingIndexFromAnswer(type);
  18913. if (idx === null){
  18914. // If this is the first offer we receive, we don't have a
  18915. // cached answer. Assume that we will be sending media using
  18916. // the first m-line for each media type.
  18917. for (var i = 0; i < session.media.length; i++) {
  18918. if (session.media[i].type === type) {
  18919. idx = i;
  18920. break;
  18921. }
  18922. }
  18923. }
  18924. }
  18925. if (idx && session.media.length > idx) {
  18926. var mLine = session.media[idx];
  18927. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  18928. if (mLine.sources && mLine.sources[ssrc]) {
  18929. console.warn("Replacing an existing SSRC.");
  18930. }
  18931. if (!mLine.sources) {
  18932. mLine.sources = {};
  18933. }
  18934. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  18935. });
  18936. }
  18937. });
  18938. // We regenerate the BUNDLE group (since we regenerated the mids)
  18939. session.groups.some(function(group) {
  18940. if (group.type === 'BUNDLE') {
  18941. group.mids = mids.join(' ');
  18942. return true;
  18943. }
  18944. });
  18945. // msid semantic
  18946. session.msidSemantic = {
  18947. semantic: 'WMS',
  18948. token: '*'
  18949. };
  18950. var resStr = transform.write(session);
  18951. // Cache the transformed SDP (Unified Plan) for later re-use in this
  18952. // function.
  18953. this.cache[desc.type] = resStr;
  18954. return new RTCSessionDescription({
  18955. type: desc.type,
  18956. sdp: resStr
  18957. });
  18958. //#endregion
  18959. };
  18960. },{"./array-equals":64,"./transform":67}],67:[function(require,module,exports){
  18961. /* Copyright @ 2015 Atlassian Pty Ltd
  18962. *
  18963. * Licensed under the Apache License, Version 2.0 (the "License");
  18964. * you may not use this file except in compliance with the License.
  18965. * You may obtain a copy of the License at
  18966. *
  18967. * http://www.apache.org/licenses/LICENSE-2.0
  18968. *
  18969. * Unless required by applicable law or agreed to in writing, software
  18970. * distributed under the License is distributed on an "AS IS" BASIS,
  18971. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18972. * See the License for the specific language governing permissions and
  18973. * limitations under the License.
  18974. */
  18975. var transform = require('sdp-transform');
  18976. exports.write = function(session, opts) {
  18977. if (typeof session !== 'undefined' &&
  18978. typeof session.media !== 'undefined' &&
  18979. Array.isArray(session.media)) {
  18980. session.media.forEach(function (mLine) {
  18981. // expand sources to ssrcs
  18982. if (typeof mLine.sources !== 'undefined' &&
  18983. Object.keys(mLine.sources).length !== 0) {
  18984. mLine.ssrcs = [];
  18985. Object.keys(mLine.sources).forEach(function (ssrc) {
  18986. var source = mLine.sources[ssrc];
  18987. Object.keys(source).forEach(function (attribute) {
  18988. mLine.ssrcs.push({
  18989. id: ssrc,
  18990. attribute: attribute,
  18991. value: source[attribute]
  18992. });
  18993. });
  18994. });
  18995. delete mLine.sources;
  18996. }
  18997. // join ssrcs in ssrc groups
  18998. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18999. Array.isArray(mLine.ssrcGroups)) {
  19000. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19001. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  19002. Array.isArray(ssrcGroup.ssrcs)) {
  19003. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  19004. }
  19005. });
  19006. }
  19007. });
  19008. }
  19009. // join group mids
  19010. if (typeof session !== 'undefined' &&
  19011. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19012. session.groups.forEach(function (g) {
  19013. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  19014. g.mids = g.mids.join(' ');
  19015. }
  19016. });
  19017. }
  19018. return transform.write(session, opts);
  19019. };
  19020. exports.parse = function(sdp) {
  19021. var session = transform.parse(sdp);
  19022. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  19023. Array.isArray(session.media)) {
  19024. session.media.forEach(function (mLine) {
  19025. // group sources attributes by ssrc
  19026. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19027. mLine.sources = {};
  19028. mLine.ssrcs.forEach(function (ssrc) {
  19029. if (!mLine.sources[ssrc.id])
  19030. mLine.sources[ssrc.id] = {};
  19031. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19032. });
  19033. delete mLine.ssrcs;
  19034. }
  19035. // split ssrcs in ssrc groups
  19036. if (typeof mLine.ssrcGroups !== 'undefined' &&
  19037. Array.isArray(mLine.ssrcGroups)) {
  19038. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  19039. if (typeof ssrcGroup.ssrcs === 'string') {
  19040. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  19041. }
  19042. });
  19043. }
  19044. });
  19045. }
  19046. // split group mids
  19047. if (typeof session !== 'undefined' &&
  19048. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  19049. session.groups.forEach(function (g) {
  19050. if (typeof g.mids === 'string') {
  19051. g.mids = g.mids.split(' ');
  19052. }
  19053. });
  19054. }
  19055. return session;
  19056. };
  19057. },{"sdp-transform":75}],68:[function(require,module,exports){
  19058. /* Copyright @ 2015 Atlassian Pty Ltd
  19059. *
  19060. * Licensed under the Apache License, Version 2.0 (the "License");
  19061. * you may not use this file except in compliance with the License.
  19062. * You may obtain a copy of the License at
  19063. *
  19064. * http://www.apache.org/licenses/LICENSE-2.0
  19065. *
  19066. * Unless required by applicable law or agreed to in writing, software
  19067. * distributed under the License is distributed on an "AS IS" BASIS,
  19068. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19069. * See the License for the specific language governing permissions and
  19070. * limitations under the License.
  19071. */
  19072. var transform = require('sdp-transform');
  19073. var transformUtils = require('./transform-utils');
  19074. var parseSsrcs = transformUtils.parseSsrcs;
  19075. var writeSsrcs = transformUtils.writeSsrcs;
  19076. //region Constants
  19077. var DEFAULT_NUM_OF_LAYERS = 3;
  19078. //endregion
  19079. //region Ctor
  19080. function Simulcast(options) {
  19081. this.options = options ? options : {};
  19082. if (!this.options.numOfLayers) {
  19083. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  19084. }
  19085. this.layers = [];
  19086. }
  19087. //endregion
  19088. //region Stateless private utility functions
  19089. /**
  19090. * Returns a random integer between min (included) and max (excluded)
  19091. * Using Math.round() gives a non-uniform distribution!
  19092. * @returns {number}
  19093. */
  19094. function generateSSRC() {
  19095. var min = 0, max = 0xffffffff;
  19096. return Math.floor(Math.random() * (max - min)) + min;
  19097. };
  19098. function processVideo(session, action) {
  19099. if (session == null || !Array.isArray(session.media)) {
  19100. return;
  19101. }
  19102. session.media.forEach(function (mLine) {
  19103. if (mLine.type === 'video') {
  19104. action(mLine);
  19105. }
  19106. });
  19107. }
  19108. function validateDescription(desc)
  19109. {
  19110. return desc && desc != null
  19111. && desc.type && desc.type != ''
  19112. && desc.sdp && desc.sdp != '';
  19113. }
  19114. function explodeRemoteSimulcast(mLine) {
  19115. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19116. return;
  19117. }
  19118. var sources = parseSsrcs(mLine);
  19119. var order = [];
  19120. // Find the SIM group and explode its sources.
  19121. var j = mLine.ssrcGroups.length;
  19122. while (j--) {
  19123. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  19124. continue;
  19125. }
  19126. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  19127. for (var i = 0; i < simulcastSsrcs.length; i++) {
  19128. var ssrc = simulcastSsrcs[i];
  19129. order.push(ssrc);
  19130. var parts = sources[ssrc].msid.split(' ');
  19131. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  19132. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  19133. // Remove all the groups that this SSRC participates in.
  19134. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19135. if (relatedGroup.semantics === 'SIM') {
  19136. return;
  19137. }
  19138. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19139. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19140. return;
  19141. }
  19142. // Nuke all the related SSRCs.
  19143. relatedSsrcs.forEach(function (relatedSSRC) {
  19144. sources[relatedSSRC].msid = sources[ssrc].msid;
  19145. sources[relatedSSRC].cname = sources[ssrc].cname;
  19146. if (relatedSSRC !== ssrc) {
  19147. order.push(relatedSSRC);
  19148. }
  19149. });
  19150. // Schedule the related group for nuking.
  19151. })
  19152. }
  19153. mLine.ssrcs = writeSsrcs(sources, order);
  19154. mLine.ssrcGroups.splice(j, 1);
  19155. };
  19156. }
  19157. function implodeRemoteSimulcast(mLine) {
  19158. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  19159. console.debug('Halt: There are no SSRC groups in the remote ' +
  19160. 'description.');
  19161. return;
  19162. }
  19163. var sources = parseSsrcs(mLine);
  19164. // Find the SIM group and nuke it.
  19165. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  19166. if (simulcastGroup.semantics !== 'SIM') {
  19167. return;
  19168. }
  19169. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  19170. // Schedule the SIM group for nuking.
  19171. simulcastGroup.nuke = true;
  19172. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  19173. // Nuke all the higher layer SSRCs.
  19174. for (var i = 1; i < simulcastSsrcs.length; i++) {
  19175. var ssrc = simulcastSsrcs[i];
  19176. delete sources[ssrc];
  19177. // Remove all the groups that this SSRC participates in.
  19178. mLine.ssrcGroups.forEach(function (relatedGroup) {
  19179. if (relatedGroup.semantics === 'SIM') {
  19180. return;
  19181. }
  19182. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  19183. if (relatedSsrcs.indexOf(ssrc) === -1) {
  19184. return;
  19185. }
  19186. // Nuke all the related SSRCs.
  19187. relatedSsrcs.forEach(function (relatedSSRC) {
  19188. delete sources[relatedSSRC];
  19189. });
  19190. // Schedule the related group for nuking.
  19191. relatedGroup.nuke = true;
  19192. })
  19193. }
  19194. return;
  19195. });
  19196. mLine.ssrcs = writeSsrcs(sources);
  19197. // Nuke all the scheduled groups.
  19198. var i = mLine.ssrcGroups.length;
  19199. while (i--) {
  19200. if (mLine.ssrcGroups[i].nuke) {
  19201. mLine.ssrcGroups.splice(i, 1);
  19202. }
  19203. }
  19204. }
  19205. function removeGoogConference(mLine) {
  19206. if (!mLine || !Array.isArray(mLine.invalid)) {
  19207. return;
  19208. }
  19209. var i = mLine.invalid.length;
  19210. while (i--) {
  19211. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  19212. mLine.invalid.splice(i, 1);
  19213. }
  19214. }
  19215. }
  19216. function assertGoogConference(mLine) {
  19217. if (!mLine) {
  19218. return;
  19219. }
  19220. if (!Array.isArray(mLine.invalid)) {
  19221. mLine.invalid = [];
  19222. }
  19223. if (!mLine.invalid.some(
  19224. function (i) { return i.value === 'x-google-flag:conference' })) {
  19225. mLine.invalid.push({'value': 'x-google-flag:conference'});
  19226. }
  19227. }
  19228. //endregion
  19229. //region "Private" functions
  19230. /**
  19231. *
  19232. * @param mLine
  19233. * @private
  19234. */
  19235. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  19236. if (!mLine || mLine.type !== 'video') {
  19237. return;
  19238. }
  19239. var sources = parseSsrcs(mLine);
  19240. if (Object.keys(sources).length === 0) {
  19241. // no sources, disable simulcast.
  19242. if (this.layers.length !== 0) {
  19243. this.layers = [];
  19244. }
  19245. return;
  19246. }
  19247. // find the base layer (we'll reuse its msid and cname).
  19248. var baseLayerSSRC = Object.keys(sources)[0];
  19249. var baseLayer = sources[baseLayerSSRC];
  19250. // todo(gp) handle screen sharing.
  19251. // check if base CNAME has changed and reinitialise layers.
  19252. if (this.layers.length > 0
  19253. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  19254. this.layers = [];
  19255. }
  19256. // (re)initialise layers
  19257. if (this.layers.length < 1) {
  19258. // first push the base layer.
  19259. this.layers.push({
  19260. ssrc: baseLayerSSRC,
  19261. msid: baseLayer.msid,
  19262. cname: baseLayer.cname
  19263. });
  19264. var rtx = false; // RFC 4588
  19265. if (Array.isArray(mLine.rtp)) {
  19266. rtx = mLine.rtp.some(
  19267. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  19268. }
  19269. if (rtx) {
  19270. this.layers[0].rtx = generateSSRC();
  19271. }
  19272. // now push additional layers.
  19273. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  19274. var layer = { ssrc: generateSSRC() };
  19275. if (rtx) {
  19276. layer.rtx = generateSSRC();
  19277. }
  19278. this.layers.push(layer);
  19279. }
  19280. }
  19281. };
  19282. /**
  19283. *
  19284. * @param mLine
  19285. * @private
  19286. */
  19287. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  19288. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  19289. var sources = {};
  19290. var msid = this.layers[0].msid;
  19291. var cname = this.layers[0].cname;
  19292. var simulcastSsrcs = [];
  19293. var ssrcGroups = [];
  19294. for (var i = 0; i < this.layers.length; i++) {
  19295. var layer = this.layers[i];
  19296. sources[layer.ssrc] = { msid: msid, cname: cname };
  19297. simulcastSsrcs.push(layer.ssrc);
  19298. if (layer.rtx) {
  19299. sources[layer.rtx] = {
  19300. msid: msid,
  19301. cname: cname
  19302. }
  19303. ssrcGroups.push({
  19304. semantics: 'FID',
  19305. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  19306. });
  19307. }
  19308. }
  19309. ssrcGroups.push({
  19310. semantics: 'SIM',
  19311. ssrcs: simulcastSsrcs.join(' ')
  19312. });
  19313. mLine.ssrcGroups = ssrcGroups;
  19314. mLine.ssrcs = writeSsrcs(sources);
  19315. }
  19316. }
  19317. //endregion
  19318. //region "Public" functions
  19319. Simulcast.prototype.isSupported = function () {
  19320. return window.chrome;
  19321. // TODO this needs improvements. For example I doubt that Chrome in Android
  19322. // has simulcast support. Also, only recent versions of Chromium have native
  19323. // simulcast support.
  19324. }
  19325. /**
  19326. *
  19327. * @param desc
  19328. * @returns {RTCSessionDescription}
  19329. */
  19330. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  19331. if (!validateDescription(desc)) {
  19332. return desc;
  19333. }
  19334. var session = transform.parse(desc.sdp);
  19335. var self = this;
  19336. processVideo(session, function (mLine) {
  19337. // Handle simulcast reception.
  19338. if (self.options.explodeRemoteSimulcast) {
  19339. explodeRemoteSimulcast(mLine);
  19340. } else {
  19341. implodeRemoteSimulcast(mLine);
  19342. }
  19343. // If native simulcast is enabled, we must append the x-goog-conference
  19344. // attribute to the SDP.
  19345. if (self.layers.length < 1) {
  19346. removeGoogConference(mLine);
  19347. } else {
  19348. assertGoogConference(mLine);
  19349. }
  19350. });
  19351. return new RTCSessionDescription({
  19352. type: desc.type,
  19353. sdp: transform.write(session)
  19354. });
  19355. };
  19356. /**
  19357. *
  19358. * @param desc
  19359. * @returns {RTCSessionDescription}
  19360. */
  19361. Simulcast.prototype.mungeLocalDescription = function (desc) {
  19362. if (!validateDescription(desc) || !this.isSupported()) {
  19363. return desc;
  19364. }
  19365. var session = transform.parse(desc.sdp);
  19366. var self = this;
  19367. processVideo(session, function (mLine) {
  19368. // Initialize native simulcast layers, if not already done.
  19369. self._maybeInitializeLayers(mLine);
  19370. // Update the SDP with the simulcast layers.
  19371. self._restoreSimulcastView(mLine);
  19372. });
  19373. return new RTCSessionDescription({
  19374. type: desc.type,
  19375. sdp: transform.write(session)
  19376. });
  19377. };
  19378. //endregion
  19379. module.exports = Simulcast;
  19380. },{"./transform-utils":69,"sdp-transform":71}],69:[function(require,module,exports){
  19381. /* Copyright @ 2015 Atlassian Pty Ltd
  19382. *
  19383. * Licensed under the Apache License, Version 2.0 (the "License");
  19384. * you may not use this file except in compliance with the License.
  19385. * You may obtain a copy of the License at
  19386. *
  19387. * http://www.apache.org/licenses/LICENSE-2.0
  19388. *
  19389. * Unless required by applicable law or agreed to in writing, software
  19390. * distributed under the License is distributed on an "AS IS" BASIS,
  19391. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19392. * See the License for the specific language governing permissions and
  19393. * limitations under the License.
  19394. */
  19395. exports.writeSsrcs = function(sources, order) {
  19396. var ssrcs = [];
  19397. // expand sources to ssrcs
  19398. if (typeof sources !== 'undefined' &&
  19399. Object.keys(sources).length !== 0) {
  19400. if (Array.isArray(order)) {
  19401. for (var i = 0; i < order.length; i++) {
  19402. var ssrc = order[i];
  19403. var source = sources[ssrc];
  19404. Object.keys(source).forEach(function (attribute) {
  19405. ssrcs.push({
  19406. id: ssrc,
  19407. attribute: attribute,
  19408. value: source[attribute]
  19409. });
  19410. });
  19411. }
  19412. } else {
  19413. Object.keys(sources).forEach(function (ssrc) {
  19414. var source = sources[ssrc];
  19415. Object.keys(source).forEach(function (attribute) {
  19416. ssrcs.push({
  19417. id: ssrc,
  19418. attribute: attribute,
  19419. value: source[attribute]
  19420. });
  19421. });
  19422. });
  19423. }
  19424. }
  19425. return ssrcs;
  19426. };
  19427. exports.parseSsrcs = function (mLine) {
  19428. var sources = {};
  19429. // group sources attributes by ssrc.
  19430. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19431. mLine.ssrcs.forEach(function (ssrc) {
  19432. if (!sources[ssrc.id])
  19433. sources[ssrc.id] = {};
  19434. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19435. });
  19436. }
  19437. return sources;
  19438. };
  19439. },{}],70:[function(require,module,exports){
  19440. var grammar = module.exports = {
  19441. v: [{
  19442. name: 'version',
  19443. reg: /^(\d*)$/
  19444. }],
  19445. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19446. // NB: sessionId will be a String in most cases because it is huge
  19447. name: 'origin',
  19448. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19449. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19450. format: "%s %s %d %s IP%d %s"
  19451. }],
  19452. // default parsing of these only (though some of these feel outdated)
  19453. s: [{ name: 'name' }],
  19454. i: [{ name: 'description' }],
  19455. u: [{ name: 'uri' }],
  19456. e: [{ name: 'email' }],
  19457. p: [{ name: 'phone' }],
  19458. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19459. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19460. //k: [{}], // outdated thing ignored
  19461. t: [{ //t=0 0
  19462. name: 'timing',
  19463. reg: /^(\d*) (\d*)/,
  19464. names: ['start', 'stop'],
  19465. format: "%d %d"
  19466. }],
  19467. c: [{ //c=IN IP4 10.47.197.26
  19468. name: 'connection',
  19469. reg: /^IN IP(\d) (\S*)/,
  19470. names: ['version', 'ip'],
  19471. format: "IN IP%d %s"
  19472. }],
  19473. b: [{ //b=AS:4000
  19474. push: 'bandwidth',
  19475. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19476. names: ['type', 'limit'],
  19477. format: "%s:%s"
  19478. }],
  19479. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19480. // NB: special - pushes to session
  19481. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19482. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19483. names: ['type', 'port', 'protocol', 'payloads'],
  19484. format: "%s %d %s %s"
  19485. }],
  19486. a: [
  19487. { //a=rtpmap:110 opus/48000/2
  19488. push: 'rtp',
  19489. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19490. names: ['payload', 'codec', 'rate', 'encoding'],
  19491. format: function (o) {
  19492. return (o.encoding) ?
  19493. "rtpmap:%d %s/%s/%s":
  19494. "rtpmap:%d %s/%s";
  19495. }
  19496. },
  19497. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19498. push: 'fmtp',
  19499. reg: /^fmtp:(\d*) (\S*)/,
  19500. names: ['payload', 'config'],
  19501. format: "fmtp:%d %s"
  19502. },
  19503. { //a=control:streamid=0
  19504. name: 'control',
  19505. reg: /^control:(.*)/,
  19506. format: "control:%s"
  19507. },
  19508. { //a=rtcp:65179 IN IP4 193.84.77.194
  19509. name: 'rtcp',
  19510. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19511. names: ['port', 'netType', 'ipVer', 'address'],
  19512. format: function (o) {
  19513. return (o.address != null) ?
  19514. "rtcp:%d %s IP%d %s":
  19515. "rtcp:%d";
  19516. }
  19517. },
  19518. { //a=rtcp-fb:98 trr-int 100
  19519. push: 'rtcpFbTrrInt',
  19520. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19521. names: ['payload', 'value'],
  19522. format: "rtcp-fb:%d trr-int %d"
  19523. },
  19524. { //a=rtcp-fb:98 nack rpsi
  19525. push: 'rtcpFb',
  19526. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19527. names: ['payload', 'type', 'subtype'],
  19528. format: function (o) {
  19529. return (o.subtype != null) ?
  19530. "rtcp-fb:%s %s %s":
  19531. "rtcp-fb:%s %s";
  19532. }
  19533. },
  19534. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19535. //a=extmap:1/recvonly URI-gps-string
  19536. push: 'ext',
  19537. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19538. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19539. format: function (o) {
  19540. return (o.config != null) ?
  19541. "extmap:%s %s %s":
  19542. "extmap:%s %s";
  19543. }
  19544. },
  19545. {
  19546. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19547. push: 'crypto',
  19548. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19549. names: ['id', 'suite', 'config', 'sessionConfig'],
  19550. format: function (o) {
  19551. return (o.sessionConfig != null) ?
  19552. "crypto:%d %s %s %s":
  19553. "crypto:%d %s %s";
  19554. }
  19555. },
  19556. { //a=setup:actpass
  19557. name: 'setup',
  19558. reg: /^setup:(\w*)/,
  19559. format: "setup:%s"
  19560. },
  19561. { //a=mid:1
  19562. name: 'mid',
  19563. reg: /^mid:([^\s]*)/,
  19564. format: "mid:%s"
  19565. },
  19566. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19567. name: 'msid',
  19568. reg: /^msid:(.*)/,
  19569. format: "msid:%s"
  19570. },
  19571. { //a=ptime:20
  19572. name: 'ptime',
  19573. reg: /^ptime:(\d*)/,
  19574. format: "ptime:%d"
  19575. },
  19576. { //a=maxptime:60
  19577. name: 'maxptime',
  19578. reg: /^maxptime:(\d*)/,
  19579. format: "maxptime:%d"
  19580. },
  19581. { //a=sendrecv
  19582. name: 'direction',
  19583. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19584. },
  19585. { //a=ice-lite
  19586. name: 'icelite',
  19587. reg: /^(ice-lite)/
  19588. },
  19589. { //a=ice-ufrag:F7gI
  19590. name: 'iceUfrag',
  19591. reg: /^ice-ufrag:(\S*)/,
  19592. format: "ice-ufrag:%s"
  19593. },
  19594. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19595. name: 'icePwd',
  19596. reg: /^ice-pwd:(\S*)/,
  19597. format: "ice-pwd:%s"
  19598. },
  19599. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19600. name: 'fingerprint',
  19601. reg: /^fingerprint:(\S*) (\S*)/,
  19602. names: ['type', 'hash'],
  19603. format: "fingerprint:%s %s"
  19604. },
  19605. {
  19606. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19607. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19608. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19609. push:'candidates',
  19610. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19611. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19612. format: function (o) {
  19613. var str = "candidate:%s %d %s %d %s %d typ %s";
  19614. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19615. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19616. if (o.generation != null) {
  19617. str += " generation %d";
  19618. }
  19619. return str;
  19620. }
  19621. },
  19622. { //a=end-of-candidates (keep after the candidates line for readability)
  19623. name: 'endOfCandidates',
  19624. reg: /^(end-of-candidates)/
  19625. },
  19626. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19627. name: 'remoteCandidates',
  19628. reg: /^remote-candidates:(.*)/,
  19629. format: "remote-candidates:%s"
  19630. },
  19631. { //a=ice-options:google-ice
  19632. name: 'iceOptions',
  19633. reg: /^ice-options:(\S*)/,
  19634. format: "ice-options:%s"
  19635. },
  19636. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19637. push: "ssrcs",
  19638. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19639. names: ['id', 'attribute', 'value'],
  19640. format: "ssrc:%d %s:%s"
  19641. },
  19642. { //a=ssrc-group:FEC 1 2
  19643. push: "ssrcGroups",
  19644. reg: /^ssrc-group:(\w*) (.*)/,
  19645. names: ['semantics', 'ssrcs'],
  19646. format: "ssrc-group:%s %s"
  19647. },
  19648. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19649. name: "msidSemantic",
  19650. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19651. names: ['semantic', 'token'],
  19652. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19653. },
  19654. { //a=group:BUNDLE audio video
  19655. push: 'groups',
  19656. reg: /^group:(\w*) (.*)/,
  19657. names: ['type', 'mids'],
  19658. format: "group:%s %s"
  19659. },
  19660. { //a=rtcp-mux
  19661. name: 'rtcpMux',
  19662. reg: /^(rtcp-mux)/
  19663. },
  19664. { //a=rtcp-rsize
  19665. name: 'rtcpRsize',
  19666. reg: /^(rtcp-rsize)/
  19667. },
  19668. { // any a= that we don't understand is kepts verbatim on media.invalid
  19669. push: 'invalid',
  19670. names: ["value"]
  19671. }
  19672. ]
  19673. };
  19674. // set sensible defaults to avoid polluting the grammar with boring details
  19675. Object.keys(grammar).forEach(function (key) {
  19676. var objs = grammar[key];
  19677. objs.forEach(function (obj) {
  19678. if (!obj.reg) {
  19679. obj.reg = /(.*)/;
  19680. }
  19681. if (!obj.format) {
  19682. obj.format = "%s";
  19683. }
  19684. });
  19685. });
  19686. },{}],71:[function(require,module,exports){
  19687. var parser = require('./parser');
  19688. var writer = require('./writer');
  19689. exports.write = writer;
  19690. exports.parse = parser.parse;
  19691. exports.parseFmtpConfig = parser.parseFmtpConfig;
  19692. exports.parsePayloads = parser.parsePayloads;
  19693. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  19694. },{"./parser":72,"./writer":73}],72:[function(require,module,exports){
  19695. var toIntIfInt = function (v) {
  19696. return String(Number(v)) === v ? Number(v) : v;
  19697. };
  19698. var attachProperties = function (match, location, names, rawName) {
  19699. if (rawName && !names) {
  19700. location[rawName] = toIntIfInt(match[1]);
  19701. }
  19702. else {
  19703. for (var i = 0; i < names.length; i += 1) {
  19704. if (match[i+1] != null) {
  19705. location[names[i]] = toIntIfInt(match[i+1]);
  19706. }
  19707. }
  19708. }
  19709. };
  19710. var parseReg = function (obj, location, content) {
  19711. var needsBlank = obj.name && obj.names;
  19712. if (obj.push && !location[obj.push]) {
  19713. location[obj.push] = [];
  19714. }
  19715. else if (needsBlank && !location[obj.name]) {
  19716. location[obj.name] = {};
  19717. }
  19718. var keyLocation = obj.push ?
  19719. {} : // blank object that will be pushed
  19720. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19721. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19722. if (obj.push) {
  19723. location[obj.push].push(keyLocation);
  19724. }
  19725. };
  19726. var grammar = require('./grammar');
  19727. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19728. exports.parse = function (sdp) {
  19729. var session = {}
  19730. , media = []
  19731. , location = session; // points at where properties go under (one of the above)
  19732. // parse lines we understand
  19733. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19734. var type = l[0];
  19735. var content = l.slice(2);
  19736. if (type === 'm') {
  19737. media.push({rtp: [], fmtp: []});
  19738. location = media[media.length-1]; // point at latest media line
  19739. }
  19740. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19741. var obj = grammar[type][j];
  19742. if (obj.reg.test(content)) {
  19743. return parseReg(obj, location, content);
  19744. }
  19745. }
  19746. });
  19747. session.media = media; // link it up
  19748. return session;
  19749. };
  19750. var fmtpReducer = function (acc, expr) {
  19751. var s = expr.split('=');
  19752. if (s.length === 2) {
  19753. acc[s[0]] = toIntIfInt(s[1]);
  19754. }
  19755. return acc;
  19756. };
  19757. exports.parseFmtpConfig = function (str) {
  19758. return str.split(';').reduce(fmtpReducer, {});
  19759. };
  19760. exports.parsePayloads = function (str) {
  19761. return str.split(' ').map(Number);
  19762. };
  19763. exports.parseRemoteCandidates = function (str) {
  19764. var candidates = [];
  19765. var parts = str.split(' ').map(toIntIfInt);
  19766. for (var i = 0; i < parts.length; i += 3) {
  19767. candidates.push({
  19768. component: parts[i],
  19769. ip: parts[i + 1],
  19770. port: parts[i + 2]
  19771. });
  19772. }
  19773. return candidates;
  19774. };
  19775. },{"./grammar":70}],73:[function(require,module,exports){
  19776. var grammar = require('./grammar');
  19777. // customized util.format - discards excess arguments and can void middle ones
  19778. var formatRegExp = /%[sdv%]/g;
  19779. var format = function (formatStr) {
  19780. var i = 1;
  19781. var args = arguments;
  19782. var len = args.length;
  19783. return formatStr.replace(formatRegExp, function (x) {
  19784. if (i >= len) {
  19785. return x; // missing argument
  19786. }
  19787. var arg = args[i];
  19788. i += 1;
  19789. switch (x) {
  19790. case '%%':
  19791. return '%';
  19792. case '%s':
  19793. return String(arg);
  19794. case '%d':
  19795. return Number(arg);
  19796. case '%v':
  19797. return '';
  19798. }
  19799. });
  19800. // NB: we discard excess arguments - they are typically undefined from makeLine
  19801. };
  19802. var makeLine = function (type, obj, location) {
  19803. var str = obj.format instanceof Function ?
  19804. (obj.format(obj.push ? location : location[obj.name])) :
  19805. obj.format;
  19806. var args = [type + '=' + str];
  19807. if (obj.names) {
  19808. for (var i = 0; i < obj.names.length; i += 1) {
  19809. var n = obj.names[i];
  19810. if (obj.name) {
  19811. args.push(location[obj.name][n]);
  19812. }
  19813. else { // for mLine and push attributes
  19814. args.push(location[obj.names[i]]);
  19815. }
  19816. }
  19817. }
  19818. else {
  19819. args.push(location[obj.name]);
  19820. }
  19821. return format.apply(null, args);
  19822. };
  19823. // RFC specified order
  19824. // TODO: extend this with all the rest
  19825. var defaultOuterOrder = [
  19826. 'v', 'o', 's', 'i',
  19827. 'u', 'e', 'p', 'c',
  19828. 'b', 't', 'r', 'z', 'a'
  19829. ];
  19830. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  19831. module.exports = function (session, opts) {
  19832. opts = opts || {};
  19833. // ensure certain properties exist
  19834. if (session.version == null) {
  19835. session.version = 0; // "v=0" must be there (only defined version atm)
  19836. }
  19837. if (session.name == null) {
  19838. session.name = " "; // "s= " must be there if no meaningful name set
  19839. }
  19840. session.media.forEach(function (mLine) {
  19841. if (mLine.payloads == null) {
  19842. mLine.payloads = "";
  19843. }
  19844. });
  19845. var outerOrder = opts.outerOrder || defaultOuterOrder;
  19846. var innerOrder = opts.innerOrder || defaultInnerOrder;
  19847. var sdp = [];
  19848. // loop through outerOrder for matching properties on session
  19849. outerOrder.forEach(function (type) {
  19850. grammar[type].forEach(function (obj) {
  19851. if (obj.name in session && session[obj.name] != null) {
  19852. sdp.push(makeLine(type, obj, session));
  19853. }
  19854. else if (obj.push in session && session[obj.push] != null) {
  19855. session[obj.push].forEach(function (el) {
  19856. sdp.push(makeLine(type, obj, el));
  19857. });
  19858. }
  19859. });
  19860. });
  19861. // then for each media line, follow the innerOrder
  19862. session.media.forEach(function (mLine) {
  19863. sdp.push(makeLine('m', grammar.m[0], mLine));
  19864. innerOrder.forEach(function (type) {
  19865. grammar[type].forEach(function (obj) {
  19866. if (obj.name in mLine && mLine[obj.name] != null) {
  19867. sdp.push(makeLine(type, obj, mLine));
  19868. }
  19869. else if (obj.push in mLine && mLine[obj.push] != null) {
  19870. mLine[obj.push].forEach(function (el) {
  19871. sdp.push(makeLine(type, obj, el));
  19872. });
  19873. }
  19874. });
  19875. });
  19876. });
  19877. return sdp.join('\r\n') + '\r\n';
  19878. };
  19879. },{"./grammar":70}],74:[function(require,module,exports){
  19880. var grammar = module.exports = {
  19881. v: [{
  19882. name: 'version',
  19883. reg: /^(\d*)$/
  19884. }],
  19885. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19886. // NB: sessionId will be a String in most cases because it is huge
  19887. name: 'origin',
  19888. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19889. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19890. format: "%s %s %d %s IP%d %s"
  19891. }],
  19892. // default parsing of these only (though some of these feel outdated)
  19893. s: [{ name: 'name' }],
  19894. i: [{ name: 'description' }],
  19895. u: [{ name: 'uri' }],
  19896. e: [{ name: 'email' }],
  19897. p: [{ name: 'phone' }],
  19898. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19899. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19900. //k: [{}], // outdated thing ignored
  19901. t: [{ //t=0 0
  19902. name: 'timing',
  19903. reg: /^(\d*) (\d*)/,
  19904. names: ['start', 'stop'],
  19905. format: "%d %d"
  19906. }],
  19907. c: [{ //c=IN IP4 10.47.197.26
  19908. name: 'connection',
  19909. reg: /^IN IP(\d) (\S*)/,
  19910. names: ['version', 'ip'],
  19911. format: "IN IP%d %s"
  19912. }],
  19913. b: [{ //b=AS:4000
  19914. push: 'bandwidth',
  19915. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19916. names: ['type', 'limit'],
  19917. format: "%s:%s"
  19918. }],
  19919. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19920. // NB: special - pushes to session
  19921. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19922. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19923. names: ['type', 'port', 'protocol', 'payloads'],
  19924. format: "%s %d %s %s"
  19925. }],
  19926. a: [
  19927. { //a=rtpmap:110 opus/48000/2
  19928. push: 'rtp',
  19929. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19930. names: ['payload', 'codec', 'rate', 'encoding'],
  19931. format: function (o) {
  19932. return (o.encoding) ?
  19933. "rtpmap:%d %s/%s/%s":
  19934. "rtpmap:%d %s/%s";
  19935. }
  19936. },
  19937. {
  19938. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19939. //a=fmtp:111 minptime=10; useinbandfec=1
  19940. push: 'fmtp',
  19941. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19942. names: ['payload', 'config'],
  19943. format: "fmtp:%d %s"
  19944. },
  19945. { //a=control:streamid=0
  19946. name: 'control',
  19947. reg: /^control:(.*)/,
  19948. format: "control:%s"
  19949. },
  19950. { //a=rtcp:65179 IN IP4 193.84.77.194
  19951. name: 'rtcp',
  19952. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19953. names: ['port', 'netType', 'ipVer', 'address'],
  19954. format: function (o) {
  19955. return (o.address != null) ?
  19956. "rtcp:%d %s IP%d %s":
  19957. "rtcp:%d";
  19958. }
  19959. },
  19960. { //a=rtcp-fb:98 trr-int 100
  19961. push: 'rtcpFbTrrInt',
  19962. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19963. names: ['payload', 'value'],
  19964. format: "rtcp-fb:%d trr-int %d"
  19965. },
  19966. { //a=rtcp-fb:98 nack rpsi
  19967. push: 'rtcpFb',
  19968. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19969. names: ['payload', 'type', 'subtype'],
  19970. format: function (o) {
  19971. return (o.subtype != null) ?
  19972. "rtcp-fb:%s %s %s":
  19973. "rtcp-fb:%s %s";
  19974. }
  19975. },
  19976. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19977. //a=extmap:1/recvonly URI-gps-string
  19978. push: 'ext',
  19979. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19980. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19981. format: function (o) {
  19982. return (o.config != null) ?
  19983. "extmap:%s %s %s":
  19984. "extmap:%s %s";
  19985. }
  19986. },
  19987. {
  19988. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19989. push: 'crypto',
  19990. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19991. names: ['id', 'suite', 'config', 'sessionConfig'],
  19992. format: function (o) {
  19993. return (o.sessionConfig != null) ?
  19994. "crypto:%d %s %s %s":
  19995. "crypto:%d %s %s";
  19996. }
  19997. },
  19998. { //a=setup:actpass
  19999. name: 'setup',
  20000. reg: /^setup:(\w*)/,
  20001. format: "setup:%s"
  20002. },
  20003. { //a=mid:1
  20004. name: 'mid',
  20005. reg: /^mid:([^\s]*)/,
  20006. format: "mid:%s"
  20007. },
  20008. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20009. name: 'msid',
  20010. reg: /^msid:(.*)/,
  20011. format: "msid:%s"
  20012. },
  20013. { //a=ptime:20
  20014. name: 'ptime',
  20015. reg: /^ptime:(\d*)/,
  20016. format: "ptime:%d"
  20017. },
  20018. { //a=maxptime:60
  20019. name: 'maxptime',
  20020. reg: /^maxptime:(\d*)/,
  20021. format: "maxptime:%d"
  20022. },
  20023. { //a=sendrecv
  20024. name: 'direction',
  20025. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20026. },
  20027. { //a=ice-lite
  20028. name: 'icelite',
  20029. reg: /^(ice-lite)/
  20030. },
  20031. { //a=ice-ufrag:F7gI
  20032. name: 'iceUfrag',
  20033. reg: /^ice-ufrag:(\S*)/,
  20034. format: "ice-ufrag:%s"
  20035. },
  20036. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20037. name: 'icePwd',
  20038. reg: /^ice-pwd:(\S*)/,
  20039. format: "ice-pwd:%s"
  20040. },
  20041. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20042. name: 'fingerprint',
  20043. reg: /^fingerprint:(\S*) (\S*)/,
  20044. names: ['type', 'hash'],
  20045. format: "fingerprint:%s %s"
  20046. },
  20047. {
  20048. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20049. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20050. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20051. push:'candidates',
  20052. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  20053. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  20054. format: function (o) {
  20055. var str = "candidate:%s %d %s %d %s %d typ %s";
  20056. // NB: candidate has two optional chunks, so %void middle one if it's missing
  20057. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20058. if (o.generation != null) {
  20059. str += " generation %d";
  20060. }
  20061. return str;
  20062. }
  20063. },
  20064. { //a=end-of-candidates (keep after the candidates line for readability)
  20065. name: 'endOfCandidates',
  20066. reg: /^(end-of-candidates)/
  20067. },
  20068. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20069. name: 'remoteCandidates',
  20070. reg: /^remote-candidates:(.*)/,
  20071. format: "remote-candidates:%s"
  20072. },
  20073. { //a=ice-options:google-ice
  20074. name: 'iceOptions',
  20075. reg: /^ice-options:(\S*)/,
  20076. format: "ice-options:%s"
  20077. },
  20078. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20079. push: "ssrcs",
  20080. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20081. names: ['id', 'attribute', 'value'],
  20082. format: "ssrc:%d %s:%s"
  20083. },
  20084. { //a=ssrc-group:FEC 1 2
  20085. push: "ssrcGroups",
  20086. reg: /^ssrc-group:(\w*) (.*)/,
  20087. names: ['semantics', 'ssrcs'],
  20088. format: "ssrc-group:%s %s"
  20089. },
  20090. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20091. name: "msidSemantic",
  20092. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20093. names: ['semantic', 'token'],
  20094. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20095. },
  20096. { //a=group:BUNDLE audio video
  20097. push: 'groups',
  20098. reg: /^group:(\w*) (.*)/,
  20099. names: ['type', 'mids'],
  20100. format: "group:%s %s"
  20101. },
  20102. { //a=rtcp-mux
  20103. name: 'rtcpMux',
  20104. reg: /^(rtcp-mux)/
  20105. },
  20106. { //a=rtcp-rsize
  20107. name: 'rtcpRsize',
  20108. reg: /^(rtcp-rsize)/
  20109. },
  20110. { // any a= that we don't understand is kepts verbatim on media.invalid
  20111. push: 'invalid',
  20112. names: ["value"]
  20113. }
  20114. ]
  20115. };
  20116. // set sensible defaults to avoid polluting the grammar with boring details
  20117. Object.keys(grammar).forEach(function (key) {
  20118. var objs = grammar[key];
  20119. objs.forEach(function (obj) {
  20120. if (!obj.reg) {
  20121. obj.reg = /(.*)/;
  20122. }
  20123. if (!obj.format) {
  20124. obj.format = "%s";
  20125. }
  20126. });
  20127. });
  20128. },{}],75:[function(require,module,exports){
  20129. arguments[4][71][0].apply(exports,arguments)
  20130. },{"./parser":76,"./writer":77,"dup":71}],76:[function(require,module,exports){
  20131. var toIntIfInt = function (v) {
  20132. return String(Number(v)) === v ? Number(v) : v;
  20133. };
  20134. var attachProperties = function (match, location, names, rawName) {
  20135. if (rawName && !names) {
  20136. location[rawName] = toIntIfInt(match[1]);
  20137. }
  20138. else {
  20139. for (var i = 0; i < names.length; i += 1) {
  20140. if (match[i+1] != null) {
  20141. location[names[i]] = toIntIfInt(match[i+1]);
  20142. }
  20143. }
  20144. }
  20145. };
  20146. var parseReg = function (obj, location, content) {
  20147. var needsBlank = obj.name && obj.names;
  20148. if (obj.push && !location[obj.push]) {
  20149. location[obj.push] = [];
  20150. }
  20151. else if (needsBlank && !location[obj.name]) {
  20152. location[obj.name] = {};
  20153. }
  20154. var keyLocation = obj.push ?
  20155. {} : // blank object that will be pushed
  20156. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20157. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20158. if (obj.push) {
  20159. location[obj.push].push(keyLocation);
  20160. }
  20161. };
  20162. var grammar = require('./grammar');
  20163. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20164. exports.parse = function (sdp) {
  20165. var session = {}
  20166. , media = []
  20167. , location = session; // points at where properties go under (one of the above)
  20168. // parse lines we understand
  20169. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20170. var type = l[0];
  20171. var content = l.slice(2);
  20172. if (type === 'm') {
  20173. media.push({rtp: [], fmtp: []});
  20174. location = media[media.length-1]; // point at latest media line
  20175. }
  20176. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20177. var obj = grammar[type][j];
  20178. if (obj.reg.test(content)) {
  20179. return parseReg(obj, location, content);
  20180. }
  20181. }
  20182. });
  20183. session.media = media; // link it up
  20184. return session;
  20185. };
  20186. var fmtpReducer = function (acc, expr) {
  20187. var s = expr.split('=');
  20188. if (s.length === 2) {
  20189. acc[s[0]] = toIntIfInt(s[1]);
  20190. }
  20191. return acc;
  20192. };
  20193. exports.parseFmtpConfig = function (str) {
  20194. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  20195. };
  20196. exports.parsePayloads = function (str) {
  20197. return str.split(' ').map(Number);
  20198. };
  20199. exports.parseRemoteCandidates = function (str) {
  20200. var candidates = [];
  20201. var parts = str.split(' ').map(toIntIfInt);
  20202. for (var i = 0; i < parts.length; i += 3) {
  20203. candidates.push({
  20204. component: parts[i],
  20205. ip: parts[i + 1],
  20206. port: parts[i + 2]
  20207. });
  20208. }
  20209. return candidates;
  20210. };
  20211. },{"./grammar":74}],77:[function(require,module,exports){
  20212. arguments[4][73][0].apply(exports,arguments)
  20213. },{"./grammar":74,"dup":73}],78:[function(require,module,exports){
  20214. var MediaStreamType = {
  20215. VIDEO_TYPE: "Video",
  20216. AUDIO_TYPE: "Audio"
  20217. };
  20218. module.exports = MediaStreamType;
  20219. },{}],79:[function(require,module,exports){
  20220. var RTCEvents = {
  20221. RTC_READY: "rtc.ready",
  20222. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20223. LASTN_CHANGED: "rtc.lastn_changed",
  20224. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20225. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20226. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20227. };
  20228. module.exports = RTCEvents;
  20229. },{}],80:[function(require,module,exports){
  20230. var Resolutions = {
  20231. "1080": {
  20232. width: 1920,
  20233. height: 1080,
  20234. order: 7
  20235. },
  20236. "fullhd": {
  20237. width: 1920,
  20238. height: 1080,
  20239. order: 7
  20240. },
  20241. "720": {
  20242. width: 1280,
  20243. height: 720,
  20244. order: 6
  20245. },
  20246. "hd": {
  20247. width: 1280,
  20248. height: 720,
  20249. order: 6
  20250. },
  20251. "960": {
  20252. width: 960,
  20253. height: 720,
  20254. order: 5
  20255. },
  20256. "640": {
  20257. width: 640,
  20258. height: 480,
  20259. order: 4
  20260. },
  20261. "vga": {
  20262. width: 640,
  20263. height: 480,
  20264. order: 4
  20265. },
  20266. "360": {
  20267. width: 640,
  20268. height: 360,
  20269. order: 3
  20270. },
  20271. "320": {
  20272. width: 320,
  20273. height: 240,
  20274. order: 2
  20275. },
  20276. "180": {
  20277. width: 320,
  20278. height: 180,
  20279. order: 1
  20280. }
  20281. };
  20282. module.exports = Resolutions;
  20283. },{}],81:[function(require,module,exports){
  20284. var AuthenticationEvents = {
  20285. /**
  20286. * Event callback arguments:
  20287. * function(authenticationEnabled, userIdentity)
  20288. * authenticationEnabled - indicates whether authentication has been enabled
  20289. * in this session
  20290. * userIdentity - if user has been logged in then it contains user name. If
  20291. * contains 'null' or 'undefined' then user is not logged in.
  20292. */
  20293. IDENTITY_UPDATED: "authentication.identity_updated"
  20294. };
  20295. module.exports = AuthenticationEvents;
  20296. },{}],82:[function(require,module,exports){
  20297. var DesktopSharingEventTypes = {
  20298. INIT: "ds.init",
  20299. SWITCHING_DONE: "ds.switching_done",
  20300. NEW_STREAM_CREATED: "ds.new_stream_created",
  20301. /**
  20302. * An event which indicates that the jidesha extension for Firefox is
  20303. * needed to proceed with screen sharing, and that it is not installed.
  20304. */
  20305. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20306. };
  20307. module.exports = DesktopSharingEventTypes;
  20308. },{}],83:[function(require,module,exports){
  20309. module.exports = {
  20310. /**
  20311. * An event carrying connection statistics.
  20312. */
  20313. CONNECTION_STATS: "statistics.connectionstats",
  20314. /**
  20315. * FIXME: needs documentation.
  20316. */
  20317. AUDIO_LEVEL: "statistics.audioLevel",
  20318. /**
  20319. * FIXME: needs documentation.
  20320. */
  20321. STOP: "statistics.stop"
  20322. };
  20323. },{}],84:[function(require,module,exports){
  20324. var Constants = {
  20325. LOCAL_JID: 'local'
  20326. };
  20327. module.exports = Constants;
  20328. },{}],85:[function(require,module,exports){
  20329. var XMPPEvents = {
  20330. // Designates an event indicating that the connection to the XMPP server
  20331. // failed.
  20332. CONNECTION_FAILED: "xmpp.connection.failed",
  20333. // Designates an event indicating that the media (ICE) connection was
  20334. // interrupted. This should go to the RTC module.
  20335. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20336. // Designates an event indicating that the media (ICE) connection was
  20337. // restored. This should go to the RTC module.
  20338. CONNECTION_RESTORED: "xmpp.connection.restored",
  20339. // Designates an event indicating that an offer (e.g. Jingle
  20340. // session-initiate) was received.
  20341. CALL_INCOMING: "xmpp.callincoming.jingle",
  20342. // Designates an event indicating that we were kicked from the XMPP MUC.
  20343. KICKED: "xmpp.kicked",
  20344. // Designates an event indicating that the userID for a specific JID has
  20345. // changed.
  20346. // Note: currently this event fires every time we receive presence from
  20347. // someone (regardless of whether or not the "userID" changed).
  20348. USER_ID_CHANGED: "xmpp.user_id_changed",
  20349. // Designates an event indicating that we have joined the XMPP MUC.
  20350. MUC_JOINED: "xmpp.muc_joined",
  20351. // Designates an event indicating that a participant joined the XMPP MUC.
  20352. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20353. // Designates an event indicating that a participant left the XMPP MUC.
  20354. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20355. // Designates an event indicating that the MUC role of a participant has
  20356. // changed.
  20357. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20358. // Designates an event indicating that the XMPP MUC was destroyed.
  20359. MUC_DESTROYED: "xmpp.muc_destroyed",
  20360. // Designates an event indicating that the display name of a participant
  20361. // has changed.
  20362. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20363. // Designates an event indicating that we received statistics from a
  20364. // participant in the MUC.
  20365. REMOTE_STATS: "xmpp.remote_stats",
  20366. // Designates an event indicating that our role in the XMPP MUC has changed.
  20367. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20368. // Designates an event indicating that the subject of the XMPP MUC has
  20369. // changed.
  20370. SUBJECT_CHANGED: "xmpp.subject_changed",
  20371. // Designates an event indicating that an XMPP message in the MUC was
  20372. // received.
  20373. MESSAGE_RECEIVED: "xmpp.message_received",
  20374. // Designates an event indicating that we sent an XMPP message to the MUC.
  20375. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20376. // Designates an event indicating that the video type (e.g. 'camera' or
  20377. // 'screen') for a participant has changed.
  20378. // Note: currently this event fires every time we receive presence from
  20379. // someone (regardless of whether or not the "video type" changed).
  20380. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20381. // Designates an event indicating that a participant in the XMPP MUC has
  20382. // advertised that they have audio muted (or unmuted).
  20383. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20384. // Designates an event indicating that a participant in the XMPP MUC has
  20385. // advertised that they have video muted (or unmuted).
  20386. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20387. // Designates an event indicating that the focus has asked us to mute our
  20388. // audio.
  20389. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20390. // Designates an event indicating that a moderator in the room changed the
  20391. // "start muted" settings for the conference.
  20392. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20393. // Designates an event indicating that we should join the conference with
  20394. // audio and/or video muted.
  20395. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20396. // Designates an event indicating that a remote participant's available
  20397. // devices (whether he supports a audio and/or video) changed.
  20398. // Note: currently this event fires every time we receive presence from
  20399. // someone (regardless of whether or not the devices changed).
  20400. DEVICE_AVAILABLE: "xmpp.device_available",
  20401. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20402. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20403. PASSWORD_REQUIRED: "xmpp.password_required",
  20404. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20405. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20406. ETHERPAD: "xmpp.etherpad",
  20407. BRIDGE_DOWN: "xmpp.bridge_down",
  20408. PRESENCE_STATUS: "xmpp.presence_status",
  20409. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20410. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20411. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20412. // TODO: only used in a hack, should probably be removed.
  20413. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20414. // TODO: only used in a hack, should probably be removed.
  20415. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20416. // TODO: only used in a hack, should probably be removed.
  20417. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20418. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20419. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20420. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20421. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20422. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20423. // xmpp is connected and obtained user media
  20424. READY_TO_JOIN: 'xmpp.ready_to_join',
  20425. FOCUS_LEFT: "xmpp.focus_left",
  20426. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  20427. };
  20428. module.exports = XMPPEvents;
  20429. },{}]},{},[7])(7)
  20430. });