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 747KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911
  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 StreamEventTypes = require("./service/RTC/StreamEventTypes");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiParticipant = require("./JitsiParticipant");
  13. var Statistics = require("./modules/statistics/statistics");
  14. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  15. /**
  16. * Creates a JitsiConference object with the given name and properties.
  17. * Note: this constructor is not a part of the public API (objects should be
  18. * created using JitsiConnection.createConference).
  19. * @param options.config properties / settings related to the conference that will be created.
  20. * @param options.name the name of the conference
  21. * @param options.connection the JitsiConnection object for this JitsiConference.
  22. * @constructor
  23. */
  24. function JitsiConference(options) {
  25. if(!options.name || options.name.toLowerCase() !== options.name) {
  26. logger.error("Invalid conference name (no conference name passed or it"
  27. + "contains invalid characters like capital letters)!");
  28. return;
  29. }
  30. this.options = options;
  31. this.connection = this.options.connection;
  32. this.xmpp = this.connection.xmpp;
  33. this.eventEmitter = new EventEmitter();
  34. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  35. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  36. this.rtc = new RTC(this.room, options);
  37. if(!options.config.disableAudioLevels)
  38. this.statistics = new Statistics();
  39. setupListeners(this);
  40. this.participants = {};
  41. this.lastActiveSpeaker = null;
  42. this.dtmfManager = null;
  43. this.somebodySupportsDTMF = false;
  44. }
  45. /**
  46. * Joins the conference.
  47. * @param password {string} the password
  48. */
  49. JitsiConference.prototype.join = function (password) {
  50. if(this.room)
  51. this.room.join(password, this.connection.tokenPassword);
  52. };
  53. /**
  54. * Leaves the conference.
  55. */
  56. JitsiConference.prototype.leave = function () {
  57. if(this.xmpp)
  58. this.xmpp.leaveRoom(this.room.roomjid);
  59. this.room = null;
  60. };
  61. /**
  62. * Returns the local tracks.
  63. */
  64. JitsiConference.prototype.getLocalTracks = function () {
  65. if (this.rtc) {
  66. return this.rtc.localStreams;
  67. } else {
  68. return [];
  69. }
  70. };
  71. /**
  72. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  73. * in JitsiConferenceEvents.
  74. * @param eventId the event ID.
  75. * @param handler handler for the event.
  76. *
  77. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  78. */
  79. JitsiConference.prototype.on = function (eventId, handler) {
  80. if(this.eventEmitter)
  81. this.eventEmitter.on(eventId, handler);
  82. };
  83. /**
  84. * Removes event listener
  85. * @param eventId the event ID.
  86. * @param [handler] optional, the specific handler to unbind
  87. *
  88. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  89. */
  90. JitsiConference.prototype.off = function (eventId, handler) {
  91. if(this.eventEmitter)
  92. this.eventEmitter.removeListener(eventId, handler);
  93. };
  94. // Common aliases for event emitter
  95. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  96. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  97. /**
  98. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  99. * @param command {String} the name of the command
  100. * @param handler {Function} handler for the command
  101. */
  102. JitsiConference.prototype.addCommandListener = function (command, handler) {
  103. if(this.room)
  104. this.room.addPresenceListener(command, handler);
  105. };
  106. /**
  107. * Removes command listener
  108. * @param command {String} the name of the command
  109. */
  110. JitsiConference.prototype.removeCommandListener = function (command) {
  111. if(this.room)
  112. this.room.removePresenceListener(command);
  113. };
  114. /**
  115. * Sends text message to the other participants in the conference
  116. * @param message the text message.
  117. */
  118. JitsiConference.prototype.sendTextMessage = function (message) {
  119. if(this.room)
  120. this.room.sendMessage(message);
  121. };
  122. /**
  123. * Send presence command.
  124. * @param name the name of the command.
  125. * @param values Object with keys and values that will be send.
  126. **/
  127. JitsiConference.prototype.sendCommand = function (name, values) {
  128. if(this.room) {
  129. this.room.addToPresence(name, values);
  130. this.room.sendPresence();
  131. }
  132. };
  133. /**
  134. * Send presence command one time.
  135. * @param name the name of the command.
  136. * @param values Object with keys and values that will be send.
  137. **/
  138. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  139. this.sendCommand(name, values);
  140. this.removeCommand(name);
  141. };
  142. /**
  143. * Send presence command.
  144. * @param name the name of the command.
  145. * @param values Object with keys and values that will be send.
  146. * @param persistent if false the command will be sent only one time
  147. **/
  148. JitsiConference.prototype.removeCommand = function (name) {
  149. if(this.room)
  150. this.room.removeFromPresence(name);
  151. };
  152. /**
  153. * Sets the display name for this conference.
  154. * @param name the display name to set
  155. */
  156. JitsiConference.prototype.setDisplayName = function(name) {
  157. if(this.room){
  158. this.room.addToPresence("nick", {
  159. attributes: {
  160. xmlns: 'http://jabber.org/protocol/nick'
  161. }, value: name
  162. });
  163. this.room.sendPresence();
  164. }
  165. };
  166. /**
  167. * Adds JitsiLocalTrack object to the conference.
  168. * @param track the JitsiLocalTrack object.
  169. */
  170. JitsiConference.prototype.addTrack = function (track) {
  171. this.rtc.addLocalStream(track);
  172. this.room.addStream(track.getOriginalStream(), function () {});
  173. };
  174. /**
  175. * Removes JitsiLocalTrack object to the conference.
  176. * @param track the JitsiLocalTrack object.
  177. */
  178. JitsiConference.prototype.removeTrack = function (track) {
  179. this.room.removeStream(track.getOriginalStream());
  180. this.rtc.removeLocalStream(track);
  181. };
  182. /**
  183. * Elects the participant with the given id to be the selected participant or the speaker.
  184. * @param id the identifier of the participant
  185. */
  186. JitsiConference.prototype.selectParticipant = function(participantId) {
  187. if (this.rtc) {
  188. this.rtc.selectedEndpoint(participantId);
  189. }
  190. };
  191. /**
  192. *
  193. * @param id the identifier of the participant
  194. */
  195. JitsiConference.prototype.pinParticipant = function(participantId) {
  196. if (this.rtc) {
  197. this.rtc.pinEndpoint(participantId);
  198. }
  199. };
  200. /**
  201. * Returns the list of participants for this conference.
  202. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  203. */
  204. JitsiConference.prototype.getParticipants = function() {
  205. return Object.keys(this.participants).map(function (key) {
  206. return this.participants[key];
  207. }, this);
  208. };
  209. /**
  210. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  211. * undefined if there isn't one).
  212. * @param id the id of the participant.
  213. */
  214. JitsiConference.prototype.getParticipantById = function(id) {
  215. return this.participants[id];
  216. };
  217. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  218. var id = Strophe.getResourceFromJid(jid);
  219. var participant = new JitsiParticipant(id, this, nick);
  220. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id);
  221. this.participants[id] = participant;
  222. this.connection.xmpp.connection.disco.info(
  223. jid, "" /* node */, function(iq) {
  224. participant._supportsDTMF = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  225. this.updateDTMFSupport();
  226. }.bind(this)
  227. );
  228. };
  229. JitsiConference.prototype.onMemberLeft = function (jid) {
  230. var id = Strophe.getResourceFromJid(jid);
  231. delete this.participants[id];
  232. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id);
  233. };
  234. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  235. var id = Strophe.getResourceFromJid(jid);
  236. var participant = this.getParticipantById(id);
  237. if (!participant) {
  238. return;
  239. }
  240. participant._displayName = displayName;
  241. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  242. };
  243. JitsiConference.prototype.onTrackAdded = function (track) {
  244. var id = track.getParticipantId();
  245. var participant = this.getParticipantById(id);
  246. participant._tracks.push(track);
  247. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  248. };
  249. JitsiConference.prototype.onTrackRemoved = function (track) {
  250. var id = track.getParticipantId();
  251. var participant = this.getParticipantById(id);
  252. var pos = participant._tracks.indexOf(track);
  253. if (pos > -1) {
  254. participant._tracks.splice(pos, 1);
  255. }
  256. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  257. };
  258. JitsiConference.prototype.updateDTMFSupport = function () {
  259. var somebodySupportsDTMF = false;
  260. var participants = this.getParticipants();
  261. // check if at least 1 participant supports DTMF
  262. for (var i = 0; i < participants.length; i += 1) {
  263. if (participants[i].supportsDTMF()) {
  264. somebodySupportsDTMF = true;
  265. break;
  266. }
  267. }
  268. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  269. this.somebodySupportsDTMF = somebodySupportsDTMF;
  270. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  271. }
  272. };
  273. /**
  274. * Allows to check if there is at least one user in the conference
  275. * that supports DTMF.
  276. * @returns {boolean} true if somebody supports DTMF, false otherwise
  277. */
  278. JitsiConference.prototype.isDTMFSupported = function () {
  279. return this.somebodySupportsDTMF;
  280. };
  281. /**
  282. * Returns the local user's ID
  283. * @return {string} local user's ID
  284. */
  285. JitsiConference.prototype.myUserId = function () {
  286. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  287. };
  288. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  289. if (!this.dtmfManager) {
  290. var connection = this.connection.xmpp.connection.jingle.activecall.peerconnection;
  291. if (!connection) {
  292. logger.warn("cannot sendTones: no conneciton");
  293. return;
  294. }
  295. var tracks = this.getLocalTracks().filter(function (track) {
  296. return track.isAudioTrack();
  297. });
  298. if (!tracks.length) {
  299. logger.warn("cannot sendTones: no local audio stream");
  300. return;
  301. }
  302. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  303. }
  304. this.dtmfManager.sendTones(tones, duration, pause);
  305. };
  306. /**
  307. * Setups the listeners needed for the conference.
  308. * @param conference the conference
  309. */
  310. function setupListeners(conference) {
  311. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  312. conference.rtc.onIncommingCall(event);
  313. if(conference.statistics)
  314. conference.statistics.startRemoteStats(event.peerconnection);
  315. });
  316. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  317. conference.rtc.createRemoteStream.bind(conference.rtc));
  318. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  319. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  320. });
  321. // FIXME
  322. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  323. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  324. // });
  325. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  326. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  327. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  328. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  329. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  330. });
  331. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  332. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  333. });
  334. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  335. conference.eventEmitter.emit(JitsiConferenceEvents.SETUP_FAILED);
  336. });
  337. conference.rtc.addListener(
  338. StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, conference.onTrackAdded.bind(conference)
  339. );
  340. //FIXME: Maybe remove event should not be associated with the conference.
  341. conference.rtc.addListener(
  342. StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, conference.onTrackRemoved.bind(conference)
  343. );
  344. //FIXME: Maybe remove event should not be associated with the conference.
  345. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, function (stream) {
  346. conference.removeTrack(stream);
  347. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  348. });
  349. conference.rtc.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  350. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  351. });
  352. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  353. if(conference.lastActiveSpeaker !== id && conference.room) {
  354. conference.lastActiveSpeaker = id;
  355. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  356. }
  357. });
  358. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  359. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  360. });
  361. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  362. function (lastNEndpoints, endpointsEnteringLastN) {
  363. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  364. lastNEndpoints, endpointsEnteringLastN);
  365. });
  366. if(conference.statistics) {
  367. //FIXME: Maybe remove event should not be associated with the conference.
  368. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  369. var userId = null;
  370. if (ssrc === Statistics.LOCAL_JID) {
  371. userId = conference.myUserId();
  372. } else {
  373. var jid = conference.room.getJidBySSRC(ssrc);
  374. if (!jid)
  375. return;
  376. userId = Strophe.getResourceFromJid(jid);
  377. }
  378. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  379. userId, level);
  380. });
  381. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_CREATED, function (stream) {
  382. conference.statistics.startLocalStats(stream);
  383. });
  384. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  385. function () {
  386. conference.statistics.dispose();
  387. });
  388. // FIXME: Maybe we should move this.
  389. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  390. // conference.room.updateDeviceAvailability(devices);
  391. // });
  392. }
  393. }
  394. module.exports = JitsiConference;
  395. }).call(this,"/JitsiConference.js")
  396. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":79,"./service/RTC/StreamEventTypes":81,"./service/xmpp/XMPPEvents":86,"events":43,"jitsi-meet-logger":47}],2:[function(require,module,exports){
  397. /**
  398. * Enumeration with the errors for the conference.
  399. * @type {{string: string}}
  400. */
  401. var JitsiConferenceErrors = {
  402. /**
  403. * Indicates that a password is required in order to join the conference.
  404. */
  405. PASSWORD_REQUIRED: "conference.passwordRequired",
  406. /**
  407. * Indicates that a connection error occurred when trying to join a
  408. * conference.
  409. */
  410. CONNECTION_ERROR: "conference.connectionError",
  411. /**
  412. * Indicates that there is no available videobridge.
  413. */
  414. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  415. /**
  416. * Many more errors TBD here.
  417. */
  418. };
  419. module.exports = JitsiConferenceErrors;
  420. },{}],3:[function(require,module,exports){
  421. /**
  422. * Enumeration with the events for the conference.
  423. * @type {{string: string}}
  424. */
  425. var JitsiConferenceEvents = {
  426. /**
  427. * A new media track was added to the conference.
  428. */
  429. TRACK_ADDED: "conference.trackAdded",
  430. /**
  431. * The media track was removed from the conference.
  432. */
  433. TRACK_REMOVED: "conference.trackRemoved",
  434. /**
  435. * The active speaker was changed.
  436. */
  437. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  438. /**
  439. * A new user joinned the conference.
  440. */
  441. USER_JOINED: "conference.userJoined",
  442. /**
  443. * A user has left the conference.
  444. */
  445. USER_LEFT: "conference.userLeft",
  446. /**
  447. * New text message was received.
  448. */
  449. MESSAGE_RECEIVED: "conference.messageReceived",
  450. /**
  451. * A user has changed it display name
  452. */
  453. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  454. /**
  455. * A participant avatar has changed.
  456. */
  457. AVATAR_CHANGED: "conference.avatarChanged",
  458. /**
  459. * New connection statistics are received.
  460. */
  461. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  462. /**
  463. * The Last N set is changed.
  464. */
  465. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  466. /**
  467. * You are included / excluded in somebody's last N set
  468. */
  469. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  470. /**
  471. * A media track ( attached to the conference) mute status was changed.
  472. */
  473. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  474. /**
  475. * Audio levels of a media track ( attached to the conference) was changed.
  476. */
  477. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  478. /**
  479. * Indicates that the connection to the conference has been interrupted
  480. * for some reason.
  481. */
  482. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  483. /**
  484. * Indicates that the connection to the conference has been restored.
  485. */
  486. CONNECTION_RESTORED: "conference.connectionRestored",
  487. /**
  488. * Indicates that the conference setup failed.
  489. */
  490. SETUP_FAILED: "conference.setup_failed",
  491. /**
  492. * Indicates that conference has been joined.
  493. */
  494. CONFERENCE_JOINED: "conference.joined",
  495. /**
  496. * Indicates that conference has been left.
  497. */
  498. CONFERENCE_LEFT: "conference.left",
  499. /**
  500. * Indicates that DTMF support changed.
  501. */
  502. DTMF_SUPPORT_CHANGED: "conference.dtmf_support_changed"
  503. };
  504. module.exports = JitsiConferenceEvents;
  505. },{}],4:[function(require,module,exports){
  506. var JitsiConference = require("./JitsiConference");
  507. var XMPP = require("./modules/xmpp/xmpp");
  508. var RandomUtil = require("./modules/util/RandomUtil");
  509. /**
  510. * Utility method that generates user name based on random hex values.
  511. * Eg. 12345678-1234-1234-12345678
  512. * @returns {string}
  513. */
  514. function generateUserName() {
  515. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  516. "-" + RandomUtil.randomHexString(4) + "-" +
  517. RandomUtil.randomHexDigit(8);
  518. }
  519. /**
  520. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  521. * JitsiConference interface.
  522. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  523. * @param tokenPassword secret generated by the provider of Jitsi Meet video conferencing services.
  524. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  525. * The format is:
  526. * passwordToken = token + "_" + roomName + "_" + ts
  527. * See doc/tokens.md for more info on how tokens are generated.
  528. * @param options Object with properties / settings related to connection with the server.
  529. * @constructor
  530. */
  531. function JitsiConnection(appID, tokenPassword, options) {
  532. this.appID = appID;
  533. this.tokenPassword = tokenPassword;
  534. this.options = options;
  535. this.xmpp = new XMPP(options);
  536. this.conferences = {};
  537. }
  538. /**
  539. * Connect the client with the server.
  540. * @param options {object} connecting options (for example authentications parameters).
  541. */
  542. JitsiConnection.prototype.connect = function (options) {
  543. if(!options)
  544. options = {};
  545. // If we have token provided use it as a password and generate random username
  546. if (this.tokenPassword) {
  547. options.password = this.tokenPassword;
  548. if (!options.id) {
  549. options.id = generateUserName() + "@" + this.options.hosts.domain;
  550. }
  551. }
  552. this.xmpp.connect(options.id, options.password);
  553. }
  554. /**
  555. * Disconnect the client from the server.
  556. */
  557. JitsiConnection.prototype.disconnect = function () {
  558. this.xmpp.disconnect();
  559. }
  560. /**
  561. * This method allows renewal of the tokens if they are expiring.
  562. * @param token the new token.
  563. */
  564. JitsiConnection.prototype.setToken = function (token) {
  565. this.token = token;
  566. }
  567. /**
  568. * Creates and joins new conference.
  569. * @param name the name of the conference; if null - a generated name will be provided from the api
  570. * @param options Object with properties / settings related to the conference that will be created.
  571. * @returns {JitsiConference} returns the new conference object.
  572. */
  573. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  574. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  575. return this.conferences[name];
  576. }
  577. /**
  578. * Subscribes the passed listener to the event.
  579. * @param event {JitsiConnectionEvents} the connection event.
  580. * @param listener {Function} the function that will receive the event
  581. */
  582. JitsiConnection.prototype.addEventListener = function (event, listener) {
  583. this.xmpp.addListener(event, listener);
  584. }
  585. /**
  586. * Unsubscribes the passed handler.
  587. * @param event {JitsiConnectionEvents} the connection event.
  588. * @param listener {Function} the function that will receive the event
  589. */
  590. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  591. this.xmpp.removeListener(event, listener);
  592. }
  593. module.exports = JitsiConnection;
  594. },{"./JitsiConference":1,"./modules/util/RandomUtil":25,"./modules/xmpp/xmpp":41}],5:[function(require,module,exports){
  595. /**
  596. * Enumeration with the errors for the connection.
  597. * @type {{string: string}}
  598. */
  599. var JitsiConnectionErrors = {
  600. /**
  601. * Indicates that a password is required in order to join the conference.
  602. */
  603. PASSWORD_REQUIRED: "connection.passwordRequired",
  604. /**
  605. * Indicates that a connection error occurred when trying to join a
  606. * conference.
  607. */
  608. CONNECTION_ERROR: "connection.connectionError",
  609. /**
  610. * Not specified errors.
  611. */
  612. OTHER_ERROR: "connection.otherError"
  613. };
  614. module.exports = JitsiConnectionErrors;
  615. },{}],6:[function(require,module,exports){
  616. /**
  617. * Enumeration with the events for the connection.
  618. * @type {{string: string}}
  619. */
  620. var JitsiConnnectionEvents = {
  621. /**
  622. * Indicates that the connection has been failed for some reason.
  623. */
  624. CONNECTION_FAILED: "connection.connectionFailed",
  625. /**
  626. * Indicates that the connection has been established.
  627. */
  628. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  629. /**
  630. * Indicates that the connection has been disconnected.
  631. */
  632. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  633. /**
  634. * Indicates that the perfomed action cannot be executed because the
  635. * connection is not in the correct state(connected, disconnected, etc.)
  636. */
  637. WRONG_STATE: "connection.wrongState"
  638. };
  639. module.exports = JitsiConnnectionEvents;
  640. },{}],7:[function(require,module,exports){
  641. var JitsiConnection = require("./JitsiConnection");
  642. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  643. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  644. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  645. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  646. var JitsiTrackEvents = require("./JitsiTrackEvents");
  647. var JitsiTrackErrors = require("./JitsiTrackErrors");
  648. var Logger = require("jitsi-meet-logger");
  649. var RTC = require("./modules/RTC/RTC");
  650. /**
  651. * Namespace for the interface of Jitsi Meet Library.
  652. */
  653. var LibJitsiMeet = {
  654. JitsiConnection: JitsiConnection,
  655. events: {
  656. conference: JitsiConferenceEvents,
  657. connection: JitsiConnectionEvents,
  658. track: JitsiTrackEvents
  659. },
  660. errors: {
  661. conference: JitsiConferenceErrors,
  662. connection: JitsiConnectionErrors,
  663. track: JitsiTrackErrors
  664. },
  665. logLevels: Logger.levels,
  666. init: function (options) {
  667. return RTC.init(options || {});
  668. },
  669. setLogLevel: function (level) {
  670. Logger.setLogLevel(level);
  671. },
  672. /**
  673. * Creates the media tracks and returns them trough the callback.
  674. * @param options Object with properties / settings specifying the tracks which should be created.
  675. * should be created or some additional configurations about resolution for example.
  676. * @param {Array} options.devices the devices that will be requested
  677. * @param {string} options.resolution resolution constraints
  678. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  679. * type: "audio" or "video", videoType: "camera" or "desktop"}
  680. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  681. * @param {string} options.cameraDeviceId
  682. * @param {string} options.micDeviceId
  683. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  684. * or a JitsiConferenceError if rejected.
  685. */
  686. createLocalTracks: function (options) {
  687. return RTC.obtainAudioAndVideoPermissions(options || {});
  688. },
  689. isDeviceListAvailable: function () {
  690. return RTC.isDeviceListAvailable();
  691. },
  692. enumerateDevices: function (callback) {
  693. RTC.enumerateDevices(callback);
  694. }
  695. };
  696. require("es6-promise").polyfill()
  697. //Setups the promise object.
  698. window.Promise = window.Promise || require("es6-promise").Promise;
  699. module.exports = LibJitsiMeet;
  700. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"es6-promise":45,"jitsi-meet-logger":47}],8:[function(require,module,exports){
  701. /**
  702. * Represents a participant in (a member of) a conference.
  703. */
  704. function JitsiParticipant(id, conference, displayName){
  705. this._id = id;
  706. this._conference = conference;
  707. this._displayName = displayName;
  708. this._supportsDTMF = false;
  709. this._tracks = [];
  710. this._isModerator = false;
  711. }
  712. /**
  713. * @returns {JitsiConference} The conference that this participant belongs to.
  714. */
  715. JitsiParticipant.prototype.getConference = function() {
  716. return this._conference;
  717. };
  718. /**
  719. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  720. */
  721. JitsiParticipant.prototype.getTracks = function() {
  722. return this._tracks;
  723. };
  724. /**
  725. * @returns {String} The ID (i.e. JID) of this participant.
  726. */
  727. JitsiParticipant.prototype.getId = function() {
  728. return this._id;
  729. };
  730. /**
  731. * @returns {String} The human-readable display name of this participant.
  732. */
  733. JitsiParticipant.prototype.getDisplayName = function() {
  734. return this._displayName;
  735. };
  736. /**
  737. * @returns {Boolean} Whether this participant is a moderator or not.
  738. */
  739. JitsiParticipant.prototype.isModerator = function() {
  740. return this._isModerator;
  741. };
  742. // Gets a link to an etherpad instance advertised by the participant?
  743. //JitsiParticipant.prototype.getEtherpad = function() {
  744. //
  745. //}
  746. /*
  747. * @returns {Boolean} Whether this participant has muted their audio.
  748. */
  749. JitsiParticipant.prototype.isAudioMuted = function() {
  750. return this.getTracks().reduce(function (track, isAudioMuted) {
  751. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  752. }, true);
  753. };
  754. /*
  755. * @returns {Boolean} Whether this participant has muted their video.
  756. */
  757. JitsiParticipant.prototype.isVideoMuted = function() {
  758. return this.getTracks().reduce(function (track, isVideoMuted) {
  759. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  760. }, true);
  761. };
  762. /*
  763. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  764. * TODO: do we expose this or handle it internally?
  765. */
  766. JitsiParticipant.prototype.getLatestStats = function() {
  767. };
  768. /**
  769. * @returns {String} The role of this participant.
  770. */
  771. JitsiParticipant.prototype.getRole = function() {
  772. };
  773. /*
  774. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  775. */
  776. JitsiParticipant.prototype.isFocus = function() {
  777. };
  778. /*
  779. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  780. */
  781. JitsiParticipant.prototype.isRecorder = function() {
  782. };
  783. /*
  784. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  785. */
  786. JitsiParticipant.prototype.isSipGateway = function() {
  787. };
  788. /**
  789. * @returns {Boolean} Whether this participant is currently sharing their screen.
  790. */
  791. JitsiParticipant.prototype.isScreenSharing = function() {
  792. };
  793. /**
  794. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  795. */
  796. JitsiParticipant.prototype.getUserAgent = function() {
  797. };
  798. /**
  799. * Kicks the participant from the conference (requires certain privileges).
  800. */
  801. JitsiParticipant.prototype.kick = function() {
  802. };
  803. /**
  804. * Asks this participant to mute themselves.
  805. */
  806. JitsiParticipant.prototype.askToMute = function() {
  807. };
  808. JitsiParticipant.prototype.supportsDTMF = function () {
  809. return this._supportsDTMF;
  810. };
  811. module.exports = JitsiParticipant;
  812. },{}],9:[function(require,module,exports){
  813. module.exports = {
  814. /**
  815. * Returns JitsiTrackErrors based on the error object passed by GUM
  816. * @param error the error
  817. * @param {Object} options the options object given to GUM.
  818. */
  819. parseError: function (error, options) {
  820. options = options || {};
  821. if (typeof error == "object" && error.constraintName && error.name
  822. && (error.name == "ConstraintNotSatisfiedError" ||
  823. error.name == "OverconstrainedError") &&
  824. (error.constraintName == "minWidth" ||
  825. error.constraintName == "maxWidth" ||
  826. error.constraintName == "minHeight" ||
  827. error.constraintName == "maxHeight") &&
  828. options.devices.indexOf("video") !== -1) {
  829. return this.UNSUPPORTED_RESOLUTION;
  830. } else {
  831. return this.GENERAL;
  832. }
  833. },
  834. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  835. GENERAL: "gum.general"
  836. };
  837. },{}],10:[function(require,module,exports){
  838. var JitsiTrackEvents = {
  839. /**
  840. * A media track mute status was changed.
  841. */
  842. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  843. /**
  844. * Audio levels of a this track was changed.
  845. */
  846. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  847. /**
  848. * The media track was removed to the conference.
  849. */
  850. TRACK_STOPPED: "track.TRACK_STOPPED",
  851. };
  852. module.exports = JitsiTrackEvents;
  853. },{}],11:[function(require,module,exports){
  854. (function (__filename){
  855. var logger = require("jitsi-meet-logger").getLogger(__filename);
  856. function JitsiDTMFManager (localAudio, peerConnection) {
  857. var tracks = localAudio._getTracks();
  858. if (!tracks.length) {
  859. throw new Error("Failed to initialize DTMFSender: no audio track.");
  860. }
  861. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  862. logger.debug("Initialized DTMFSender");
  863. }
  864. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  865. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  866. };
  867. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  868. },{"jitsi-meet-logger":47}],12:[function(require,module,exports){
  869. (function (__filename){
  870. /* global config, APP, Strophe */
  871. // cache datachannels to avoid garbage collection
  872. // https://code.google.com/p/chromium/issues/detail?id=405545
  873. var logger = require("jitsi-meet-logger").getLogger(__filename);
  874. var RTCEvents = require("../../service/RTC/RTCEvents");
  875. /**
  876. * Binds "ondatachannel" event listener to given PeerConnection instance.
  877. * @param peerConnection WebRTC peer connection instance.
  878. */
  879. function DataChannels(peerConnection, emitter) {
  880. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  881. this.eventEmitter = emitter;
  882. this._dataChannels = [];
  883. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  884. // Although it's not a requirement to open separate channels from both bridge
  885. // and peer as single channel can be used for sending and receiving data.
  886. // So either channel opened by the bridge or the one opened here is enough
  887. // for communication with the bridge.
  888. /*var dataChannelOptions =
  889. {
  890. reliable: true
  891. };
  892. var dataChannel
  893. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  894. // Can be used only when is in open state
  895. dataChannel.onopen = function ()
  896. {
  897. dataChannel.send("My channel !!!");
  898. };
  899. dataChannel.onmessage = function (event)
  900. {
  901. var msgData = event.data;
  902. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  903. };*/
  904. };
  905. /**
  906. * Callback triggered by PeerConnection when new data channel is opened
  907. * on the bridge.
  908. * @param event the event info object.
  909. */
  910. DataChannels.prototype.onDataChannel = function (event) {
  911. var dataChannel = event.channel;
  912. var self = this;
  913. dataChannel.onopen = function () {
  914. logger.info("Data channel opened by the Videobridge!", dataChannel);
  915. // Code sample for sending string and/or binary data
  916. // Sends String message to the bridge
  917. //dataChannel.send("Hello bridge!");
  918. // Sends 12 bytes binary message to the bridge
  919. //dataChannel.send(new ArrayBuffer(12));
  920. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  921. };
  922. dataChannel.onerror = function (error) {
  923. logger.error("Data Channel Error:", error, dataChannel);
  924. };
  925. dataChannel.onmessage = function (event) {
  926. var data = event.data;
  927. // JSON
  928. var obj;
  929. try {
  930. obj = JSON.parse(data);
  931. }
  932. catch (e) {
  933. logger.error(
  934. "Failed to parse data channel message as JSON: ",
  935. data,
  936. dataChannel);
  937. }
  938. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  939. var colibriClass = obj.colibriClass;
  940. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  941. // Endpoint ID from the Videobridge.
  942. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  943. logger.info(
  944. "Data channel new dominant speaker event: ",
  945. dominantSpeakerEndpoint);
  946. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  947. }
  948. else if ("InLastNChangeEvent" === colibriClass) {
  949. var oldValue = obj.oldValue;
  950. var newValue = obj.newValue;
  951. // Make sure that oldValue and newValue are of type boolean.
  952. var type;
  953. if ((type = typeof oldValue) !== 'boolean') {
  954. if (type === 'string') {
  955. oldValue = (oldValue == "true");
  956. } else {
  957. oldValue = new Boolean(oldValue).valueOf();
  958. }
  959. }
  960. if ((type = typeof newValue) !== 'boolean') {
  961. if (type === 'string') {
  962. newValue = (newValue == "true");
  963. } else {
  964. newValue = new Boolean(newValue).valueOf();
  965. }
  966. }
  967. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  968. }
  969. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  970. // The new/latest list of last-n endpoint IDs.
  971. var lastNEndpoints = obj.lastNEndpoints;
  972. // The list of endpoint IDs which are entering the list of
  973. // last-n at this time i.e. were not in the old list of last-n
  974. // endpoint IDs.
  975. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  976. logger.info(
  977. "Data channel new last-n event: ",
  978. lastNEndpoints, endpointsEnteringLastN, obj);
  979. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  980. lastNEndpoints, endpointsEnteringLastN, obj);
  981. }
  982. else {
  983. logger.debug("Data channel JSON-formatted message: ", obj);
  984. // The received message appears to be appropriately formatted
  985. // (i.e. is a JSON object which assigns a value to the mandatory
  986. // property colibriClass) so don't just swallow it, expose it to
  987. // public consumption.
  988. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  989. }
  990. }
  991. };
  992. dataChannel.onclose = function () {
  993. logger.info("The Data Channel closed", dataChannel);
  994. var idx = self._dataChannels.indexOf(dataChannel);
  995. if (idx > -1)
  996. self._dataChannels = self._dataChannels.splice(idx, 1);
  997. };
  998. this._dataChannels.push(dataChannel);
  999. };
  1000. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1001. this._onXXXEndpointChanged("selected", userResource);
  1002. }
  1003. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1004. this._onXXXEndpointChanged("pinnned", userResource);
  1005. }
  1006. /**
  1007. * Notifies Videobridge about a change in the value of a specific
  1008. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1009. *
  1010. * @param xxx the name of the endpoint-related property whose value changed
  1011. * @param userResource the new value of the endpoint-related property after the
  1012. * change
  1013. */
  1014. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1015. // Derive the correct words from xxx such as selected and Selected, pinned
  1016. // and Pinned.
  1017. var head = xxx.charAt(0);
  1018. var tail = xxx.substring(1);
  1019. var lower = head.toLowerCase() + tail;
  1020. var upper = head.toUpperCase() + tail;
  1021. // Notify Videobridge about the specified endpoint change.
  1022. console.log(lower + ' endpoint changed: ', userResource);
  1023. this._some(function (dataChannel) {
  1024. if (dataChannel.readyState == 'open') {
  1025. console.log(
  1026. 'sending ' + lower
  1027. + ' endpoint changed notification to the bridge: ',
  1028. userResource);
  1029. var jsonObject = {};
  1030. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1031. jsonObject[lower + "Endpoint"]
  1032. = (userResource ? userResource : null);
  1033. dataChannel.send(JSON.stringify(jsonObject));
  1034. return true;
  1035. }
  1036. });
  1037. }
  1038. DataChannels.prototype._some = function (callback, thisArg) {
  1039. var dataChannels = this._dataChannels;
  1040. if (dataChannels && dataChannels.length !== 0) {
  1041. if (thisArg)
  1042. return dataChannels.some(callback, thisArg);
  1043. else
  1044. return dataChannels.some(callback);
  1045. } else {
  1046. return false;
  1047. }
  1048. }
  1049. module.exports = DataChannels;
  1050. }).call(this,"/modules/RTC/DataChannels.js")
  1051. },{"../../service/RTC/RTCEvents":79,"jitsi-meet-logger":47}],13:[function(require,module,exports){
  1052. var JitsiTrack = require("./JitsiTrack");
  1053. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1054. var RTCBrowserType = require("./RTCBrowserType");
  1055. var RTC = require("./RTCUtils");
  1056. /**
  1057. * Represents a single media track (either audio or video).
  1058. * @constructor
  1059. */
  1060. function JitsiLocalTrack(stream, videoType,
  1061. resolution)
  1062. {
  1063. this.videoType = videoType;
  1064. this.dontFireRemoveEvent = false;
  1065. this.resolution = resolution;
  1066. var self = this;
  1067. JitsiTrack.call(this, null, stream,
  1068. function () {
  1069. if(!self.dontFireRemoveEvent && self.rtc)
  1070. self.rtc.eventEmitter.emit(
  1071. StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, self);
  1072. self.dontFireRemoveEvent = false;
  1073. });
  1074. }
  1075. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1076. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1077. /**
  1078. * Mutes / unmutes the track.
  1079. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1080. */
  1081. JitsiLocalTrack.prototype._setMute = function (mute) {
  1082. if(!this.rtc) {
  1083. console.error("Mute is not supported for streams not attached to conference!");
  1084. return;
  1085. }
  1086. var isAudio = this.type === JitsiTrack.AUDIO;
  1087. this.dontFireRemoveEvent = false;
  1088. if ((window.location.protocol != "https:") ||
  1089. (isAudio) || this.videoType === "screen" ||
  1090. // FIXME FF does not support 'removeStream' method used to mute
  1091. RTCBrowserType.isFirefox()) {
  1092. var tracks = this._getTracks();
  1093. for (var idx = 0; idx < tracks.length; idx++) {
  1094. tracks[idx].enabled = !mute;
  1095. }
  1096. if(isAudio)
  1097. this.rtc.room.setAudioMute(mute);
  1098. else
  1099. this.rtc.room.setVideoMute(mute);
  1100. this.rtc.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  1101. } else {
  1102. if (mute) {
  1103. this.dontFireRemoveEvent = true;
  1104. this.rtc.room.removeStream(this.stream);
  1105. RTC.stopMediaStream(this.stream);
  1106. if(isAudio)
  1107. this.rtc.room.setAudioMute(mute);
  1108. else
  1109. this.rtc.room.setVideoMute(mute);
  1110. this.stream = null;
  1111. this.rtc.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  1112. //FIXME: Maybe here we should set the SRC for the containers to something
  1113. } else {
  1114. var self = this;
  1115. RTC.obtainAudioAndVideoPermissions({
  1116. devices: (isAudio ? ["audio"] : ["video"]),
  1117. resolution: self.resolution})
  1118. .then(function (streams) {
  1119. var stream = null;
  1120. for(var i = 0; i < streams.length; i++) {
  1121. stream = streams[i];
  1122. if(stream.type === self.type) {
  1123. self.stream = stream.stream;
  1124. self.videoType = stream.videoType;
  1125. break;
  1126. }
  1127. }
  1128. if(!stream)
  1129. return;
  1130. for(var i = 0; i < self.containers.length; i++)
  1131. {
  1132. RTC.attachMediaStream(self.containers[i], self.stream);
  1133. }
  1134. self.rtc.room.addStream(stream.stream,
  1135. function () {
  1136. if(isAudio)
  1137. self.rtc.room.setAudioMute(mute);
  1138. else
  1139. self.rtc.room.setVideoMute(mute);
  1140. self.rtc.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, self);
  1141. });
  1142. });
  1143. }
  1144. }
  1145. }
  1146. /**
  1147. * Stops sending the media track. And removes it from the HTML.
  1148. * NOTE: Works for local tracks only.
  1149. */
  1150. JitsiLocalTrack.prototype.stop = function () {
  1151. if(!this.stream)
  1152. return;
  1153. if(this.rtc)
  1154. this.rtc.room.removeStream(this.stream);
  1155. this.rtc.stopMediaStream(this.stream);
  1156. this.detach();
  1157. }
  1158. /**
  1159. * Returns <tt>true</tt> - if the stream is muted
  1160. * and <tt>false</tt> otherwise.
  1161. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1162. * and <tt>false</tt> otherwise.
  1163. */
  1164. JitsiLocalTrack.prototype.isMuted = function () {
  1165. if (!this.stream)
  1166. return true;
  1167. var tracks = [];
  1168. var isAudio = this.type === JitsiTrack.AUDIO;
  1169. if (isAudio) {
  1170. tracks = this.stream.getAudioTracks();
  1171. } else {
  1172. if (!this.isActive())
  1173. return true;
  1174. tracks = this.stream.getVideoTracks();
  1175. }
  1176. for (var idx = 0; idx < tracks.length; idx++) {
  1177. if(tracks[idx].enabled)
  1178. return false;
  1179. }
  1180. return true;
  1181. };
  1182. /**
  1183. * Private method. Updates rtc property of the track.
  1184. * @param rtc the rtc instance.
  1185. */
  1186. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1187. this.rtc = rtc;
  1188. };
  1189. module.exports = JitsiLocalTrack;
  1190. },{"../../service/RTC/StreamEventTypes":81,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1191. var JitsiTrack = require("./JitsiTrack");
  1192. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1193. /**
  1194. * Represents a single media track (either audio or video).
  1195. * @param RTC the rtc instance.
  1196. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1197. * @param sid sid for the Media Stream
  1198. * @param ssrc ssrc for the Media Stream
  1199. * @param eventEmitter the event emitter
  1200. * @constructor
  1201. */
  1202. function JitsiRemoteTrack(RTC, data, sid, ssrc, eventEmitter) {
  1203. JitsiTrack.call(this, RTC, data.stream,
  1204. function () {
  1205. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, self);
  1206. });
  1207. this.rtc = RTC;
  1208. this.sid = sid;
  1209. this.stream = data.stream;
  1210. this.peerjid = data.peerjid;
  1211. this.videoType = data.videoType;
  1212. this.ssrc = ssrc;
  1213. this.muted = false;
  1214. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1215. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1216. this.muted = true
  1217. }
  1218. this.eventEmitter = eventEmitter;
  1219. var self = this;
  1220. }
  1221. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1222. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1223. /**
  1224. * Sets current muted status and fires an events for the change.
  1225. * @param value the muted status.
  1226. */
  1227. JitsiRemoteTrack.prototype.setMute = function (value) {
  1228. this.stream.muted = value;
  1229. this.muted = value;
  1230. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  1231. };
  1232. /**
  1233. * Returns the current muted status of the track.
  1234. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1235. */
  1236. JitsiRemoteTrack.prototype.isMuted = function () {
  1237. return this.muted;
  1238. }
  1239. /**
  1240. * Returns the participant id which owns the track.
  1241. * @returns {string} the id of the participants.
  1242. */
  1243. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1244. return Strophe.getResourceFromJid(this.peerjid);
  1245. };
  1246. delete JitsiRemoteTrack.prototype.stop;
  1247. delete JitsiRemoteTrack.prototype.start;
  1248. module.exports = JitsiRemoteTrack;
  1249. },{"../../service/RTC/StreamEventTypes":81,"./JitsiTrack":15}],15:[function(require,module,exports){
  1250. var RTCBrowserType = require("./RTCBrowserType");
  1251. /**
  1252. * This implements 'onended' callback normally fired by WebRTC after the stream
  1253. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1254. * @param jitsiTrack our track object holding the original WebRTC stream object
  1255. * to which 'onended' handling will be added.
  1256. */
  1257. function implementOnEndedHandling(jitsiTrack) {
  1258. var stream = jitsiTrack.getOriginalStream();
  1259. var originalStop = stream.stop;
  1260. stream.stop = function () {
  1261. originalStop.apply(stream);
  1262. if (jitsiTrack.isActive()) {
  1263. stream.onended();
  1264. }
  1265. };
  1266. }
  1267. /**
  1268. * Adds onended/oninactive handler to a MediaStream.
  1269. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1270. * @param handler the handler
  1271. */
  1272. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1273. if(RTCBrowserType.isTemasysPluginUsed()) {
  1274. // themasys
  1275. mediaStream.attachEvent('ended', function () {
  1276. handler(mediaStream);
  1277. });
  1278. }
  1279. else {
  1280. if(typeof mediaStream.active !== "undefined")
  1281. mediaStream.oninactive = handler;
  1282. else
  1283. mediaStream.onended = handler;
  1284. }
  1285. }
  1286. /**
  1287. * Represents a single media track (either audio or video).
  1288. * @constructor
  1289. * @param rtc the rtc instance
  1290. * @param stream the stream
  1291. * @param streamInactiveHandler the function that will handle
  1292. * onended/oninactive events of the stream.
  1293. */
  1294. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1295. {
  1296. /**
  1297. * Array with the HTML elements that are displaying the streams.
  1298. * @type {Array}
  1299. */
  1300. this.containers = [];
  1301. this.rtc = rtc;
  1302. this.stream = stream;
  1303. this.type = (this.stream.getVideoTracks().length > 0)?
  1304. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1305. if(this.type == "audio") {
  1306. this._getTracks = function () {
  1307. return this.stream.getAudioTracks();
  1308. }.bind(this);
  1309. } else {
  1310. this._getTracks = function () {
  1311. return this.stream.getVideoTracks();
  1312. }.bind(this);
  1313. }
  1314. if (RTCBrowserType.isFirefox() && this.stream) {
  1315. implementOnEndedHandling(this);
  1316. }
  1317. if(stream)
  1318. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1319. }
  1320. /**
  1321. * JitsiTrack video type.
  1322. * @type {string}
  1323. */
  1324. JitsiTrack.VIDEO = "video";
  1325. /**
  1326. * JitsiTrack audio type.
  1327. * @type {string}
  1328. */
  1329. JitsiTrack.AUDIO = "audio";
  1330. /**
  1331. * Returns the type (audio or video) of this track.
  1332. */
  1333. JitsiTrack.prototype.getType = function() {
  1334. return this.type;
  1335. };
  1336. /**
  1337. * Check if this is audiotrack.
  1338. */
  1339. JitsiTrack.prototype.isAudioTrack = function () {
  1340. return this.getType() === JitsiTrack.AUDIO;
  1341. };
  1342. /**
  1343. * Check if this is videotrack.
  1344. */
  1345. JitsiTrack.prototype.isVideoTrack = function () {
  1346. return this.getType() === JitsiTrack.VIDEO;
  1347. };
  1348. /**
  1349. * Returns the RTCMediaStream from the browser (?).
  1350. */
  1351. JitsiTrack.prototype.getOriginalStream = function() {
  1352. return this.stream;
  1353. }
  1354. /**
  1355. * Mutes the track.
  1356. */
  1357. JitsiTrack.prototype.mute = function () {
  1358. this._setMute(true);
  1359. }
  1360. /**
  1361. * Unmutes the stream.
  1362. */
  1363. JitsiTrack.prototype.unmute = function () {
  1364. this._setMute(false);
  1365. }
  1366. /**
  1367. * Attaches the MediaStream of this track to an HTML container (?).
  1368. * Adds the container to the list of containers that are displaying the track.
  1369. * @param container the HTML container
  1370. */
  1371. JitsiTrack.prototype.attach = function (container) {
  1372. if(this.stream)
  1373. require("./RTCUtils").attachMediaStream(container, this.stream);
  1374. this.containers.push(container);
  1375. }
  1376. /**
  1377. * Removes the track from the passed HTML container.
  1378. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1379. */
  1380. JitsiTrack.prototype.detach = function (container) {
  1381. for(var i = 0; i < this.containers.length; i++)
  1382. {
  1383. if(this.containers[i].is(container))
  1384. {
  1385. this.containers.splice(i,1);
  1386. }
  1387. if(!container)
  1388. {
  1389. this.containers[i].find(">video").remove();
  1390. }
  1391. }
  1392. if(container)
  1393. $(container).find(">video").remove();
  1394. }
  1395. /**
  1396. * Stops sending the media track. And removes it from the HTML.
  1397. * NOTE: Works for local tracks only.
  1398. */
  1399. JitsiTrack.prototype.stop = function () {
  1400. }
  1401. /**
  1402. * Returns true if this is a video track and the source of the video is a
  1403. * screen capture as opposed to a camera.
  1404. */
  1405. JitsiTrack.prototype.isScreenSharing = function(){
  1406. }
  1407. /**
  1408. * Returns id of the track.
  1409. * @returns {string} id of the track or null if this is fake track.
  1410. */
  1411. JitsiTrack.prototype.getId = function () {
  1412. var tracks = this.stream.getTracks();
  1413. if(!tracks || tracks.length === 0)
  1414. return null;
  1415. return tracks[0].id;
  1416. };
  1417. /**
  1418. * Checks whether the MediaStream is avtive/not ended.
  1419. * When there is no check for active we don't have information and so
  1420. * will return that stream is active (in case of FF).
  1421. * @returns {boolean} whether MediaStream is active.
  1422. */
  1423. JitsiTrack.prototype.isActive = function () {
  1424. if((typeof this.stream.active !== "undefined"))
  1425. return this.stream.active;
  1426. else
  1427. return true;
  1428. };
  1429. module.exports = JitsiTrack;
  1430. },{"./RTCBrowserType":17,"./RTCUtils":18}],16:[function(require,module,exports){
  1431. /* global APP */
  1432. var EventEmitter = require("events");
  1433. var RTCBrowserType = require("./RTCBrowserType");
  1434. var RTCUtils = require("./RTCUtils.js");
  1435. var JitsiTrack = require("./JitsiTrack");
  1436. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1437. var DataChannels = require("./DataChannels");
  1438. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1439. var DesktopSharingEventTypes
  1440. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1441. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1442. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1443. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1444. function createLocalTracks(streams) {
  1445. var newStreams = []
  1446. for (var i = 0; i < streams.length; i++) {
  1447. var localStream = new JitsiLocalTrack(streams[i].stream,
  1448. streams[i].videoType, streams[i].resolution);
  1449. newStreams.push(localStream);
  1450. if (streams[i].isMuted === true)
  1451. localStream.setMute(true);
  1452. //FIXME:
  1453. // var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1454. //
  1455. // eventEmitter.emit(eventType, localStream);
  1456. }
  1457. return newStreams;
  1458. }
  1459. function RTC(room, options) {
  1460. this.room = room;
  1461. this.localStreams = [];
  1462. this.remoteStreams = {};
  1463. this.localAudio = null;
  1464. this.localVideo = null;
  1465. this.eventEmitter = new EventEmitter();
  1466. var self = this;
  1467. this.options = options || {};
  1468. room.addPresenceListener("videomuted", function (values, from) {
  1469. if(self.remoteStreams[from])
  1470. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1471. });
  1472. room.addPresenceListener("audiomuted", function (values, from) {
  1473. if(self.remoteStreams[from])
  1474. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1475. });
  1476. }
  1477. /**
  1478. * Creates the local MediaStreams.
  1479. * @param {Object} [options] optional parameters
  1480. * @param {Array} options.devices the devices that will be requested
  1481. * @param {string} options.resolution resolution constraints
  1482. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1483. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1484. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1485. * @param {string} options.cameraDeviceId
  1486. * @param {string} options.micDeviceId
  1487. * @returns {*} Promise object that will receive the new JitsiTracks
  1488. */
  1489. RTC.obtainAudioAndVideoPermissions = function (options) {
  1490. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  1491. }
  1492. RTC.prototype.onIncommingCall = function(event) {
  1493. if(this.options.config.openSctp)
  1494. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1495. for(var i = 0; i < this.localStreams.length; i++)
  1496. if(this.localStreams[i])
  1497. {
  1498. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1499. }
  1500. }
  1501. RTC.prototype.selectedEndpoint = function (id) {
  1502. if(this.dataChannels)
  1503. this.dataChannels.handleSelectedEndpointEvent(id);
  1504. }
  1505. RTC.prototype.pinEndpoint = function (id) {
  1506. if(this.dataChannels)
  1507. this.dataChannels.handlePinnedEndpointEvent(id);
  1508. }
  1509. RTC.prototype.addListener = function (type, listener) {
  1510. this.eventEmitter.on(type, listener);
  1511. };
  1512. RTC.prototype.removeListener = function (eventType, listener) {
  1513. this.eventEmitter.removeListener(eventType, listener);
  1514. };
  1515. RTC.addListener = function (eventType, listener) {
  1516. RTCUtils.addListener(eventType, listener);
  1517. }
  1518. RTC.removeListener = function (eventType, listener) {
  1519. RTCUtils.removeListener(eventType, listener)
  1520. }
  1521. RTC.isRTCReady = function () {
  1522. return RTCUtils.isRTCReady();
  1523. }
  1524. RTC.init = function (options) {
  1525. return RTCUtils.init(options || {});
  1526. }
  1527. RTC.getDeviceAvailability = function () {
  1528. return RTCUtils.getDeviceAvailability();
  1529. }
  1530. RTC.prototype.addLocalStream = function (stream) {
  1531. this.localStreams.push(stream);
  1532. stream._setRTC(this);
  1533. if (stream.type == "audio") {
  1534. this.localAudio = stream;
  1535. } else {
  1536. this.localVideo = stream;
  1537. }
  1538. };
  1539. RTC.prototype.removeLocalStream = function (stream) {
  1540. for(var i = 0; i < this.localStreams.length; i++) {
  1541. if(this.localStreams[i].getOriginalStream() === stream) {
  1542. delete this.localStreams[i];
  1543. return;
  1544. }
  1545. }
  1546. };
  1547. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1548. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  1549. this.eventEmitter);
  1550. if(!data.peerjid)
  1551. return;
  1552. var jid = data.peerjid;
  1553. if(!this.remoteStreams[jid]) {
  1554. this.remoteStreams[jid] = {};
  1555. }
  1556. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1557. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1558. return remoteStream;
  1559. };
  1560. RTC.getPCConstraints = function () {
  1561. return RTCUtils.pc_constraints;
  1562. };
  1563. RTC.attachMediaStream = function (elSelector, stream) {
  1564. RTCUtils.attachMediaStream(elSelector, stream);
  1565. };
  1566. RTC.getStreamID = function (stream) {
  1567. return RTCUtils.getStreamID(stream);
  1568. };
  1569. RTC.getVideoSrc = function (element) {
  1570. return RTCUtils.getVideoSrc(element);
  1571. };
  1572. RTC.isDeviceListAvailable = function () {
  1573. return RTCUtils.isDeviceListAvailable();
  1574. };
  1575. /**
  1576. * Allows to receive list of available cameras/microphones.
  1577. * @param {function} callback would receive array of devices as an argument
  1578. */
  1579. RTC.enumerateDevices = function (callback) {
  1580. RTCUtils.enumerateDevices(callback);
  1581. };
  1582. RTC.setVideoSrc = function (element, src) {
  1583. RTCUtils.setVideoSrc(element, src);
  1584. };
  1585. /**
  1586. * A method to handle stopping of the stream.
  1587. * One point to handle the differences in various implementations.
  1588. * @param mediaStream MediaStream object to stop.
  1589. */
  1590. RTC.stopMediaStream = function (mediaStream) {
  1591. RTCUtils.stopMediaStream(mediaStream);
  1592. };
  1593. RTC.prototype.getVideoElementName = function () {
  1594. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1595. };
  1596. RTC.prototype.dispose = function() {
  1597. };
  1598. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  1599. var stream;
  1600. if(this.remoteStreams[jid] &&
  1601. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1602. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1603. }
  1604. if(!stream)
  1605. return true;
  1606. if (value != stream.muted) {
  1607. stream.setMute(value);
  1608. return true;
  1609. }
  1610. return false;
  1611. };
  1612. RTC.prototype.switchVideoStreams = function (newStream) {
  1613. this.localVideo.stream = newStream;
  1614. this.localStreams = [];
  1615. //in firefox we have only one stream object
  1616. if (this.localAudio.getOriginalStream() != newStream)
  1617. this.localStreams.push(this.localAudio);
  1618. this.localStreams.push(this.localVideo);
  1619. };
  1620. RTC.prototype.isVideoMuted = function (jid) {
  1621. if (jid === APP.xmpp.myJid()) {
  1622. var localVideo = APP.RTC.localVideo;
  1623. return (!localVideo || localVideo.isMuted());
  1624. } else {
  1625. if (!this.remoteStreams[jid] ||
  1626. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1627. return null;
  1628. }
  1629. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1630. }
  1631. };
  1632. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1633. if (!this.localVideo)
  1634. return;
  1635. if (mute == this.localVideo.isMuted())
  1636. {
  1637. APP.xmpp.sendVideoInfoPresence(mute);
  1638. if (callback)
  1639. callback(mute);
  1640. }
  1641. else
  1642. {
  1643. this.localVideo.setMute(mute);
  1644. this.room.setVideoMute(
  1645. mute,
  1646. callback,
  1647. options);
  1648. }
  1649. };
  1650. module.exports = RTC;
  1651. },{"../../service/RTC/MediaStreamTypes":78,"../../service/RTC/RTCEvents.js":79,"../../service/RTC/StreamEventTypes.js":81,"../../service/desktopsharing/DesktopSharingEventTypes":83,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":43}],17:[function(require,module,exports){
  1652. var currentBrowser;
  1653. var browserVersion;
  1654. var isAndroid;
  1655. var RTCBrowserType = {
  1656. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1657. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1658. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1659. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1660. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1661. getBrowserType: function () {
  1662. return currentBrowser;
  1663. },
  1664. isChrome: function () {
  1665. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1666. },
  1667. isOpera: function () {
  1668. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1669. },
  1670. isFirefox: function () {
  1671. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1672. },
  1673. isIExplorer: function () {
  1674. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1675. },
  1676. isSafari: function () {
  1677. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1678. },
  1679. isTemasysPluginUsed: function () {
  1680. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1681. },
  1682. getFirefoxVersion: function () {
  1683. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1684. },
  1685. getChromeVersion: function () {
  1686. return RTCBrowserType.isChrome() ? browserVersion : null;
  1687. },
  1688. usesPlanB: function() {
  1689. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1690. RTCBrowserType.isTemasysPluginUsed();
  1691. },
  1692. usesUnifiedPlan: function() {
  1693. return RTCBrowserType.isFirefox();
  1694. },
  1695. /**
  1696. * Whether the browser is running on an android device.
  1697. */
  1698. isAndroid: function() {
  1699. return isAndroid;
  1700. }
  1701. // Add version getters for other browsers when needed
  1702. };
  1703. // detectOpera() must be called before detectChrome() !!!
  1704. // otherwise Opera wil be detected as Chrome
  1705. function detectChrome() {
  1706. if (navigator.webkitGetUserMedia) {
  1707. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1708. var userAgent = navigator.userAgent.toLowerCase();
  1709. // We can assume that user agent is chrome, because it's
  1710. // enforced when 'ext' streaming method is set
  1711. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1712. console.log("This appears to be Chrome, ver: " + ver);
  1713. return ver;
  1714. }
  1715. return null;
  1716. }
  1717. function detectOpera() {
  1718. var userAgent = navigator.userAgent;
  1719. if (userAgent.match(/Opera|OPR/)) {
  1720. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1721. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1722. console.info("This appears to be Opera, ver: " + version);
  1723. return version;
  1724. }
  1725. return null;
  1726. }
  1727. function detectFirefox() {
  1728. if (navigator.mozGetUserMedia) {
  1729. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1730. var version = parseInt(
  1731. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1732. console.log('This appears to be Firefox, ver: ' + version);
  1733. return version;
  1734. }
  1735. return null;
  1736. }
  1737. function detectSafari() {
  1738. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1739. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1740. console.info("This appears to be Safari");
  1741. // FIXME detect Safari version when needed
  1742. return 1;
  1743. }
  1744. return null;
  1745. }
  1746. function detectIE() {
  1747. var version;
  1748. var ua = window.navigator.userAgent;
  1749. var msie = ua.indexOf('MSIE ');
  1750. if (msie > 0) {
  1751. // IE 10 or older => return version number
  1752. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1753. }
  1754. var trident = ua.indexOf('Trident/');
  1755. if (!version && trident > 0) {
  1756. // IE 11 => return version number
  1757. var rv = ua.indexOf('rv:');
  1758. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1759. }
  1760. var edge = ua.indexOf('Edge/');
  1761. if (!version && edge > 0) {
  1762. // IE 12 => return version number
  1763. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1764. }
  1765. if (version) {
  1766. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1767. console.info("This appears to be IExplorer, ver: " + version);
  1768. }
  1769. return version;
  1770. }
  1771. function detectBrowser() {
  1772. var version;
  1773. var detectors = [
  1774. detectOpera,
  1775. detectChrome,
  1776. detectFirefox,
  1777. detectIE,
  1778. detectSafari
  1779. ];
  1780. // Try all browser detectors
  1781. for (var i = 0; i < detectors.length; i++) {
  1782. version = detectors[i]();
  1783. if (version)
  1784. return version;
  1785. }
  1786. console.error("Failed to detect browser type");
  1787. return undefined;
  1788. }
  1789. browserVersion = detectBrowser();
  1790. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1791. module.exports = RTCBrowserType;
  1792. },{}],18:[function(require,module,exports){
  1793. (function (__filename){
  1794. /* global config, require, attachMediaStream, getUserMedia */
  1795. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1796. var RTCBrowserType = require("./RTCBrowserType");
  1797. var Resolutions = require("../../service/RTC/Resolutions");
  1798. var RTCEvents = require("../../service/RTC/RTCEvents");
  1799. var AdapterJS = require("./adapter.screenshare");
  1800. var SDPUtil = require("../xmpp/SDPUtil");
  1801. var EventEmitter = require("events");
  1802. var screenObtainer = require("./ScreenObtainer");
  1803. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  1804. var eventEmitter = new EventEmitter();
  1805. var devices = {
  1806. audio: true,
  1807. video: true
  1808. }
  1809. var rtcReady = false;
  1810. function setResolutionConstraints(constraints, resolution) {
  1811. var isAndroid = RTCBrowserType.isAndroid();
  1812. if (Resolutions[resolution]) {
  1813. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1814. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1815. }
  1816. else if (isAndroid) {
  1817. // FIXME can't remember if the purpose of this was to always request
  1818. // low resolution on Android ? if yes it should be moved up front
  1819. constraints.video.mandatory.minWidth = 320;
  1820. constraints.video.mandatory.minHeight = 240;
  1821. constraints.video.mandatory.maxFrameRate = 15;
  1822. }
  1823. if (constraints.video.mandatory.minWidth)
  1824. constraints.video.mandatory.maxWidth =
  1825. constraints.video.mandatory.minWidth;
  1826. if (constraints.video.mandatory.minHeight)
  1827. constraints.video.mandatory.maxHeight =
  1828. constraints.video.mandatory.minHeight;
  1829. }
  1830. /**
  1831. * @param {string[]} um required user media types
  1832. *
  1833. * @param {Object} [options={}] optional parameters
  1834. * @param {string} options.resolution
  1835. * @param {number} options.bandwidth
  1836. * @param {number} options.fps
  1837. * @param {string} options.desktopStream
  1838. * @param {string} options.cameraDeviceId
  1839. * @param {string} options.micDeviceId
  1840. * @param {bool} firefox_fake_device
  1841. */
  1842. function getConstraints(um, options) {
  1843. var constraints = {audio: false, video: false};
  1844. if (um.indexOf('video') >= 0) {
  1845. // same behaviour as true
  1846. constraints.video = { mandatory: {}, optional: [] };
  1847. if (options.cameraDeviceId) {
  1848. constraints.video.optional.push({
  1849. sourceId: options.cameraDeviceId
  1850. });
  1851. }
  1852. constraints.video.optional.push({ googLeakyBucket: true });
  1853. setResolutionConstraints(constraints, options.resolution);
  1854. }
  1855. if (um.indexOf('audio') >= 0) {
  1856. if (!RTCBrowserType.isFirefox()) {
  1857. // same behaviour as true
  1858. constraints.audio = { mandatory: {}, optional: []};
  1859. if (options.micDeviceId) {
  1860. constraints.audio.optional.push({
  1861. sourceId: options.micDeviceId
  1862. });
  1863. }
  1864. // if it is good enough for hangouts...
  1865. constraints.audio.optional.push(
  1866. {googEchoCancellation: true},
  1867. {googAutoGainControl: true},
  1868. {googNoiseSupression: true},
  1869. {googHighpassFilter: true},
  1870. {googNoisesuppression2: true},
  1871. {googEchoCancellation2: true},
  1872. {googAutoGainControl2: true}
  1873. );
  1874. } else {
  1875. if (options.micDeviceId) {
  1876. constraints.audio = {
  1877. mandatory: {},
  1878. optional: [{
  1879. sourceId: options.micDeviceId
  1880. }]};
  1881. } else {
  1882. constraints.audio = true;
  1883. }
  1884. }
  1885. }
  1886. if (um.indexOf('screen') >= 0) {
  1887. if (RTCBrowserType.isChrome()) {
  1888. constraints.video = {
  1889. mandatory: {
  1890. chromeMediaSource: "screen",
  1891. googLeakyBucket: true,
  1892. maxWidth: window.screen.width,
  1893. maxHeight: window.screen.height,
  1894. maxFrameRate: 3
  1895. },
  1896. optional: []
  1897. };
  1898. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1899. constraints.video = {
  1900. optional: [
  1901. {
  1902. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1903. }
  1904. ]
  1905. };
  1906. } else if (RTCBrowserType.isFirefox()) {
  1907. constraints.video = {
  1908. mozMediaSource: "window",
  1909. mediaSource: "window"
  1910. };
  1911. } else {
  1912. logger.error(
  1913. "'screen' WebRTC media source is supported only in Chrome" +
  1914. " and with Temasys plugin");
  1915. }
  1916. }
  1917. if (um.indexOf('desktop') >= 0) {
  1918. constraints.video = {
  1919. mandatory: {
  1920. chromeMediaSource: "desktop",
  1921. chromeMediaSourceId: options.desktopStream,
  1922. googLeakyBucket: true,
  1923. maxWidth: window.screen.width,
  1924. maxHeight: window.screen.height,
  1925. maxFrameRate: 3
  1926. },
  1927. optional: []
  1928. };
  1929. }
  1930. if (options.bandwidth) {
  1931. if (!constraints.video) {
  1932. //same behaviour as true
  1933. constraints.video = {mandatory: {}, optional: []};
  1934. }
  1935. constraints.video.optional.push({bandwidth: options.bandwidth});
  1936. }
  1937. if (options.fps) {
  1938. // for some cameras it might be necessary to request 30fps
  1939. // so they choose 30fps mjpg over 10fps yuy2
  1940. if (!constraints.video) {
  1941. // same behaviour as true;
  1942. constraints.video = {mandatory: {}, optional: []};
  1943. }
  1944. constraints.video.mandatory.minFrameRate = options.fps;
  1945. }
  1946. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  1947. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  1948. // this later can be a problem with some of the tests
  1949. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  1950. {
  1951. constraints.audio = true;
  1952. constraints.fake = true;
  1953. }
  1954. return constraints;
  1955. }
  1956. function setAvailableDevices(um, available) {
  1957. if (um.indexOf("video") != -1) {
  1958. devices.video = available;
  1959. }
  1960. if (um.indexOf("audio") != -1) {
  1961. devices.audio = available;
  1962. }
  1963. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  1964. }
  1965. // In case of IE we continue from 'onReady' callback
  1966. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1967. // once it is initialized.
  1968. function onReady (options, GUM) {
  1969. rtcReady = true;
  1970. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1971. screenObtainer.init(eventEmitter, options, GUM);
  1972. };
  1973. /**
  1974. * Apply function with arguments if function exists.
  1975. * Do nothing if function not provided.
  1976. * @param {function} [fn] function to apply
  1977. * @param {Array} [args=[]] arguments for function
  1978. */
  1979. function maybeApply(fn, args) {
  1980. if (fn) {
  1981. fn.apply(null, args || []);
  1982. }
  1983. }
  1984. var getUserMediaStatus = {
  1985. initialized: false,
  1986. callbacks: []
  1987. };
  1988. /**
  1989. * Wrap `getUserMedia` to allow others to know if it was executed at least
  1990. * once or not. Wrapper function uses `getUserMediaStatus` object.
  1991. * @param {Function} getUserMedia native function
  1992. * @returns {Function} wrapped function
  1993. */
  1994. function wrapGetUserMedia(getUserMedia) {
  1995. return function (constraints, successCallback, errorCallback) {
  1996. getUserMedia(constraints, function (stream) {
  1997. maybeApply(successCallback, [stream]);
  1998. if (!getUserMediaStatus.initialized) {
  1999. getUserMediaStatus.initialized = true;
  2000. getUserMediaStatus.callbacks.forEach(function (callback) {
  2001. callback();
  2002. });
  2003. getUserMediaStatus.callbacks.length = 0;
  2004. }
  2005. }, function (error) {
  2006. maybeApply(errorCallback, [error]);
  2007. });
  2008. };
  2009. }
  2010. /**
  2011. * Create stub device which equals to auto selected device.
  2012. * @param {string} kind if that should be `audio` or `video` device
  2013. * @returns {Object} stub device description in `enumerateDevices` format
  2014. */
  2015. function createAutoDeviceInfo(kind) {
  2016. return {
  2017. facing: null,
  2018. label: 'Auto',
  2019. kind: kind,
  2020. deviceId: '',
  2021. groupId: null
  2022. };
  2023. }
  2024. /**
  2025. * Execute function after getUserMedia was executed at least once.
  2026. * @param {Function} callback function to execute after getUserMedia
  2027. */
  2028. function afterUserMediaInitialized(callback) {
  2029. if (getUserMediaStatus.initialized) {
  2030. callback();
  2031. } else {
  2032. getUserMediaStatus.callbacks.push(callback);
  2033. }
  2034. }
  2035. /**
  2036. * Wrapper function which makes enumerateDevices to wait
  2037. * until someone executes getUserMedia first time.
  2038. * @param {Function} enumerateDevices native function
  2039. * @returns {Funtion} wrapped function
  2040. */
  2041. function wrapEnumerateDevices(enumerateDevices) {
  2042. return function (callback) {
  2043. // enumerate devices only after initial getUserMedia
  2044. afterUserMediaInitialized(function () {
  2045. enumerateDevices().then(function (devices) {
  2046. //add auto devices
  2047. devices.unshift(
  2048. createAutoDeviceInfo('audioinput'),
  2049. createAutoDeviceInfo('videoinput')
  2050. );
  2051. callback(devices);
  2052. }, function (err) {
  2053. console.error('cannot enumerate devices: ', err);
  2054. // return only auto devices
  2055. callback([createAutoDeviceInfo('audioInput'),
  2056. createAutoDeviceInfo('videoinput')]);
  2057. });
  2058. });
  2059. };
  2060. }
  2061. /**
  2062. * Use old MediaStreamTrack to get devices list and
  2063. * convert it to enumerateDevices format.
  2064. * @param {Function} callback function to call when received devices list.
  2065. */
  2066. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2067. MediaStreamTrack.getSources(function (sources) {
  2068. var devices = sources.map(function (source) {
  2069. var kind = (source.kind || '').toLowerCase();
  2070. return {
  2071. facing: source.facing || null,
  2072. label: source.label,
  2073. kind: kind ? kind + 'input': null,
  2074. deviceId: source.id,
  2075. groupId: source.groupId || null
  2076. };
  2077. });
  2078. //add auto devices
  2079. devices.unshift(
  2080. createAutoDeviceInfo('audioinput'),
  2081. createAutoDeviceInfo('videoinput')
  2082. );
  2083. callback(devices);
  2084. });
  2085. }
  2086. function obtainDevices(options) {
  2087. if(!options.devices || options.devices.length === 0) {
  2088. return options.successCallback(streams);
  2089. }
  2090. var device = options.devices.splice(0, 1);
  2091. options.deviceGUM[device](function (stream) {
  2092. options.streams[device] = stream;
  2093. obtainDevices(options);
  2094. },
  2095. function (error) {
  2096. logger.error(
  2097. "failed to obtain " + device + " stream - stop", error);
  2098. options.errorCallback(JitsiTrackErrors.parseError(error));
  2099. });
  2100. }
  2101. /**
  2102. * Handles the newly created Media Streams.
  2103. * @param streams the new Media Streams
  2104. * @param resolution the resolution of the video streams
  2105. * @returns {*[]} object that describes the new streams
  2106. */
  2107. function handleLocalStream(streams, resolution) {
  2108. var audioStream, videoStream, desktopStream, res = [];
  2109. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2110. // an object with two properties: audioStream, videoStream.
  2111. if (window.webkitMediaStream) {
  2112. var audioVideo = streams.audioVideo;
  2113. if (audioVideo) {
  2114. var audioTracks = audioVideo.getAudioTracks();
  2115. if(audioTracks.length) {
  2116. audioStream = new webkitMediaStream();
  2117. for (var i = 0; i < audioTracks.length; i++) {
  2118. audioStream.addTrack(audioTracks[i]);
  2119. }
  2120. }
  2121. var videoTracks = audioVideo.getVideoTracks();
  2122. if(videoTracks.length) {
  2123. videoStream = new webkitMediaStream();
  2124. for (i = 0; i < videoTracks.length; i++) {
  2125. videoStream.addTrack(videoTracks[i]);
  2126. }
  2127. }
  2128. }
  2129. }
  2130. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2131. if (streams && streams.audioStream)
  2132. audioStream = streams.audioStream;
  2133. if (streams && streams.videoStream)
  2134. videoStream = streams.videoStream;
  2135. }
  2136. if (streams && streams.desktopStream)
  2137. res.push({stream: streams.desktopStream,
  2138. type: "video", videoType: "desktop"});
  2139. if(audioStream)
  2140. res.push({stream: audioStream, type: "audio", videoType: null});
  2141. if(videoStream)
  2142. res.push({stream: videoStream, type: "video", videoType: "camera",
  2143. resolution: resolution});
  2144. return res;
  2145. }
  2146. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2147. var RTCUtils = {
  2148. init: function (options) {
  2149. return new Promise(function(resolve, reject) {
  2150. if (RTCBrowserType.isFirefox()) {
  2151. var FFversion = RTCBrowserType.getFirefoxVersion();
  2152. if (FFversion < 40) {
  2153. logger.error(
  2154. "Firefox version too old: " + FFversion +
  2155. ". Required >= 40.");
  2156. reject(new Error("Firefox version too old: " + FFversion +
  2157. ". Required >= 40."));
  2158. return;
  2159. }
  2160. this.peerconnection = mozRTCPeerConnection;
  2161. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2162. this.enumerateDevices = wrapEnumerateDevices(
  2163. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2164. );
  2165. this.pc_constraints = {};
  2166. this.attachMediaStream = function (element, stream) {
  2167. // srcObject is being standardized and FF will eventually
  2168. // support that unprefixed. FF also supports the
  2169. // "element.src = URL.createObjectURL(...)" combo, but that
  2170. // will be deprecated in favour of srcObject.
  2171. //
  2172. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2173. // https://github.com/webrtc/samples/issues/302
  2174. if (!element[0])
  2175. return;
  2176. element[0].mozSrcObject = stream;
  2177. element[0].play();
  2178. };
  2179. this.getStreamID = function (stream) {
  2180. var id = stream.id;
  2181. if (!id) {
  2182. var tracks = stream.getVideoTracks();
  2183. if (!tracks || tracks.length === 0) {
  2184. tracks = stream.getAudioTracks();
  2185. }
  2186. id = tracks[0].id;
  2187. }
  2188. return SDPUtil.filter_special_chars(id);
  2189. };
  2190. this.getVideoSrc = function (element) {
  2191. if (!element)
  2192. return null;
  2193. return element.mozSrcObject;
  2194. };
  2195. this.setVideoSrc = function (element, src) {
  2196. if (element)
  2197. element.mozSrcObject = src;
  2198. };
  2199. RTCSessionDescription = mozRTCSessionDescription;
  2200. RTCIceCandidate = mozRTCIceCandidate;
  2201. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2202. this.peerconnection = webkitRTCPeerConnection;
  2203. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2204. if (navigator.mediaDevices) {
  2205. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2206. this.enumerateDevices = wrapEnumerateDevices(
  2207. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2208. );
  2209. } else {
  2210. this.getUserMedia = getUserMedia;
  2211. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2212. }
  2213. this.attachMediaStream = function (element, stream) {
  2214. element.attr('src', webkitURL.createObjectURL(stream));
  2215. };
  2216. this.getStreamID = function (stream) {
  2217. // streams from FF endpoints have the characters '{' and '}'
  2218. // that make jQuery choke.
  2219. return SDPUtil.filter_special_chars(stream.id);
  2220. };
  2221. this.getVideoSrc = function (element) {
  2222. if (!element)
  2223. return null;
  2224. return element.getAttribute("src");
  2225. };
  2226. this.setVideoSrc = function (element, src) {
  2227. if (element)
  2228. element.setAttribute("src", src);
  2229. };
  2230. // DTLS should now be enabled by default but..
  2231. this.pc_constraints = {'optional': [
  2232. {'DtlsSrtpKeyAgreement': 'true'}
  2233. ]};
  2234. if (options.useIPv6) {
  2235. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2236. this.pc_constraints.optional.push({googIPv6: true});
  2237. }
  2238. if (RTCBrowserType.isAndroid()) {
  2239. this.pc_constraints = {}; // disable DTLS on Android
  2240. }
  2241. if (!webkitMediaStream.prototype.getVideoTracks) {
  2242. webkitMediaStream.prototype.getVideoTracks = function () {
  2243. return this.videoTracks;
  2244. };
  2245. }
  2246. if (!webkitMediaStream.prototype.getAudioTracks) {
  2247. webkitMediaStream.prototype.getAudioTracks = function () {
  2248. return this.audioTracks;
  2249. };
  2250. }
  2251. }
  2252. // Detect IE/Safari
  2253. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2254. //AdapterJS.WebRTCPlugin.setLogLevel(
  2255. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2256. AdapterJS.webRTCReady(function (isPlugin) {
  2257. self.peerconnection = RTCPeerConnection;
  2258. self.getUserMedia = window.getUserMedia;
  2259. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2260. self.attachMediaStream = function (elSel, stream) {
  2261. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2262. return;
  2263. }
  2264. attachMediaStream(elSel[0], stream);
  2265. };
  2266. self.getStreamID = function (stream) {
  2267. var id = SDPUtil.filter_special_chars(stream.label);
  2268. return id;
  2269. };
  2270. self.getVideoSrc = function (element) {
  2271. if (!element) {
  2272. logger.warn("Attempt to get video SRC of null element");
  2273. return null;
  2274. }
  2275. var children = element.children;
  2276. for (var i = 0; i !== children.length; ++i) {
  2277. if (children[i].name === 'streamId') {
  2278. return children[i].value;
  2279. }
  2280. }
  2281. //logger.info(element.id + " SRC: " + src);
  2282. return null;
  2283. };
  2284. self.setVideoSrc = function (element, src) {
  2285. //logger.info("Set video src: ", element, src);
  2286. if (!src) {
  2287. logger.warn("Not attaching video stream, 'src' is null");
  2288. return;
  2289. }
  2290. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2291. var stream = AdapterJS.WebRTCPlugin.plugin
  2292. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2293. attachMediaStream(element, stream);
  2294. };
  2295. onReady(options, self.getUserMediaWithConstraints);
  2296. resolve();
  2297. });
  2298. } else {
  2299. try {
  2300. logger.error('Browser does not appear to be WebRTC-capable');
  2301. } catch (e) {
  2302. }
  2303. reject('Browser does not appear to be WebRTC-capable');
  2304. return;
  2305. }
  2306. // Call onReady() if Temasys plugin is not used
  2307. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2308. onReady(options, self.getUserMediaWithConstraints);
  2309. resolve();
  2310. }
  2311. }.bind(this));
  2312. },
  2313. /**
  2314. * @param {string[]} um required user media types
  2315. * @param {function} success_callback
  2316. * @param {Function} failure_callback
  2317. * @param {Object} [options] optional parameters
  2318. * @param {string} options.resolution
  2319. * @param {number} options.bandwidth
  2320. * @param {number} options.fps
  2321. * @param {string} options.desktopStream
  2322. * @param {string} options.cameraDeviceId
  2323. * @param {string} options.micDeviceId
  2324. **/
  2325. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2326. options = options || {};
  2327. resolution = options.resolution;
  2328. var constraints = getConstraints(
  2329. um, options);
  2330. logger.info("Get media constraints", constraints);
  2331. try {
  2332. this.getUserMedia(constraints,
  2333. function (stream) {
  2334. logger.log('onUserMediaSuccess');
  2335. setAvailableDevices(um, true);
  2336. success_callback(stream);
  2337. },
  2338. function (error) {
  2339. setAvailableDevices(um, false);
  2340. logger.warn('Failed to get access to local media. Error ',
  2341. error, constraints);
  2342. if (failure_callback) {
  2343. failure_callback(error, resolution);
  2344. }
  2345. });
  2346. } catch (e) {
  2347. logger.error('GUM failed: ', e);
  2348. if (failure_callback) {
  2349. failure_callback(e);
  2350. }
  2351. }
  2352. },
  2353. /**
  2354. * Creates the local MediaStreams.
  2355. * @param {Object} [options] optional parameters
  2356. * @param {Array} options.devices the devices that will be requested
  2357. * @param {string} options.resolution resolution constraints
  2358. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2359. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2360. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2361. * @param {string} options.cameraDeviceId
  2362. * @param {string} options.micDeviceId
  2363. * @returns {*} Promise object that will receive the new JitsiTracks
  2364. */
  2365. obtainAudioAndVideoPermissions: function (options) {
  2366. var self = this;
  2367. options = options || {};
  2368. return new Promise(function (resolve, reject) {
  2369. var successCallback = function (stream) {
  2370. resolve(handleLocalStream(stream, options.resolution));
  2371. };
  2372. options.devices = options.devices || ['audio', 'video'];
  2373. if(!screenObtainer.isSupported()
  2374. && options.devices.indexOf("desktop") !== -1){
  2375. reject(new Error("Desktop sharing is not supported!"));
  2376. }
  2377. if (RTCBrowserType.isFirefox() ||
  2378. RTCBrowserType.isTemasysPluginUsed()) {
  2379. var GUM = function (device, s, e) {
  2380. this.getUserMediaWithConstraints(device, s, e, options);
  2381. }
  2382. var deviceGUM = {
  2383. "audio": GUM.bind(self, ["audio"]),
  2384. "video": GUM.bind(self, ["video"]),
  2385. "desktop": screenObtainer.obtainStream
  2386. }
  2387. // With FF/IE we can't split the stream into audio and video because FF
  2388. // doesn't support media stream constructors. So, we need to get the
  2389. // audio stream separately from the video stream using two distinct GUM
  2390. // calls. Not very user friendly :-( but we don't have many other
  2391. // options neither.
  2392. //
  2393. // Note that we pack those 2 streams in a single object and pass it to
  2394. // the successCallback method.
  2395. obtainDevices({
  2396. devices: options.devices,
  2397. successCallback: successCallback,
  2398. errorCallback: reject,
  2399. deviceGUM: deviceGUM
  2400. });
  2401. } else {
  2402. var hasDesktop = false;
  2403. if(hasDesktop = options.devices.indexOf("desktop") !== -1) {
  2404. options.devices.splice(options.devices.indexOf("desktop"), 1);
  2405. }
  2406. options.resolution = options.resolution || '360';
  2407. if(options.devices.length) {
  2408. this.getUserMediaWithConstraints(
  2409. options.devices,
  2410. function (stream) {
  2411. if(hasDesktop) {
  2412. screenObtainer.obtainStream(
  2413. function (desktopStream) {
  2414. successCallback({audioVideo: stream,
  2415. desktopStream: desktopStream});
  2416. }, function (error) {
  2417. reject(
  2418. JitsiTrackErrors.parseError(error));
  2419. });
  2420. } else {
  2421. successCallback({audioVideo: stream});
  2422. }
  2423. },
  2424. function (error) {
  2425. reject(JitsiTrackErrors.parseError(error));
  2426. },
  2427. options);
  2428. } else if (hasDesktop) {
  2429. screenObtainer.obtainStream(
  2430. function (stream) {
  2431. successCallback({desktopStream: stream});
  2432. }, function (error) {
  2433. reject(
  2434. JitsiTrackErrors.parseError(error));
  2435. });
  2436. }
  2437. }
  2438. }.bind(this));
  2439. },
  2440. addListener: function (eventType, listener) {
  2441. eventEmitter.on(eventType, listener);
  2442. },
  2443. removeListener: function (eventType, listener) {
  2444. eventEmitter.removeListener(eventType, listener);
  2445. },
  2446. getDeviceAvailability: function () {
  2447. return devices;
  2448. },
  2449. isRTCReady: function () {
  2450. return rtcReady;
  2451. },
  2452. /**
  2453. * Checks if its possible to enumerate available cameras/micropones.
  2454. * @returns {boolean} true if available, false otherwise.
  2455. */
  2456. isDeviceListAvailable: function () {
  2457. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2458. if (isEnumerateDevicesAvailable) {
  2459. return true;
  2460. }
  2461. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2462. },
  2463. /**
  2464. * A method to handle stopping of the stream.
  2465. * One point to handle the differences in various implementations.
  2466. * @param mediaStream MediaStream object to stop.
  2467. */
  2468. stopMediaStream: function (mediaStream) {
  2469. mediaStream.getTracks().forEach(function (track) {
  2470. // stop() not supported with IE
  2471. if (track.stop) {
  2472. track.stop();
  2473. }
  2474. });
  2475. // leave stop for implementation still using it
  2476. if (mediaStream.stop) {
  2477. mediaStream.stop();
  2478. }
  2479. }
  2480. };
  2481. module.exports = RTCUtils;
  2482. }).call(this,"/modules/RTC/RTCUtils.js")
  2483. },{"../../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){
  2484. (function (__filename){
  2485. /* global chrome, $, alert */
  2486. /* jshint -W003 */
  2487. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2488. var RTCBrowserType = require("./RTCBrowserType");
  2489. var AdapterJS = require("./adapter.screenshare");
  2490. var DesktopSharingEventTypes
  2491. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2492. /**
  2493. * Indicates whether the Chrome desktop sharing extension is installed.
  2494. * @type {boolean}
  2495. */
  2496. var chromeExtInstalled = false;
  2497. /**
  2498. * Indicates whether an update of the Chrome desktop sharing extension is
  2499. * required.
  2500. * @type {boolean}
  2501. */
  2502. var chromeExtUpdateRequired = false;
  2503. /**
  2504. * Whether the jidesha extension for firefox is installed for the domain on
  2505. * which we are running. Null designates an unknown value.
  2506. * @type {null}
  2507. */
  2508. var firefoxExtInstalled = null;
  2509. /**
  2510. * If set to true, detection of an installed firefox extension will be started
  2511. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  2512. * user tries to enable screen sharing).
  2513. */
  2514. var reDetectFirefoxExtension = false;
  2515. var GUM = null;
  2516. /**
  2517. * Handles obtaining a stream from a screen capture on different browsers.
  2518. */
  2519. var ScreenObtainer = {
  2520. /**
  2521. * The EventEmitter to use to emit events.
  2522. * @type {null}
  2523. */
  2524. eventEmitter: null,
  2525. obtainStream: null,
  2526. /**
  2527. * Initializes the function used to obtain a screen capture
  2528. * (this.obtainStream).
  2529. *
  2530. * If the browser is Chrome, it uses the value of
  2531. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  2532. * decide whether to use the a Chrome extension (if the value is 'ext'),
  2533. * use the "screen" media source (if the value is 'webrtc'),
  2534. * or disable screen capture (if the value is other).
  2535. * Note that for the "screen" media source to work the
  2536. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  2537. */
  2538. init: function(eventEmitter, options, gum) {
  2539. this.eventEmitter = eventEmitter;
  2540. var obtainDesktopStream = null;
  2541. this.options = options = options || {};
  2542. GUM = gum;
  2543. if (RTCBrowserType.isFirefox())
  2544. initFirefoxExtensionDetection(options);
  2545. // TODO remove this, options.desktopSharing is deprecated.
  2546. var chromeMethod =
  2547. (options.desktopSharingChromeMethod || options.desktopSharing);
  2548. if (RTCBrowserType.isTemasysPluginUsed()) {
  2549. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  2550. logger.info("Screensharing not supported by this plugin " +
  2551. "version");
  2552. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2553. logger.info(
  2554. "Screensharing not available with Temasys plugin on" +
  2555. " this site");
  2556. } else {
  2557. obtainDesktopStream = obtainWebRTCScreen;
  2558. logger.info("Using Temasys plugin for desktop sharing");
  2559. }
  2560. } else if (RTCBrowserType.isChrome()) {
  2561. if (chromeMethod == "ext") {
  2562. if (RTCBrowserType.getChromeVersion() >= 34) {
  2563. obtainDesktopStream =
  2564. this.obtainScreenFromExtension;
  2565. logger.info("Using Chrome extension for desktop sharing");
  2566. initChromeExtension(options);
  2567. } else {
  2568. logger.info("Chrome extension not supported until ver 34");
  2569. }
  2570. } else if (chromeMethod == "webrtc") {
  2571. obtainDesktopStream = obtainWebRTCScreen;
  2572. logger.info("Using Chrome WebRTC for desktop sharing");
  2573. }
  2574. } else if (RTCBrowserType.isFirefox()) {
  2575. if (options.desktopSharingFirefoxDisabled) {
  2576. obtainDesktopStream = null;
  2577. } else if (window.location.protocol === "http:"){
  2578. logger.log("Screen sharing is not supported over HTTP. " +
  2579. "Use of HTTPS is required.");
  2580. obtainDesktopStream = null;
  2581. } else {
  2582. obtainDesktopStream = this.obtainScreenOnFirefox;
  2583. }
  2584. }
  2585. if (!obtainDesktopStream) {
  2586. logger.info("Desktop sharing disabled");
  2587. }
  2588. this.obtainStream = obtainDesktopStream;
  2589. },
  2590. /**
  2591. * Checks whether obtaining a screen capture is supported in the current
  2592. * environment.
  2593. * @returns {boolean}
  2594. */
  2595. isSupported: function() {
  2596. return !!this.obtainStream;
  2597. },
  2598. /**
  2599. * Obtains a screen capture stream on Firefox.
  2600. * @param callback
  2601. * @param errorCallback
  2602. */
  2603. obtainScreenOnFirefox:
  2604. function (callback, errorCallback) {
  2605. var self = this;
  2606. var extensionRequired = false;
  2607. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  2608. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  2609. RTCBrowserType.getFirefoxVersion() <=
  2610. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  2611. extensionRequired = true;
  2612. logger.log("Jidesha extension required on firefox version " +
  2613. RTCBrowserType.getFirefoxVersion());
  2614. }
  2615. if (!extensionRequired || firefoxExtInstalled === true) {
  2616. obtainWebRTCScreen(callback, errorCallback);
  2617. return;
  2618. }
  2619. if (reDetectFirefoxExtension) {
  2620. reDetectFirefoxExtension = false;
  2621. initFirefoxExtensionDetection(this.options);
  2622. }
  2623. // Give it some (more) time to initialize, and assume lack of
  2624. // extension if it hasn't.
  2625. if (firefoxExtInstalled === null) {
  2626. window.setTimeout(
  2627. function() {
  2628. if (firefoxExtInstalled === null)
  2629. firefoxExtInstalled = false;
  2630. self.obtainScreenOnFirefox(callback, errorCallback);
  2631. },
  2632. 300
  2633. );
  2634. logger.log("Waiting for detection of jidesha on firefox to " +
  2635. "finish.");
  2636. return;
  2637. }
  2638. // We need an extension and it isn't installed.
  2639. // Make sure we check for the extension when the user clicks again.
  2640. firefoxExtInstalled = null;
  2641. reDetectFirefoxExtension = true;
  2642. // Prompt the user to install the extension
  2643. this.eventEmitter.emit(
  2644. DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  2645. this.options.desktopSharingFirefoxExtensionURL);
  2646. // Make sure desktopsharing knows that we failed, so that it doesn't get
  2647. // stuck in 'switching' mode.
  2648. errorCallback('Firefox extension required.');
  2649. },
  2650. /**
  2651. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  2652. * 'desktop' stream for returned stream token.
  2653. */
  2654. obtainScreenFromExtension: function (streamCallback, failCallback) {
  2655. if (chromeExtInstalled) {
  2656. doGetStreamFromExtension(this.options, streamCallback,
  2657. failCallback);
  2658. } else {
  2659. if (chromeExtUpdateRequired) {
  2660. alert(
  2661. 'Jitsi Desktop Streamer requires update. ' +
  2662. 'Changes will take effect after next Chrome restart.');
  2663. }
  2664. chrome.webstore.install(
  2665. getWebStoreInstallUrl(this.options),
  2666. function (arg) {
  2667. logger.log("Extension installed successfully", arg);
  2668. chromeExtInstalled = true;
  2669. // We need to give a moment for the endpoint to become
  2670. // available
  2671. window.setTimeout(function () {
  2672. doGetStreamFromExtension(this.options, streamCallback,
  2673. failCallback);
  2674. }, 500);
  2675. },
  2676. function (arg) {
  2677. logger.log("Failed to install the extension", arg);
  2678. failCallback(arg);
  2679. }
  2680. );
  2681. }
  2682. }
  2683. };
  2684. /**
  2685. * Obtains a desktop stream using getUserMedia.
  2686. * For this to work on Chrome, the
  2687. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  2688. *
  2689. * On firefox, the document's domain must be white-listed in the
  2690. * 'media.getusermedia.screensharing.allowed_domains' preference in
  2691. * 'about:config'.
  2692. */
  2693. function obtainWebRTCScreen(streamCallback, failCallback) {
  2694. GUM(
  2695. ['screen'],
  2696. streamCallback,
  2697. failCallback
  2698. );
  2699. }
  2700. /**
  2701. * Constructs inline install URL for Chrome desktop streaming extension.
  2702. * The 'chromeExtensionId' must be defined in options parameter.
  2703. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  2704. * @returns {string}
  2705. */
  2706. function getWebStoreInstallUrl(options)
  2707. {
  2708. //TODO remove chromeExtensionId (deprecated)
  2709. return "https://chrome.google.com/webstore/detail/" +
  2710. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  2711. }
  2712. /**
  2713. * Checks whether an update of the Chrome extension is required.
  2714. * @param minVersion minimal required version
  2715. * @param extVersion current extension version
  2716. * @returns {boolean}
  2717. */
  2718. function isUpdateRequired(minVersion, extVersion) {
  2719. try {
  2720. var s1 = minVersion.split('.');
  2721. var s2 = extVersion.split('.');
  2722. var len = Math.max(s1.length, s2.length);
  2723. for (var i = 0; i < len; i++) {
  2724. var n1 = 0,
  2725. n2 = 0;
  2726. if (i < s1.length)
  2727. n1 = parseInt(s1[i]);
  2728. if (i < s2.length)
  2729. n2 = parseInt(s2[i]);
  2730. if (isNaN(n1) || isNaN(n2)) {
  2731. return true;
  2732. } else if (n1 !== n2) {
  2733. return n1 > n2;
  2734. }
  2735. }
  2736. // will happen if both versions have identical numbers in
  2737. // their components (even if one of them is longer, has more components)
  2738. return false;
  2739. }
  2740. catch (e) {
  2741. logger.error("Failed to parse extension version", e);
  2742. return true;
  2743. }
  2744. }
  2745. function checkChromeExtInstalled(callback, options) {
  2746. if (!chrome || !chrome.runtime) {
  2747. // No API, so no extension for sure
  2748. callback(false, false);
  2749. return;
  2750. }
  2751. chrome.runtime.sendMessage(
  2752. //TODO: remove chromeExtensionId (deprecated)
  2753. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  2754. { getVersion: true },
  2755. function (response) {
  2756. if (!response || !response.version) {
  2757. // Communication failure - assume that no endpoint exists
  2758. logger.warn(
  2759. "Extension not installed?: ", chrome.runtime.lastError);
  2760. callback(false, false);
  2761. return;
  2762. }
  2763. // Check installed extension version
  2764. var extVersion = response.version;
  2765. logger.log('Extension version is: ' + extVersion);
  2766. //TODO: remove minChromeExtVersion (deprecated)
  2767. var updateRequired
  2768. = isUpdateRequired(
  2769. (options.desktopSharingChromeMinExtVersion ||
  2770. options.minChromeExtVersion),
  2771. extVersion);
  2772. callback(!updateRequired, updateRequired);
  2773. }
  2774. );
  2775. }
  2776. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  2777. // Sends 'getStream' msg to the extension.
  2778. // Extension id must be defined in the config.
  2779. chrome.runtime.sendMessage(
  2780. //TODO: remove chromeExtensionId (deprecated)
  2781. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  2782. {
  2783. getStream: true,
  2784. //TODO: remove desktopSharingSources (deprecated).
  2785. sources: (options.desktopSharingChromeSources ||
  2786. options.desktopSharingSources)
  2787. },
  2788. function (response) {
  2789. if (!response) {
  2790. failCallback(chrome.runtime.lastError);
  2791. return;
  2792. }
  2793. logger.log("Response from extension: " + response);
  2794. if (response.streamId) {
  2795. GUM(
  2796. ['desktop'],
  2797. function (stream) {
  2798. streamCallback(stream);
  2799. },
  2800. failCallback,
  2801. {desktopStream: response.streamId});
  2802. } else {
  2803. failCallback("Extension failed to get the stream");
  2804. }
  2805. }
  2806. );
  2807. }
  2808. /**
  2809. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  2810. * config.js to support inline installs. Host site must be selected as main
  2811. * website of published extension.
  2812. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  2813. */
  2814. function initInlineInstalls(options)
  2815. {
  2816. $("link[rel=chrome-webstore-item]").attr("href",
  2817. getWebStoreInstallUrl(options));
  2818. }
  2819. function initChromeExtension(options) {
  2820. // Initialize Chrome extension inline installs
  2821. initInlineInstalls(options);
  2822. // Check if extension is installed
  2823. checkChromeExtInstalled(function (installed, updateRequired) {
  2824. chromeExtInstalled = installed;
  2825. chromeExtUpdateRequired = updateRequired;
  2826. logger.info(
  2827. "Chrome extension installed: " + chromeExtInstalled +
  2828. " updateRequired: " + chromeExtUpdateRequired);
  2829. }, options);
  2830. }
  2831. /**
  2832. * Starts the detection of an installed jidesha extension for firefox.
  2833. * @param options supports "desktopSharingFirefoxDisabled",
  2834. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  2835. */
  2836. function initFirefoxExtensionDetection(options) {
  2837. if (options.desktopSharingFirefoxDisabled) {
  2838. return;
  2839. }
  2840. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  2841. return;
  2842. if (!options.desktopSharingFirefoxExtId) {
  2843. firefoxExtInstalled = false;
  2844. return;
  2845. }
  2846. var img = document.createElement('img');
  2847. img.onload = function(){
  2848. logger.log("Detected firefox screen sharing extension.");
  2849. firefoxExtInstalled = true;
  2850. };
  2851. img.onerror = function(){
  2852. logger.log("Detected lack of firefox screen sharing extension.");
  2853. firefoxExtInstalled = false;
  2854. };
  2855. // The jidesha extension exposes an empty image file under the url:
  2856. // "chrome://EXT_ID/content/DOMAIN.png"
  2857. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  2858. // DOMAIN is a domain whitelisted by the extension.
  2859. var src = "chrome://" +
  2860. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  2861. "/content/" + document.location.hostname + ".png";
  2862. img.setAttribute('src', src);
  2863. }
  2864. module.exports = ScreenObtainer;
  2865. }).call(this,"/modules/RTC/ScreenObtainer.js")
  2866. },{"../../service/desktopsharing/DesktopSharingEventTypes":83,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":47}],20:[function(require,module,exports){
  2867. (function (__filename){
  2868. /*! adapterjs - v0.12.0 - 2015-09-04 */
  2869. var console = require("jitsi-meet-logger").getLogger(__filename);
  2870. // Adapter's interface.
  2871. var AdapterJS = AdapterJS || {};
  2872. // Browserify compatibility
  2873. if(typeof exports !== 'undefined') {
  2874. module.exports = AdapterJS;
  2875. }
  2876. AdapterJS.options = AdapterJS.options || {};
  2877. // uncomment to get virtual webcams
  2878. // AdapterJS.options.getAllCams = true;
  2879. // uncomment to prevent the install prompt when the plugin in not yet installed
  2880. // AdapterJS.options.hidePluginInstallPrompt = true;
  2881. // AdapterJS version
  2882. AdapterJS.VERSION = '0.12.0';
  2883. // This function will be called when the WebRTC API is ready to be used
  2884. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  2885. // the plugin
  2886. // You may Override this function to synchronise the start of your application
  2887. // with the WebRTC API being ready.
  2888. // If you decide not to override use this synchronisation, it may result in
  2889. // an extensive CPU usage on the plugin start (once per tab loaded)
  2890. // Params:
  2891. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  2892. //
  2893. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  2894. // The WebRTC API is ready.
  2895. // Override me and do whatever you want here
  2896. };
  2897. // Sets a callback function to be called when the WebRTC interface is ready.
  2898. // The first argument is the function to callback.\
  2899. // Throws an error if the first argument is not a function
  2900. AdapterJS.webRTCReady = function (callback) {
  2901. if (typeof callback !== 'function') {
  2902. throw new Error('Callback provided is not a function');
  2903. }
  2904. if (true === AdapterJS.onwebrtcreadyDone) {
  2905. // All WebRTC interfaces are ready, just call the callback
  2906. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  2907. } else {
  2908. // will be triggered automatically when your browser/plugin is ready.
  2909. AdapterJS.onwebrtcready = callback;
  2910. }
  2911. };
  2912. // Plugin namespace
  2913. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  2914. // The object to store plugin information
  2915. AdapterJS.WebRTCPlugin.pluginInfo = {
  2916. prefix : 'Tem',
  2917. plugName : 'TemWebRTCPlugin',
  2918. pluginId : 'plugin0',
  2919. type : 'application/x-temwebrtcplugin',
  2920. onload : '__TemWebRTCReady0',
  2921. portalLink : 'http://skylink.io/plugin/',
  2922. downloadLink : null, //set below
  2923. companyName: 'Temasys'
  2924. };
  2925. if(!!navigator.platform.match(/^Mac/i)) {
  2926. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  2927. }
  2928. else if(!!navigator.platform.match(/^Win/i)) {
  2929. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  2930. }
  2931. AdapterJS.WebRTCPlugin.TAGS = {
  2932. NONE : 'none',
  2933. AUDIO : 'audio',
  2934. VIDEO : 'video'
  2935. };
  2936. // Unique identifier of each opened page
  2937. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  2938. // Use this whenever you want to call the plugin.
  2939. AdapterJS.WebRTCPlugin.plugin = null;
  2940. // Set log level for the plugin once it is ready.
  2941. // The different values are
  2942. // This is an asynchronous function that will run when the plugin is ready
  2943. AdapterJS.WebRTCPlugin.setLogLevel = null;
  2944. // Defines webrtc's JS interface according to the plugin's implementation.
  2945. // Define plugin Browsers as WebRTC Interface.
  2946. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  2947. // This function detects whether or not a plugin is installed.
  2948. // Checks if Not IE (firefox, for example), else if it's IE,
  2949. // we're running IE and do something. If not it is not supported.
  2950. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  2951. // Lets adapter.js wait until the the document is ready before injecting the plugin
  2952. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  2953. // Inject the HTML DOM object element into the page.
  2954. AdapterJS.WebRTCPlugin.injectPlugin = null;
  2955. // States of readiness that the plugin goes through when
  2956. // being injected and stated
  2957. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  2958. NONE : 0, // no plugin use
  2959. INITIALIZING : 1, // Detected need for plugin
  2960. INJECTING : 2, // Injecting plugin
  2961. INJECTED: 3, // Plugin element injected but not usable yet
  2962. READY: 4 // Plugin ready to be used
  2963. };
  2964. // Current state of the plugin. You cannot use the plugin before this is
  2965. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  2966. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  2967. // True is AdapterJS.onwebrtcready was already called, false otherwise
  2968. // Used to make sure AdapterJS.onwebrtcready is only called once
  2969. AdapterJS.onwebrtcreadyDone = false;
  2970. // Log levels for the plugin.
  2971. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  2972. /*
  2973. Log outputs are prefixed in some cases.
  2974. INFO: Information reported by the plugin.
  2975. ERROR: Errors originating from within the plugin.
  2976. WEBRTC: Error originating from within the libWebRTC library
  2977. */
  2978. // From the least verbose to the most verbose
  2979. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  2980. NONE : 'NONE',
  2981. ERROR : 'ERROR',
  2982. WARNING : 'WARNING',
  2983. INFO: 'INFO',
  2984. VERBOSE: 'VERBOSE',
  2985. SENSITIVE: 'SENSITIVE'
  2986. };
  2987. // Does a waiting check before proceeding to load the plugin.
  2988. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  2989. // This methid will use an interval to wait for the plugin to be ready.
  2990. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  2991. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  2992. // This function will be called when plugin is ready. It sends necessary
  2993. // details to the plugin.
  2994. // The function will wait for the document to be ready and the set the
  2995. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  2996. // indicating that it can start being requested.
  2997. // This function is not in the IE/Safari condition brackets so that
  2998. // TemPluginLoaded function might be called on Chrome/Firefox.
  2999. // This function is the only private function that is not encapsulated to
  3000. // allow the plugin method to be called.
  3001. __TemWebRTCReady0 = function () {
  3002. if (document.readyState === 'complete') {
  3003. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3004. AdapterJS.maybeThroughWebRTCReady();
  3005. } else {
  3006. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3007. if (document.readyState === 'complete') {
  3008. // TODO: update comments, we wait for the document to be ready
  3009. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3010. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3011. AdapterJS.maybeThroughWebRTCReady();
  3012. }
  3013. }, 100);
  3014. }
  3015. };
  3016. AdapterJS.maybeThroughWebRTCReady = function() {
  3017. if (!AdapterJS.onwebrtcreadyDone) {
  3018. AdapterJS.onwebrtcreadyDone = true;
  3019. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3020. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3021. }
  3022. }
  3023. };
  3024. // Text namespace
  3025. AdapterJS.TEXT = {
  3026. PLUGIN: {
  3027. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3028. 'to work on this browser.',
  3029. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3030. BUTTON: 'Install Now'
  3031. },
  3032. REFRESH: {
  3033. REQUIRE_REFRESH: 'Please refresh page',
  3034. BUTTON: 'Refresh Page'
  3035. }
  3036. };
  3037. // The result of ice connection states.
  3038. // - starting: Ice connection is starting.
  3039. // - checking: Ice connection is checking.
  3040. // - connected Ice connection is connected.
  3041. // - completed Ice connection is connected.
  3042. // - done Ice connection has been completed.
  3043. // - disconnected Ice connection has been disconnected.
  3044. // - failed Ice connection has failed.
  3045. // - closed Ice connection is closed.
  3046. AdapterJS._iceConnectionStates = {
  3047. starting : 'starting',
  3048. checking : 'checking',
  3049. connected : 'connected',
  3050. completed : 'connected',
  3051. done : 'completed',
  3052. disconnected : 'disconnected',
  3053. failed : 'failed',
  3054. closed : 'closed'
  3055. };
  3056. //The IceConnection states that has been fired for each peer.
  3057. AdapterJS._iceConnectionFiredStates = [];
  3058. // Check if WebRTC Interface is defined.
  3059. AdapterJS.isDefined = null;
  3060. // This function helps to retrieve the webrtc detected browser information.
  3061. // This sets:
  3062. // - webrtcDetectedBrowser: The browser agent name.
  3063. // - webrtcDetectedVersion: The browser version.
  3064. // - webrtcDetectedType: The types of webRTC support.
  3065. // - 'moz': Mozilla implementation of webRTC.
  3066. // - 'webkit': WebKit implementation of webRTC.
  3067. // - 'plugin': Using the plugin implementation.
  3068. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3069. var hasMatch, checkMatch = navigator.userAgent.match(
  3070. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3071. if (/trident/i.test(checkMatch[1])) {
  3072. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3073. webrtcDetectedBrowser = 'IE';
  3074. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3075. } else if (checkMatch[1] === 'Chrome') {
  3076. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3077. if (hasMatch !== null) {
  3078. webrtcDetectedBrowser = 'opera';
  3079. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3080. }
  3081. }
  3082. if (navigator.userAgent.indexOf('Safari')) {
  3083. if (typeof InstallTrigger !== 'undefined') {
  3084. webrtcDetectedBrowser = 'firefox';
  3085. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3086. webrtcDetectedBrowser = 'IE';
  3087. } else if (
  3088. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3089. webrtcDetectedBrowser = 'safari';
  3090. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3091. webrtcDetectedBrowser = 'opera';
  3092. } else if (!!window.chrome) {
  3093. webrtcDetectedBrowser = 'chrome';
  3094. }
  3095. }
  3096. if (!webrtcDetectedBrowser) {
  3097. webrtcDetectedVersion = checkMatch[1];
  3098. }
  3099. if (!webrtcDetectedVersion) {
  3100. try {
  3101. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3102. [navigator.appName, navigator.appVersion, '-?'];
  3103. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3104. checkMatch.splice(1, 1, hasMatch[1]);
  3105. }
  3106. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3107. } catch (error) { }
  3108. }
  3109. };
  3110. // To fix configuration as some browsers does not support
  3111. // the 'urls' attribute.
  3112. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3113. if (pcConfig === null) {
  3114. return;
  3115. }
  3116. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3117. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3118. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3119. delete pcConfig.iceServers[i].urls;
  3120. }
  3121. }
  3122. };
  3123. AdapterJS.addEvent = function(elem, evnt, func) {
  3124. if (elem.addEventListener) { // W3C DOM
  3125. elem.addEventListener(evnt, func, false);
  3126. } else if (elem.attachEvent) {// OLD IE DOM
  3127. elem.attachEvent('on'+evnt, func);
  3128. } else { // No much to do
  3129. elem[evnt] = func;
  3130. }
  3131. };
  3132. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3133. // only inject once the page is ready
  3134. if (document.readyState !== 'complete') {
  3135. return;
  3136. }
  3137. var w = window;
  3138. var i = document.createElement('iframe');
  3139. i.style.position = 'fixed';
  3140. i.style.top = '-41px';
  3141. i.style.left = 0;
  3142. i.style.right = 0;
  3143. i.style.width = '100%';
  3144. i.style.height = '40px';
  3145. i.style.backgroundColor = '#ffffe1';
  3146. i.style.border = 'none';
  3147. i.style.borderBottom = '1px solid #888888';
  3148. i.style.zIndex = '9999999';
  3149. if(typeof i.style.webkitTransition === 'string') {
  3150. i.style.webkitTransition = 'all .5s ease-out';
  3151. } else if(typeof i.style.transition === 'string') {
  3152. i.style.transition = 'all .5s ease-out';
  3153. }
  3154. document.body.appendChild(i);
  3155. c = (i.contentWindow) ? i.contentWindow :
  3156. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3157. c.document.open();
  3158. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3159. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3160. 'middle; cursor: default;">' + text + '</span>');
  3161. if(buttonText && buttonLink) {
  3162. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3163. c.document.close();
  3164. // On click on okay
  3165. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3166. if (!!displayRefreshBar) {
  3167. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3168. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3169. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3170. }
  3171. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3172. e.preventDefault();
  3173. try {
  3174. event.cancelBubble = true;
  3175. } catch(error) { }
  3176. var pluginInstallInterval = setInterval(function(){
  3177. if(! isIE) {
  3178. navigator.plugins.refresh(false);
  3179. }
  3180. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3181. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3182. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3183. function() { // plugin now installed
  3184. clearInterval(pluginInstallInterval);
  3185. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3186. },
  3187. function() {
  3188. // still no plugin detected, nothing to do
  3189. });
  3190. } , 500);
  3191. });
  3192. // On click on Cancel
  3193. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3194. w.document.body.removeChild(i);
  3195. });
  3196. } else {
  3197. c.document.close();
  3198. }
  3199. setTimeout(function() {
  3200. if(typeof i.style.webkitTransform === 'string') {
  3201. i.style.webkitTransform = 'translateY(40px)';
  3202. } else if(typeof i.style.transform === 'string') {
  3203. i.style.transform = 'translateY(40px)';
  3204. } else {
  3205. i.style.top = '0px';
  3206. }
  3207. }, 300);
  3208. };
  3209. // -----------------------------------------------------------
  3210. // Detected webrtc implementation. Types are:
  3211. // - 'moz': Mozilla implementation of webRTC.
  3212. // - 'webkit': WebKit implementation of webRTC.
  3213. // - 'plugin': Using the plugin implementation.
  3214. webrtcDetectedType = null;
  3215. // Detected webrtc datachannel support. Types are:
  3216. // - 'SCTP': SCTP datachannel support.
  3217. // - 'RTP': RTP datachannel support.
  3218. webrtcDetectedDCSupport = null;
  3219. // Set the settings for creating DataChannels, MediaStream for
  3220. // Cross-browser compability.
  3221. // - This is only for SCTP based support browsers.
  3222. // the 'urls' attribute.
  3223. checkMediaDataChannelSettings =
  3224. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3225. if (typeof callback !== 'function') {
  3226. return;
  3227. }
  3228. var beOfferer = true;
  3229. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3230. // Nightly version does not require MozDontOfferDataChannel for interop
  3231. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3232. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3233. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3234. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3235. // Resends an updated version of constraints for MozDataChannel to work
  3236. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3237. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3238. try {
  3239. delete constraints.mandatory.MozDontOfferDataChannel;
  3240. } catch (error) {
  3241. console.error('Failed deleting MozDontOfferDataChannel');
  3242. console.error(error);
  3243. }
  3244. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3245. constraints.mandatory.MozDontOfferDataChannel = true;
  3246. }
  3247. if (!isLocalFirefox) {
  3248. // temporary measure to remove Moz* constraints in non Firefox browsers
  3249. for (var prop in constraints.mandatory) {
  3250. if (constraints.mandatory.hasOwnProperty(prop)) {
  3251. if (prop.indexOf('Moz') !== -1) {
  3252. delete constraints.mandatory[prop];
  3253. }
  3254. }
  3255. }
  3256. }
  3257. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3258. // interopability of the media stream
  3259. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  3260. beOfferer = false;
  3261. }
  3262. callback(beOfferer, constraints);
  3263. };
  3264. // Handles the differences for all browsers ice connection state output.
  3265. // - Tested outcomes are:
  3266. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  3267. // - Chrome (answerer) : 'checking' > 'connected'
  3268. // - Firefox (offerer) : 'checking' > 'connected'
  3269. // - Firefox (answerer): 'checking' > 'connected'
  3270. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  3271. if (typeof callback !== 'function') {
  3272. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  3273. return;
  3274. }
  3275. peerId = (peerId) ? peerId : 'peer';
  3276. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  3277. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  3278. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  3279. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  3280. AdapterJS._iceConnectionFiredStates[peerId] = [];
  3281. }
  3282. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  3283. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  3284. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  3285. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  3286. setTimeout(function () {
  3287. AdapterJS._iceConnectionFiredStates[peerId]
  3288. .push(AdapterJS._iceConnectionStates.done);
  3289. callback(AdapterJS._iceConnectionStates.done);
  3290. }, 1000);
  3291. }
  3292. callback(iceConnectionState);
  3293. }
  3294. return;
  3295. };
  3296. // Firefox:
  3297. // - Creates iceServer from the url for Firefox.
  3298. // - Create iceServer with stun url.
  3299. // - Create iceServer with turn url.
  3300. // - Ignore the transport parameter from TURN url for FF version <=27.
  3301. // - Return null for createIceServer if transport=tcp.
  3302. // - FF 27 and above supports transport parameters in TURN url,
  3303. // - So passing in the full url to create iceServer.
  3304. // Chrome:
  3305. // - Creates iceServer from the url for Chrome M33 and earlier.
  3306. // - Create iceServer with stun url.
  3307. // - Chrome M28 & above uses below TURN format.
  3308. // Plugin:
  3309. // - Creates Ice Server for Plugin Browsers
  3310. // - If Stun - Create iceServer with stun url.
  3311. // - Else - Create iceServer with turn url
  3312. // - This is a WebRTC Function
  3313. createIceServer = null;
  3314. // Firefox:
  3315. // - Creates IceServers for Firefox
  3316. // - Use .url for FireFox.
  3317. // - Multiple Urls support
  3318. // Chrome:
  3319. // - Creates iceServers from the urls for Chrome M34 and above.
  3320. // - .urls is supported since Chrome M34.
  3321. // - Multiple Urls support
  3322. // Plugin:
  3323. // - Creates Ice Servers for Plugin Browsers
  3324. // - Multiple Urls support
  3325. // - This is a WebRTC Function
  3326. createIceServers = null;
  3327. //------------------------------------------------------------
  3328. //The RTCPeerConnection object.
  3329. RTCPeerConnection = null;
  3330. // Creates RTCSessionDescription object for Plugin Browsers
  3331. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  3332. RTCSessionDescription : null;
  3333. // Creates RTCIceCandidate object for Plugin Browsers
  3334. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  3335. RTCIceCandidate : null;
  3336. // Get UserMedia (only difference is the prefix).
  3337. // Code from Adam Barth.
  3338. getUserMedia = null;
  3339. // Attach a media stream to an element.
  3340. attachMediaStream = null;
  3341. // Re-attach a media stream to an element.
  3342. reattachMediaStream = null;
  3343. // Detected browser agent name. Types are:
  3344. // - 'firefox': Firefox browser.
  3345. // - 'chrome': Chrome browser.
  3346. // - 'opera': Opera browser.
  3347. // - 'safari': Safari browser.
  3348. // - 'IE' - Internet Explorer browser.
  3349. webrtcDetectedBrowser = null;
  3350. // Detected browser version.
  3351. webrtcDetectedVersion = null;
  3352. // Check for browser types and react accordingly
  3353. if (navigator.mozGetUserMedia) {
  3354. webrtcDetectedBrowser = 'firefox';
  3355. webrtcDetectedVersion = parseInt(navigator
  3356. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  3357. webrtcDetectedType = 'moz';
  3358. webrtcDetectedDCSupport = 'SCTP';
  3359. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3360. AdapterJS.maybeFixConfiguration(pcConfig);
  3361. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  3362. };
  3363. // The RTCSessionDescription object.
  3364. RTCSessionDescription = mozRTCSessionDescription;
  3365. window.RTCSessionDescription = RTCSessionDescription;
  3366. // The RTCIceCandidate object.
  3367. RTCIceCandidate = mozRTCIceCandidate;
  3368. window.RTCIceCandidate = RTCIceCandidate;
  3369. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  3370. navigator.getUserMedia = window.getUserMedia;
  3371. // Shim for MediaStreamTrack.getSources.
  3372. MediaStreamTrack.getSources = function(successCb) {
  3373. setTimeout(function() {
  3374. var infos = [
  3375. { kind: 'audio', id: 'default', label:'', facing:'' },
  3376. { kind: 'video', id: 'default', label:'', facing:'' }
  3377. ];
  3378. successCb(infos);
  3379. }, 0);
  3380. };
  3381. createIceServer = function (url, username, password) {
  3382. var iceServer = null;
  3383. var url_parts = url.split(':');
  3384. if (url_parts[0].indexOf('stun') === 0) {
  3385. iceServer = { url : url };
  3386. } else if (url_parts[0].indexOf('turn') === 0) {
  3387. if (webrtcDetectedVersion < 27) {
  3388. var turn_url_parts = url.split('?');
  3389. if (turn_url_parts.length === 1 ||
  3390. turn_url_parts[1].indexOf('transport=udp') === 0) {
  3391. iceServer = {
  3392. url : turn_url_parts[0],
  3393. credential : password,
  3394. username : username
  3395. };
  3396. }
  3397. } else {
  3398. iceServer = {
  3399. url : url,
  3400. credential : password,
  3401. username : username
  3402. };
  3403. }
  3404. }
  3405. return iceServer;
  3406. };
  3407. createIceServers = function (urls, username, password) {
  3408. var iceServers = [];
  3409. for (i = 0; i < urls.length; i++) {
  3410. var iceServer = createIceServer(urls[i], username, password);
  3411. if (iceServer !== null) {
  3412. iceServers.push(iceServer);
  3413. }
  3414. }
  3415. return iceServers;
  3416. };
  3417. attachMediaStream = function (element, stream) {
  3418. element.mozSrcObject = stream;
  3419. if (stream !== null)
  3420. element.play();
  3421. return element;
  3422. };
  3423. reattachMediaStream = function (to, from) {
  3424. to.mozSrcObject = from.mozSrcObject;
  3425. to.play();
  3426. return to;
  3427. };
  3428. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  3429. if (!callback) {
  3430. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  3431. ': 1 argument required, but only 0 present.');
  3432. }
  3433. return callback([]);
  3434. };
  3435. // Fake get{Video,Audio}Tracks
  3436. if (!MediaStream.prototype.getVideoTracks) {
  3437. MediaStream.prototype.getVideoTracks = function () {
  3438. return [];
  3439. };
  3440. }
  3441. if (!MediaStream.prototype.getAudioTracks) {
  3442. MediaStream.prototype.getAudioTracks = function () {
  3443. return [];
  3444. };
  3445. }
  3446. AdapterJS.maybeThroughWebRTCReady();
  3447. } else if (navigator.webkitGetUserMedia) {
  3448. webrtcDetectedBrowser = 'chrome';
  3449. webrtcDetectedType = 'webkit';
  3450. webrtcDetectedVersion = parseInt(navigator
  3451. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  3452. // check if browser is opera 20+
  3453. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3454. if (checkIfOpera !== null) {
  3455. webrtcDetectedBrowser = 'opera';
  3456. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  3457. }
  3458. // check browser datachannel support
  3459. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  3460. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  3461. webrtcDetectedDCSupport = 'SCTP';
  3462. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  3463. webrtcDetectedVersion > 24) {
  3464. webrtcDetectedDCSupport = 'RTP';
  3465. } else {
  3466. webrtcDetectedDCSupport = '';
  3467. }
  3468. createIceServer = function (url, username, password) {
  3469. var iceServer = null;
  3470. var url_parts = url.split(':');
  3471. if (url_parts[0].indexOf('stun') === 0) {
  3472. iceServer = { 'url' : url };
  3473. } else if (url_parts[0].indexOf('turn') === 0) {
  3474. iceServer = {
  3475. 'url' : url,
  3476. 'credential' : password,
  3477. 'username' : username
  3478. };
  3479. }
  3480. return iceServer;
  3481. };
  3482. createIceServers = function (urls, username, password) {
  3483. var iceServers = [];
  3484. if (webrtcDetectedVersion >= 34) {
  3485. iceServers = {
  3486. 'urls' : urls,
  3487. 'credential' : password,
  3488. 'username' : username
  3489. };
  3490. } else {
  3491. for (i = 0; i < urls.length; i++) {
  3492. var iceServer = createIceServer(urls[i], username, password);
  3493. if (iceServer !== null) {
  3494. iceServers.push(iceServer);
  3495. }
  3496. }
  3497. }
  3498. return iceServers;
  3499. };
  3500. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3501. if (webrtcDetectedVersion < 34) {
  3502. AdapterJS.maybeFixConfiguration(pcConfig);
  3503. }
  3504. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3505. };
  3506. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3507. navigator.getUserMedia = window.getUserMedia;
  3508. attachMediaStream = function (element, stream) {
  3509. if (typeof element.srcObject !== 'undefined') {
  3510. element.srcObject = stream;
  3511. } else if (typeof element.mozSrcObject !== 'undefined') {
  3512. element.mozSrcObject = stream;
  3513. } else if (typeof element.src !== 'undefined') {
  3514. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  3515. } else {
  3516. console.log('Error attaching stream to element.');
  3517. }
  3518. return element;
  3519. };
  3520. reattachMediaStream = function (to, from) {
  3521. to.src = from.src;
  3522. return to;
  3523. };
  3524. AdapterJS.maybeThroughWebRTCReady();
  3525. } else if (navigator.mediaDevices && navigator.userAgent.match(
  3526. /Edge\/(\d+).(\d+)$/)) {
  3527. webrtcDetectedBrowser = 'edge';
  3528. webrtcDetectedVersion =
  3529. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  3530. // the minimum version still supported by adapter.
  3531. webrtcMinimumVersion = 12;
  3532. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3533. attachMediaStream = function(element, stream) {
  3534. element.srcObject = stream;
  3535. return element;
  3536. };
  3537. reattachMediaStream = function(to, from) {
  3538. to.srcObject = from.srcObject;
  3539. return to;
  3540. };
  3541. AdapterJS.maybeThroughWebRTCReady();
  3542. } else { // TRY TO USE PLUGIN
  3543. // IE 9 is not offering an implementation of console.log until you open a console
  3544. if (typeof console !== 'object' || typeof console.log !== 'function') {
  3545. /* jshint -W020 */
  3546. console = {} || console;
  3547. // Implemented based on console specs from MDN
  3548. // You may override these functions
  3549. console.log = function (arg) {};
  3550. console.info = function (arg) {};
  3551. console.error = function (arg) {};
  3552. console.dir = function (arg) {};
  3553. console.exception = function (arg) {};
  3554. console.trace = function (arg) {};
  3555. console.warn = function (arg) {};
  3556. console.count = function (arg) {};
  3557. console.debug = function (arg) {};
  3558. console.count = function (arg) {};
  3559. console.time = function (arg) {};
  3560. console.timeEnd = function (arg) {};
  3561. console.group = function (arg) {};
  3562. console.groupCollapsed = function (arg) {};
  3563. console.groupEnd = function (arg) {};
  3564. /* jshint +W020 */
  3565. }
  3566. webrtcDetectedType = 'plugin';
  3567. webrtcDetectedDCSupport = 'plugin';
  3568. AdapterJS.parseWebrtcDetectedBrowser();
  3569. isIE = webrtcDetectedBrowser === 'IE';
  3570. /* jshint -W035 */
  3571. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  3572. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3573. /* empty because it needs to prevent the function from running. */
  3574. }
  3575. };
  3576. /* jshint +W035 */
  3577. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  3578. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3579. // Call immediately if possible
  3580. // Once the plugin is set, the code will always take this path
  3581. callback();
  3582. } else {
  3583. // otherwise start a 100ms interval
  3584. var checkPluginReadyState = setInterval(function () {
  3585. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3586. clearInterval(checkPluginReadyState);
  3587. callback();
  3588. }
  3589. }, 100);
  3590. }
  3591. };
  3592. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  3593. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3594. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  3595. });
  3596. };
  3597. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  3598. // only inject once the page is ready
  3599. if (document.readyState !== 'complete') {
  3600. return;
  3601. }
  3602. // Prevent multiple injections
  3603. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  3604. return;
  3605. }
  3606. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  3607. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  3608. var frag = document.createDocumentFragment();
  3609. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  3610. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  3611. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  3612. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  3613. '<param name="pluginId" value="' +
  3614. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  3615. '<param name="windowless" value="false" /> ' +
  3616. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3617. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  3618. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  3619. // uncomment to be able to use virtual cams
  3620. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3621. '</object>';
  3622. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  3623. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  3624. }
  3625. document.body.appendChild(frag);
  3626. // Need to re-fetch the plugin
  3627. AdapterJS.WebRTCPlugin.plugin =
  3628. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  3629. } else {
  3630. // Load Plugin
  3631. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  3632. AdapterJS.WebRTCPlugin.plugin.id =
  3633. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  3634. // IE will only start the plugin if it's ACTUALLY visible
  3635. if (isIE) {
  3636. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  3637. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  3638. } else { // The size of the plugin on Safari should be 0x0px
  3639. // so that the autorisation prompt is at the top
  3640. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  3641. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  3642. }
  3643. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  3644. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  3645. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  3646. '<param name="pluginId" value="' +
  3647. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  3648. '<param name="windowless" value="false" /> ' +
  3649. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3650. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  3651. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  3652. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  3653. }
  3654. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  3655. };
  3656. AdapterJS.WebRTCPlugin.isPluginInstalled =
  3657. function (comName, plugName, installedCb, notInstalledCb) {
  3658. if (!isIE) {
  3659. var pluginArray = navigator.plugins;
  3660. for (var i = 0; i < pluginArray.length; i++) {
  3661. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  3662. installedCb();
  3663. return;
  3664. }
  3665. }
  3666. notInstalledCb();
  3667. } else {
  3668. try {
  3669. var axo = new ActiveXObject(comName + '.' + plugName);
  3670. } catch (e) {
  3671. notInstalledCb();
  3672. return;
  3673. }
  3674. installedCb();
  3675. }
  3676. };
  3677. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  3678. if (AdapterJS.WebRTCPlugin.pluginState ===
  3679. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3680. console.error("AdapterJS - WebRTC interface has already been defined");
  3681. return;
  3682. }
  3683. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  3684. AdapterJS.isDefined = function (variable) {
  3685. return variable !== null && variable !== undefined;
  3686. };
  3687. createIceServer = function (url, username, password) {
  3688. var iceServer = null;
  3689. var url_parts = url.split(':');
  3690. if (url_parts[0].indexOf('stun') === 0) {
  3691. iceServer = {
  3692. 'url' : url,
  3693. 'hasCredentials' : false
  3694. };
  3695. } else if (url_parts[0].indexOf('turn') === 0) {
  3696. iceServer = {
  3697. 'url' : url,
  3698. 'hasCredentials' : true,
  3699. 'credential' : password,
  3700. 'username' : username
  3701. };
  3702. }
  3703. return iceServer;
  3704. };
  3705. createIceServers = function (urls, username, password) {
  3706. var iceServers = [];
  3707. for (var i = 0; i < urls.length; ++i) {
  3708. iceServers.push(createIceServer(urls[i], username, password));
  3709. }
  3710. return iceServers;
  3711. };
  3712. RTCSessionDescription = function (info) {
  3713. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3714. return AdapterJS.WebRTCPlugin.plugin.
  3715. ConstructSessionDescription(info.type, info.sdp);
  3716. };
  3717. RTCPeerConnection = function (servers, constraints) {
  3718. var iceServers = null;
  3719. if (servers) {
  3720. iceServers = servers.iceServers;
  3721. for (var i = 0; i < iceServers.length; i++) {
  3722. if (iceServers[i].urls && !iceServers[i].url) {
  3723. iceServers[i].url = iceServers[i].urls;
  3724. }
  3725. iceServers[i].hasCredentials = AdapterJS.
  3726. isDefined(iceServers[i].username) &&
  3727. AdapterJS.isDefined(iceServers[i].credential);
  3728. }
  3729. }
  3730. var mandatory = (constraints && constraints.mandatory) ?
  3731. constraints.mandatory : null;
  3732. var optional = (constraints && constraints.optional) ?
  3733. constraints.optional : null;
  3734. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3735. return AdapterJS.WebRTCPlugin.plugin.
  3736. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  3737. iceServers, mandatory, optional);
  3738. };
  3739. MediaStreamTrack = {};
  3740. MediaStreamTrack.getSources = function (callback) {
  3741. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3742. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  3743. });
  3744. };
  3745. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  3746. constraints.audio = constraints.audio || false;
  3747. constraints.video = constraints.video || false;
  3748. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3749. AdapterJS.WebRTCPlugin.plugin.
  3750. getUserMedia(constraints, successCallback, failureCallback);
  3751. });
  3752. };
  3753. window.navigator.getUserMedia = window.getUserMedia;
  3754. attachMediaStream = function (element, stream) {
  3755. if (!element || !element.parentNode) {
  3756. return;
  3757. }
  3758. var streamId
  3759. if (stream === null) {
  3760. streamId = '';
  3761. }
  3762. else {
  3763. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  3764. streamId = stream.id;
  3765. }
  3766. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  3767. var nodeName = element.nodeName.toLowerCase();
  3768. if (nodeName !== 'object') { // not a plugin <object> tag yet
  3769. var tag;
  3770. switch(nodeName) {
  3771. case 'audio':
  3772. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  3773. break;
  3774. case 'video':
  3775. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  3776. break;
  3777. default:
  3778. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  3779. }
  3780. var frag = document.createDocumentFragment();
  3781. var temp = document.createElement('div');
  3782. var classHTML = '';
  3783. if (element.className) {
  3784. classHTML = 'class="' + element.className + '" ';
  3785. } else if (element.attributes && element.attributes['class']) {
  3786. classHTML = 'class="' + element.attributes['class'].value + '" ';
  3787. }
  3788. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  3789. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  3790. '<param name="pluginId" value="' + elementId + '" /> ' +
  3791. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3792. '<param name="windowless" value="true" /> ' +
  3793. '<param name="streamId" value="' + streamId + '" /> ' +
  3794. '<param name="tag" value="' + tag + '" /> ' +
  3795. '</object>';
  3796. while (temp.firstChild) {
  3797. frag.appendChild(temp.firstChild);
  3798. }
  3799. var height = '';
  3800. var width = '';
  3801. if (element.getBoundingClientRect) {
  3802. var rectObject = element.getBoundingClientRect();
  3803. width = rectObject.width + 'px';
  3804. height = rectObject.height + 'px';
  3805. }
  3806. else if (element.width) {
  3807. width = element.width;
  3808. height = element.height;
  3809. } else {
  3810. // TODO: What scenario could bring us here?
  3811. }
  3812. element.parentNode.insertBefore(frag, element);
  3813. frag = document.getElementById(elementId);
  3814. frag.width = width;
  3815. frag.height = height;
  3816. element.parentNode.removeChild(element);
  3817. } else { // already an <object> tag, just change the stream id
  3818. var children = element.children;
  3819. for (var i = 0; i !== children.length; ++i) {
  3820. if (children[i].name === 'streamId') {
  3821. children[i].value = streamId;
  3822. break;
  3823. }
  3824. }
  3825. element.setStreamId(streamId);
  3826. }
  3827. var newElement = document.getElementById(elementId);
  3828. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  3829. newElement.onplay = (element.onplay) ? element.onplay : function (arg) {};
  3830. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  3831. if (isIE) { // on IE the event needs to be plugged manually
  3832. newElement.attachEvent('onplaying', newElement.onplaying);
  3833. newElement.attachEvent('onplay', newElement.onplay);
  3834. newElement._TemOnClick = function (id) {
  3835. var arg = {
  3836. srcElement : document.getElementById(id)
  3837. };
  3838. newElement.onclick(arg);
  3839. };
  3840. }
  3841. return newElement;
  3842. };
  3843. reattachMediaStream = function (to, from) {
  3844. var stream = null;
  3845. var children = from.children;
  3846. for (var i = 0; i !== children.length; ++i) {
  3847. if (children[i].name === 'streamId') {
  3848. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3849. stream = AdapterJS.WebRTCPlugin.plugin
  3850. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  3851. break;
  3852. }
  3853. }
  3854. if (stream !== null) {
  3855. return attachMediaStream(to, stream);
  3856. } else {
  3857. console.log('Could not find the stream associated with this element');
  3858. }
  3859. };
  3860. RTCIceCandidate = function (candidate) {
  3861. if (!candidate.sdpMid) {
  3862. candidate.sdpMid = '';
  3863. }
  3864. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3865. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  3866. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  3867. );
  3868. };
  3869. // inject plugin
  3870. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  3871. AdapterJS.WebRTCPlugin.injectPlugin();
  3872. };
  3873. // This function will be called if the plugin is needed (browser different
  3874. // from Chrome or Firefox), but the plugin is not installed.
  3875. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  3876. function() {
  3877. AdapterJS.addEvent(document,
  3878. 'readystatechange',
  3879. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  3880. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  3881. };
  3882. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  3883. if (AdapterJS.options.hidePluginInstallPrompt) {
  3884. return;
  3885. }
  3886. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  3887. if(downloadLink) { // if download link
  3888. var popupString;
  3889. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  3890. popupString = 'This website requires you to install the ' +
  3891. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  3892. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  3893. ' WebRTC Plugin</a>' +
  3894. ' to work on this browser.';
  3895. } else { // no portal link, just print a generic explanation
  3896. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  3897. }
  3898. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  3899. } else { // no download link, just print a generic explanation
  3900. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  3901. }
  3902. };
  3903. // Try to detect the plugin and act accordingly
  3904. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3905. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3906. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3907. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  3908. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  3909. }
  3910. }).call(this,"/modules/RTC/adapter.screenshare.js")
  3911. },{"jitsi-meet-logger":47}],21:[function(require,module,exports){
  3912. (function (__filename){
  3913. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3914. function supportsLocalStorage() {
  3915. try {
  3916. return 'localStorage' in window && window.localStorage !== null;
  3917. } catch (e) {
  3918. logger.log("localstorage is not supported");
  3919. return false;
  3920. }
  3921. }
  3922. function generateUniqueId() {
  3923. function _p8() {
  3924. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3925. }
  3926. return _p8() + _p8() + _p8() + _p8();
  3927. }
  3928. function Settings(conferenceID) {
  3929. this.email = '';
  3930. this.displayName = '';
  3931. this.userId;
  3932. this.language = null;
  3933. this.confSettings = null;
  3934. this.conferenceID = conferenceID;
  3935. if (supportsLocalStorage()) {
  3936. if(!window.localStorage.getItem(conferenceID))
  3937. this.confSettings = {};
  3938. else
  3939. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3940. if(!this.confSettings.jitsiMeetId) {
  3941. this.confSettings.jitsiMeetId = generateUniqueId();
  3942. logger.log("generated id",
  3943. this.confSettings.jitsiMeetId);
  3944. this.save();
  3945. }
  3946. this.userId = this.confSettings.jitsiMeetId || '';
  3947. this.email = this.confSettings.email || '';
  3948. this.displayName = this.confSettings.displayname || '';
  3949. this.language = this.confSettings.language;
  3950. } else {
  3951. logger.log("local storage is not supported");
  3952. this.userId = generateUniqueId();
  3953. }
  3954. }
  3955. Settings.prototype.save = function () {
  3956. if(!supportsLocalStorage())
  3957. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3958. }
  3959. Settings.prototype.setDisplayName = function (newDisplayName) {
  3960. this.displayName = newDisplayName;
  3961. if(this.confSettings != null)
  3962. this.confSettings.displayname = displayName;
  3963. this.save();
  3964. return this.displayName;
  3965. },
  3966. Settings.prototype.setEmail = function (newEmail) {
  3967. this.email = newEmail;
  3968. if(this.confSettings != null)
  3969. this.confSettings.email = newEmail;
  3970. this.save();
  3971. return this.email;
  3972. },
  3973. Settings.prototype.getSettings = function () {
  3974. return {
  3975. email: this.email,
  3976. displayName: this.displayName,
  3977. uid: this.userId,
  3978. language: this.language
  3979. };
  3980. },
  3981. Settings.prototype.setLanguage = function (lang) {
  3982. this.language = lang;
  3983. if(this.confSettings != null)
  3984. this.confSettings.language = lang;
  3985. this.save();
  3986. }
  3987. module.exports = Settings;
  3988. }).call(this,"/modules/settings/Settings.js")
  3989. },{"jitsi-meet-logger":47}],22:[function(require,module,exports){
  3990. /* global config */
  3991. /**
  3992. * Provides statistics for the local stream.
  3993. */
  3994. var RTCBrowserType = require('../RTC/RTCBrowserType');
  3995. var StatisticsEvents = require('../../service/statistics/Events');
  3996. var LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  3997. /**
  3998. * Size of the webaudio analyzer buffer.
  3999. * @type {number}
  4000. */
  4001. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4002. /**
  4003. * Value of the webaudio analyzer smoothing time parameter.
  4004. * @type {number}
  4005. */
  4006. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4007. /**
  4008. * Converts time domain data array to audio level.
  4009. * @param samples the time domain data array.
  4010. * @returns {number} the audio level
  4011. */
  4012. function timeDomainDataToAudioLevel(samples) {
  4013. var maxVolume = 0;
  4014. var length = samples.length;
  4015. for (var i = 0; i < length; i++) {
  4016. if (maxVolume < samples[i])
  4017. maxVolume = samples[i];
  4018. }
  4019. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4020. }
  4021. /**
  4022. * Animates audio level change
  4023. * @param newLevel the new audio level
  4024. * @param lastLevel the last audio level
  4025. * @returns {Number} the audio level to be set
  4026. */
  4027. function animateLevel(newLevel, lastLevel) {
  4028. var value = 0;
  4029. var diff = lastLevel - newLevel;
  4030. if(diff > 0.2) {
  4031. value = lastLevel - 0.2;
  4032. }
  4033. else if(diff < -0.4) {
  4034. value = lastLevel + 0.4;
  4035. }
  4036. else {
  4037. value = newLevel;
  4038. }
  4039. return parseFloat(value.toFixed(3));
  4040. }
  4041. /**
  4042. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4043. *
  4044. * @param stream the local stream
  4045. * @param interval stats refresh interval given in ms.
  4046. * @constructor
  4047. */
  4048. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  4049. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4050. this.stream = stream;
  4051. this.intervalId = null;
  4052. this.intervalMilis = interval;
  4053. this.eventEmitter = eventEmitter;
  4054. this.audioLevel = 0;
  4055. this.statisticsService = statisticsService;
  4056. }
  4057. /**
  4058. * Starts the collecting the statistics.
  4059. */
  4060. LocalStatsCollector.prototype.start = function () {
  4061. if (!window.AudioContext ||
  4062. RTCBrowserType.isTemasysPluginUsed())
  4063. return;
  4064. var context = new AudioContext();
  4065. var analyser = context.createAnalyser();
  4066. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4067. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4068. var source = context.createMediaStreamSource(this.stream);
  4069. source.connect(analyser);
  4070. var self = this;
  4071. this.intervalId = setInterval(
  4072. function () {
  4073. var array = new Uint8Array(analyser.frequencyBinCount);
  4074. analyser.getByteTimeDomainData(array);
  4075. var audioLevel = timeDomainDataToAudioLevel(array);
  4076. if (audioLevel != self.audioLevel) {
  4077. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4078. self.eventEmitter.emit(
  4079. StatisticsEvents.AUDIO_LEVEL,
  4080. self.statisticsService.LOCAL_JID,
  4081. self.audioLevel);
  4082. }
  4083. },
  4084. this.intervalMilis
  4085. );
  4086. };
  4087. /**
  4088. * Stops collecting the statistics.
  4089. */
  4090. LocalStatsCollector.prototype.stop = function () {
  4091. if (this.intervalId) {
  4092. clearInterval(this.intervalId);
  4093. this.intervalId = null;
  4094. }
  4095. };
  4096. module.exports = LocalStatsCollector;
  4097. },{"../../service/statistics/Events":84,"../../service/statistics/constants":85,"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
  4098. (function (__filename){
  4099. /* global require, ssrc2jid */
  4100. /* jshint -W117 */
  4101. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4102. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4103. var StatisticsEvents = require("../../service/statistics/Events");
  4104. /* Whether we support the browser we are running into for logging statistics */
  4105. var browserSupported = RTCBrowserType.isChrome() ||
  4106. RTCBrowserType.isOpera();
  4107. var keyMap = {};
  4108. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4109. "ssrc": "ssrc",
  4110. "packetsReceived": "packetsReceived",
  4111. "packetsLost": "packetsLost",
  4112. "packetsSent": "packetsSent",
  4113. "bytesReceived": "bytesReceived",
  4114. "bytesSent": "bytesSent"
  4115. };
  4116. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4117. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4118. "sendBandwidth": "googAvailableSendBandwidth",
  4119. "remoteAddress": "googRemoteAddress",
  4120. "transportType": "googTransportType",
  4121. "localAddress": "googLocalAddress",
  4122. "activeConnection": "googActiveConnection",
  4123. "ssrc": "ssrc",
  4124. "packetsReceived": "packetsReceived",
  4125. "packetsSent": "packetsSent",
  4126. "packetsLost": "packetsLost",
  4127. "bytesReceived": "bytesReceived",
  4128. "bytesSent": "bytesSent",
  4129. "googFrameHeightReceived": "googFrameHeightReceived",
  4130. "googFrameWidthReceived": "googFrameWidthReceived",
  4131. "googFrameHeightSent": "googFrameHeightSent",
  4132. "googFrameWidthSent": "googFrameWidthSent",
  4133. "audioInputLevel": "audioInputLevel",
  4134. "audioOutputLevel": "audioOutputLevel"
  4135. };
  4136. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4137. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4138. /**
  4139. * Calculates packet lost percent using the number of lost packets and the
  4140. * number of all packet.
  4141. * @param lostPackets the number of lost packets
  4142. * @param totalPackets the number of all packets.
  4143. * @returns {number} packet loss percent
  4144. */
  4145. function calculatePacketLoss(lostPackets, totalPackets) {
  4146. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4147. return 0;
  4148. return Math.round((lostPackets/totalPackets)*100);
  4149. }
  4150. function getStatValue(item, name) {
  4151. var browserType = RTCBrowserType.getBrowserType();
  4152. if (!keyMap[browserType][name])
  4153. throw "The property isn't supported!";
  4154. var key = keyMap[browserType][name];
  4155. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4156. item.stat(key) : item[key];
  4157. }
  4158. function formatAudioLevel(audioLevel) {
  4159. return Math.min(Math.max(audioLevel, 0), 1);
  4160. }
  4161. /**
  4162. * Checks whether a certain record should be included in the logged statistics.
  4163. */
  4164. function acceptStat(reportId, reportType, statName) {
  4165. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4166. return false;
  4167. if (reportType == "ssrc") {
  4168. if (statName == "googTrackId" ||
  4169. statName == "transportId" ||
  4170. statName == "ssrc")
  4171. return false;
  4172. }
  4173. return true;
  4174. }
  4175. /**
  4176. * Checks whether a certain record should be included in the logged statistics.
  4177. */
  4178. function acceptReport(id, type) {
  4179. if (id.substring(0, 15) == "googCertificate" ||
  4180. id.substring(0, 9) == "googTrack" ||
  4181. id.substring(0, 20) == "googLibjingleSession")
  4182. return false;
  4183. if (type == "googComponent")
  4184. return false;
  4185. return true;
  4186. }
  4187. /**
  4188. * Peer statistics data holder.
  4189. * @constructor
  4190. */
  4191. function PeerStats()
  4192. {
  4193. this.ssrc2Loss = {};
  4194. this.ssrc2AudioLevel = {};
  4195. this.ssrc2bitrate = {};
  4196. this.ssrc2resolution = {};
  4197. }
  4198. /**
  4199. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4200. * represented by this instance.
  4201. * @param lossRate new packet loss rate value to be set.
  4202. */
  4203. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4204. {
  4205. this.ssrc2Loss = lossRate;
  4206. };
  4207. /**
  4208. * Sets resolution that belong to the ssrc
  4209. * represented by this instance.
  4210. * @param resolution new resolution value to be set.
  4211. */
  4212. PeerStats.prototype.setSsrcResolution = function (resolution)
  4213. {
  4214. if(resolution === null && this.ssrc2resolution[ssrc])
  4215. {
  4216. delete this.ssrc2resolution[ssrc];
  4217. }
  4218. else if(resolution !== null)
  4219. this.ssrc2resolution[ssrc] = resolution;
  4220. };
  4221. /**
  4222. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4223. * represented by this instance.
  4224. * @param ssrc audio or video RTP stream SSRC.
  4225. * @param bitrate new bitrate value to be set.
  4226. */
  4227. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4228. {
  4229. if(this.ssrc2bitrate[ssrc])
  4230. {
  4231. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4232. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4233. }
  4234. else {
  4235. this.ssrc2bitrate[ssrc] = bitrate;
  4236. }
  4237. };
  4238. /**
  4239. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4240. * the stream which belongs to the peer represented by this instance.
  4241. * @param ssrc RTP stream SSRC for which current audio level value will be
  4242. * updated.
  4243. * @param audioLevel the new audio level value to be set. Value is truncated to
  4244. * fit the range from 0 to 1.
  4245. */
  4246. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4247. {
  4248. // Range limit 0 - 1
  4249. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4250. };
  4251. function ConferenceStats() {
  4252. /**
  4253. * The bandwidth
  4254. * @type {{}}
  4255. */
  4256. this.bandwidth = {};
  4257. /**
  4258. * The bit rate
  4259. * @type {{}}
  4260. */
  4261. this.bitrate = {};
  4262. /**
  4263. * The packet loss rate
  4264. * @type {{}}
  4265. */
  4266. this.packetLoss = null;
  4267. /**
  4268. * Array with the transport information.
  4269. * @type {Array}
  4270. */
  4271. this.transport = [];
  4272. }
  4273. /**
  4274. * <tt>StatsCollector</tt> registers for stats updates of given
  4275. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4276. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4277. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4278. * instance as an event source.
  4279. *
  4280. * @param peerconnection webRTC peer connection object.
  4281. * @param interval stats refresh interval given in ms.
  4282. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4283. * called on stats update.
  4284. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4285. * @constructor
  4286. */
  4287. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4288. {
  4289. this.peerconnection = peerconnection;
  4290. this.baselineAudioLevelsReport = null;
  4291. this.currentAudioLevelsReport = null;
  4292. this.currentStatsReport = null;
  4293. this.baselineStatsReport = null;
  4294. this.audioLevelsIntervalId = null;
  4295. this.eventEmitter = eventEmitter;
  4296. this.config = config || {};
  4297. this.conferenceStats = new ConferenceStats();
  4298. /**
  4299. * Gather PeerConnection stats once every this many milliseconds.
  4300. */
  4301. this.GATHER_INTERVAL = 15000;
  4302. /**
  4303. * Log stats via the focus once every this many milliseconds.
  4304. */
  4305. this.LOG_INTERVAL = 60000;
  4306. /**
  4307. * Gather stats and store them in this.statsToBeLogged.
  4308. */
  4309. this.gatherStatsIntervalId = null;
  4310. /**
  4311. * Send the stats already saved in this.statsToBeLogged to be logged via
  4312. * the focus.
  4313. */
  4314. this.logStatsIntervalId = null;
  4315. /**
  4316. * Stores the statistics which will be send to the focus to be logged.
  4317. */
  4318. this.statsToBeLogged =
  4319. {
  4320. timestamps: [],
  4321. stats: {}
  4322. };
  4323. // Updates stats interval
  4324. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4325. this.statsIntervalId = null;
  4326. this.statsIntervalMilis = statsInterval;
  4327. // Map of ssrcs to PeerStats
  4328. this.ssrc2stats = {};
  4329. }
  4330. module.exports = StatsCollector;
  4331. /**
  4332. * Stops stats updates.
  4333. */
  4334. StatsCollector.prototype.stop = function () {
  4335. if (this.audioLevelsIntervalId) {
  4336. clearInterval(this.audioLevelsIntervalId);
  4337. this.audioLevelsIntervalId = null;
  4338. }
  4339. if (this.statsIntervalId)
  4340. {
  4341. clearInterval(this.statsIntervalId);
  4342. this.statsIntervalId = null;
  4343. }
  4344. if(this.logStatsIntervalId)
  4345. {
  4346. clearInterval(this.logStatsIntervalId);
  4347. this.logStatsIntervalId = null;
  4348. }
  4349. if(this.gatherStatsIntervalId)
  4350. {
  4351. clearInterval(this.gatherStatsIntervalId);
  4352. this.gatherStatsIntervalId = null;
  4353. }
  4354. };
  4355. /**
  4356. * Callback passed to <tt>getStats</tt> method.
  4357. * @param error an error that occurred on <tt>getStats</tt> call.
  4358. */
  4359. StatsCollector.prototype.errorCallback = function (error)
  4360. {
  4361. logger.error("Get stats error", error);
  4362. this.stop();
  4363. };
  4364. /**
  4365. * Starts stats updates.
  4366. */
  4367. StatsCollector.prototype.start = function ()
  4368. {
  4369. var self = this;
  4370. this.audioLevelsIntervalId = setInterval(
  4371. function () {
  4372. // Interval updates
  4373. self.peerconnection.getStats(
  4374. function (report) {
  4375. var results = null;
  4376. if (!report || !report.result ||
  4377. typeof report.result != 'function') {
  4378. results = report;
  4379. }
  4380. else {
  4381. results = report.result();
  4382. }
  4383. //logger.error("Got interval report", results);
  4384. self.currentAudioLevelsReport = results;
  4385. self.processAudioLevelReport();
  4386. self.baselineAudioLevelsReport =
  4387. self.currentAudioLevelsReport;
  4388. },
  4389. self.errorCallback
  4390. );
  4391. },
  4392. self.audioLevelsIntervalMilis
  4393. );
  4394. // if (!this.config.disableStats && browserSupported) {
  4395. // this.statsIntervalId = setInterval(
  4396. // function () {
  4397. // // Interval updates
  4398. // self.peerconnection.getStats(
  4399. // function (report) {
  4400. // var results = null;
  4401. // if (!report || !report.result ||
  4402. // typeof report.result != 'function') {
  4403. // //firefox
  4404. // results = report;
  4405. // }
  4406. // else {
  4407. // //chrome
  4408. // results = report.result();
  4409. // }
  4410. // //logger.error("Got interval report", results);
  4411. // self.currentStatsReport = results;
  4412. // try {
  4413. // self.processStatsReport();
  4414. // }
  4415. // catch (e) {
  4416. // logger.error("Unsupported key:" + e, e);
  4417. // }
  4418. //
  4419. // self.baselineStatsReport = self.currentStatsReport;
  4420. // },
  4421. // self.errorCallback
  4422. // );
  4423. // },
  4424. // self.statsIntervalMilis
  4425. // );
  4426. // }
  4427. //
  4428. // if (this.config.logStats && browserSupported) {
  4429. // this.gatherStatsIntervalId = setInterval(
  4430. // function () {
  4431. // self.peerconnection.getStats(
  4432. // function (report) {
  4433. // self.addStatsToBeLogged(report.result());
  4434. // },
  4435. // function () {
  4436. // }
  4437. // );
  4438. // },
  4439. // this.GATHER_INTERVAL
  4440. // );
  4441. //
  4442. // this.logStatsIntervalId = setInterval(
  4443. // function() { self.logStats(); },
  4444. // this.LOG_INTERVAL);
  4445. // }
  4446. };
  4447. /**
  4448. * Converts the stats to the format used for logging, and saves the data in
  4449. * this.statsToBeLogged.
  4450. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4451. */
  4452. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4453. var self = this;
  4454. var num_records = this.statsToBeLogged.timestamps.length;
  4455. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4456. reports.map(function (report) {
  4457. if (!acceptReport(report.id, report.type))
  4458. return;
  4459. var stat = self.statsToBeLogged.stats[report.id];
  4460. if (!stat) {
  4461. stat = self.statsToBeLogged.stats[report.id] = {};
  4462. }
  4463. stat.type = report.type;
  4464. report.names().map(function (name) {
  4465. if (!acceptStat(report.id, report.type, name))
  4466. return;
  4467. var values = stat[name];
  4468. if (!values) {
  4469. values = stat[name] = [];
  4470. }
  4471. while (values.length < num_records) {
  4472. values.push(null);
  4473. }
  4474. values.push(report.stat(name));
  4475. });
  4476. });
  4477. };
  4478. //FIXME:
  4479. //StatsCollector.prototype.logStats = function () {
  4480. //
  4481. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4482. // return;
  4483. // // Reset the stats
  4484. // this.statsToBeLogged.stats = {};
  4485. // this.statsToBeLogged.timestamps = [];
  4486. //};
  4487. /**
  4488. * Stats processing logic.
  4489. */
  4490. StatsCollector.prototype.processStatsReport = function () {
  4491. if (!this.baselineStatsReport) {
  4492. return;
  4493. }
  4494. for (var idx in this.currentStatsReport) {
  4495. var now = this.currentStatsReport[idx];
  4496. try {
  4497. if (getStatValue(now, 'receiveBandwidth') ||
  4498. getStatValue(now, 'sendBandwidth')) {
  4499. this.conferenceStats.bandwidth = {
  4500. "download": Math.round(
  4501. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4502. "upload": Math.round(
  4503. (getStatValue(now, 'sendBandwidth')) / 1000)
  4504. };
  4505. }
  4506. }
  4507. catch(e){/*not supported*/}
  4508. if(now.type == 'googCandidatePair')
  4509. {
  4510. var ip, type, localIP, active;
  4511. try {
  4512. ip = getStatValue(now, 'remoteAddress');
  4513. type = getStatValue(now, "transportType");
  4514. localIP = getStatValue(now, "localAddress");
  4515. active = getStatValue(now, "activeConnection");
  4516. }
  4517. catch(e){/*not supported*/}
  4518. if(!ip || !type || !localIP || active != "true")
  4519. continue;
  4520. var addressSaved = false;
  4521. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4522. {
  4523. if(this.conferenceStats.transport[i].ip == ip &&
  4524. this.conferenceStats.transport[i].type == type &&
  4525. this.conferenceStats.transport[i].localip == localIP)
  4526. {
  4527. addressSaved = true;
  4528. }
  4529. }
  4530. if(addressSaved)
  4531. continue;
  4532. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4533. continue;
  4534. }
  4535. if(now.type == "candidatepair")
  4536. {
  4537. if(now.state == "succeeded")
  4538. continue;
  4539. var local = this.currentStatsReport[now.localCandidateId];
  4540. var remote = this.currentStatsReport[now.remoteCandidateId];
  4541. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4542. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4543. }
  4544. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4545. now.type != "inboundrtp") {
  4546. continue;
  4547. }
  4548. var before = this.baselineStatsReport[idx];
  4549. if (!before) {
  4550. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4551. continue;
  4552. }
  4553. var ssrc = getStatValue(now, 'ssrc');
  4554. if(!ssrc)
  4555. continue;
  4556. var ssrcStats = this.ssrc2stats[ssrc];
  4557. if (!ssrcStats) {
  4558. ssrcStats = new PeerStats();
  4559. this.ssrc2stats[ssrc] = ssrcStats;
  4560. }
  4561. var isDownloadStream = true;
  4562. var key = 'packetsReceived';
  4563. var packetsNow = getStatValue(now, key);
  4564. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4565. isDownloadStream = false;
  4566. key = 'packetsSent';
  4567. packetsNow = getStatValue(now, key);
  4568. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4569. console.warn("No packetsReceived nor packetsSent stat found");
  4570. continue;
  4571. }
  4572. }
  4573. if (!packetsNow || packetsNow < 0)
  4574. packetsNow = 0;
  4575. var packetsBefore = getStatValue(before, key);
  4576. if (!packetsBefore || packetsBefore < 0)
  4577. packetsBefore = 0;
  4578. var packetRate = packetsNow - packetsBefore;
  4579. if (!packetRate || packetRate < 0)
  4580. packetRate = 0;
  4581. var currentLoss = getStatValue(now, 'packetsLost');
  4582. if (!currentLoss || currentLoss < 0)
  4583. currentLoss = 0;
  4584. var previousLoss = getStatValue(before, 'packetsLost');
  4585. if (!previousLoss || previousLoss < 0)
  4586. previousLoss = 0;
  4587. var lossRate = currentLoss - previousLoss;
  4588. if (!lossRate || lossRate < 0)
  4589. lossRate = 0;
  4590. var packetsTotal = (packetRate + lossRate);
  4591. ssrcStats.setSsrcLoss(ssrc,
  4592. {"packetsTotal": packetsTotal,
  4593. "packetsLost": lossRate,
  4594. "isDownloadStream": isDownloadStream});
  4595. var bytesReceived = 0, bytesSent = 0;
  4596. if(getStatValue(now, "bytesReceived")) {
  4597. bytesReceived = getStatValue(now, "bytesReceived") -
  4598. getStatValue(before, "bytesReceived");
  4599. }
  4600. if (getStatValue(now, "bytesSent")) {
  4601. bytesSent = getStatValue(now, "bytesSent") -
  4602. getStatValue(before, "bytesSent");
  4603. }
  4604. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4605. if (bytesReceived <= 0 || time <= 0) {
  4606. bytesReceived = 0;
  4607. } else {
  4608. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4609. }
  4610. if (bytesSent <= 0 || time <= 0) {
  4611. bytesSent = 0;
  4612. } else {
  4613. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4614. }
  4615. ssrcStats.setSsrcBitrate(ssrc, {
  4616. "download": bytesReceived,
  4617. "upload": bytesSent});
  4618. var resolution = {height: null, width: null};
  4619. try {
  4620. if (getStatValue(now, "googFrameHeightReceived") &&
  4621. getStatValue(now, "googFrameWidthReceived")) {
  4622. resolution.height =
  4623. getStatValue(now, "googFrameHeightReceived");
  4624. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4625. }
  4626. else if (getStatValue(now, "googFrameHeightSent") &&
  4627. getStatValue(now, "googFrameWidthSent")) {
  4628. resolution.height = getStatValue(now, "googFrameHeightSent");
  4629. resolution.width = getStatValue(now, "googFrameWidthSent");
  4630. }
  4631. }
  4632. catch(e){/*not supported*/}
  4633. if (resolution.height && resolution.width) {
  4634. ssrcStats.setSsrcResolution(ssrc, resolution);
  4635. } else {
  4636. ssrcStats.setSsrcResolution(ssrc, null);
  4637. }
  4638. }
  4639. var self = this;
  4640. // Jid stats
  4641. var totalPackets = {download: 0, upload: 0};
  4642. var lostPackets = {download: 0, upload: 0};
  4643. var bitrateDownload = 0;
  4644. var bitrateUpload = 0;
  4645. var resolutions = {};
  4646. Object.keys(this.ssrc2stats).forEach(
  4647. function (jid) {
  4648. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4649. function (ssrc) {
  4650. var type = "upload";
  4651. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4652. type = "download";
  4653. totalPackets[type] +=
  4654. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4655. lostPackets[type] +=
  4656. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4657. }
  4658. );
  4659. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4660. function (ssrc) {
  4661. bitrateDownload +=
  4662. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4663. bitrateUpload +=
  4664. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4665. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4666. }
  4667. );
  4668. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4669. }
  4670. );
  4671. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4672. this.conferenceStats.packetLoss = {
  4673. total:
  4674. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4675. totalPackets.download + totalPackets.upload),
  4676. download:
  4677. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4678. upload:
  4679. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4680. };
  4681. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  4682. {
  4683. "bitrate": this.conferenceStats.bitrate,
  4684. "packetLoss": this.conferenceStats.packetLoss,
  4685. "bandwidth": this.conferenceStats.bandwidth,
  4686. "resolution": resolutions,
  4687. "transport": this.conferenceStats.transport
  4688. });
  4689. this.conferenceStats.transport = [];
  4690. };
  4691. /**
  4692. * Stats processing logic.
  4693. */
  4694. StatsCollector.prototype.processAudioLevelReport = function () {
  4695. if (!this.baselineAudioLevelsReport) {
  4696. return;
  4697. }
  4698. for (var idx in this.currentAudioLevelsReport) {
  4699. var now = this.currentAudioLevelsReport[idx];
  4700. //if we don't have "packetsReceived" this is local stream
  4701. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4702. continue;
  4703. }
  4704. var before = this.baselineAudioLevelsReport[idx];
  4705. if (!before) {
  4706. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4707. continue;
  4708. }
  4709. var ssrc = getStatValue(now, 'ssrc');
  4710. if (!ssrc) {
  4711. if((Date.now() - now.timestamp) < 3000)
  4712. logger.warn("No ssrc: ");
  4713. continue;
  4714. }
  4715. var ssrcStats = this.ssrc2stats[ssrc];
  4716. if (!ssrcStats) {
  4717. ssrcStats = new PeerStats();
  4718. this.ssrc2stats[ssrc] = ssrcStats;
  4719. }
  4720. // Audio level
  4721. var audioLevel = null;
  4722. try {
  4723. audioLevel = getStatValue(now, 'audioInputLevel');
  4724. if (!audioLevel)
  4725. audioLevel = getStatValue(now, 'audioOutputLevel');
  4726. }
  4727. catch(e) {/*not supported*/
  4728. logger.warn("Audio Levels are not available in the statistics.");
  4729. clearInterval(this.audioLevelsIntervalId);
  4730. return;
  4731. }
  4732. if (audioLevel) {
  4733. // TODO: can't find specs about what this value really is,
  4734. // but it seems to vary between 0 and around 32k.
  4735. audioLevel = audioLevel / 32767;
  4736. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4737. this.eventEmitter.emit(
  4738. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  4739. }
  4740. }
  4741. };
  4742. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  4743. },{"../../service/statistics/Events":84,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],24:[function(require,module,exports){
  4744. /* global require, APP */
  4745. var LocalStats = require("./LocalStatsCollector.js");
  4746. var RTPStats = require("./RTPStatsCollector.js");
  4747. var EventEmitter = require("events");
  4748. var StatisticsEvents = require("../../service/statistics/Events");
  4749. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  4750. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4751. //var CallStats = require("./CallStats");
  4752. //var RTCEvents = require("../../service/RTC/RTCEvents");
  4753. //
  4754. //function onDisposeConference(onUnload) {
  4755. // CallStats.sendTerminateEvent();
  4756. // stopRemote();
  4757. // if(onUnload) {
  4758. // stopLocal();
  4759. // eventEmitter.removeAllListeners();
  4760. // }
  4761. //}
  4762. function Statistics() {
  4763. this.localStats = null;
  4764. this.rtpStats = null;
  4765. this.eventEmitter = new EventEmitter();
  4766. }
  4767. Statistics.prototype.startRemoteStats = function (peerconnection) {
  4768. if (this.rtpStats) {
  4769. this.rtpStats.stop();
  4770. }
  4771. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  4772. this.rtpStats.start();
  4773. }
  4774. Statistics.prototype.startLocalStats = function (stream) {
  4775. if(stream.getType() !== "audio")
  4776. return;
  4777. this.localStats = new LocalStats(stream.getOriginalStream(), 200, this,
  4778. this.eventEmitter);
  4779. this.localStats.start();
  4780. }
  4781. Statistics.prototype.addAudioLevelListener = function(listener)
  4782. {
  4783. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  4784. }
  4785. Statistics.prototype.removeAudioLevelListener = function(listener)
  4786. {
  4787. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  4788. }
  4789. Statistics.prototype.dispose = function () {
  4790. this.stopLocal();
  4791. this.stopRemote();
  4792. if(this.eventEmitter)
  4793. {
  4794. this.eventEmitter.removeAllListeners();
  4795. }
  4796. }
  4797. Statistics.prototype.stopLocal = function () {
  4798. if (this.localStats) {
  4799. this.localStats.stop();
  4800. this.localStats = null;
  4801. }
  4802. }
  4803. Statistics.prototype.stopRemote = function () {
  4804. if (this.rtpStats) {
  4805. this.rtpStats.stop();
  4806. this.eventEmitter.emit(StatisticsEvents.STOP);
  4807. this.rtpStats = null;
  4808. }
  4809. }
  4810. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  4811. //
  4812. //var statistics = {
  4813. // /**
  4814. // * Indicates that this audio level is for local jid.
  4815. // * @type {string}
  4816. // */
  4817. // LOCAL_JID: 'local',
  4818. //
  4819. // addConnectionStatsListener: function(listener)
  4820. // {
  4821. // eventEmitter.on("statistics.connectionstats", listener);
  4822. // },
  4823. //
  4824. // removeConnectionStatsListener: function(listener)
  4825. // {
  4826. // eventEmitter.removeListener("statistics.connectionstats", listener);
  4827. // },
  4828. //
  4829. //
  4830. // addRemoteStatsStopListener: function(listener)
  4831. // {
  4832. // eventEmitter.on("statistics.stop", listener);
  4833. // },
  4834. //
  4835. // removeRemoteStatsStopListener: function(listener)
  4836. // {
  4837. // eventEmitter.removeListener("statistics.stop", listener);
  4838. // },
  4839. //
  4840. //
  4841. // stopRemoteStatistics: function()
  4842. // {
  4843. // stopRemote();
  4844. // },
  4845. //
  4846. //// Already implemented with the constructor
  4847. // start: function () {
  4848. // APP.RTC.addStreamListener(onStreamCreated,
  4849. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  4850. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  4851. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  4852. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  4853. // startRemoteStats(event.peerconnection);
  4854. //// CallStats.init(event);
  4855. // });
  4856. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  4857. //// CallStats.init(session);
  4858. //// });
  4859. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4860. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  4861. //// CallStats.sendMuteEvent(mute, "audio");
  4862. //// });
  4863. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  4864. //// CallStats.sendSetupFailedEvent();
  4865. //// });
  4866. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4867. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  4868. //// CallStats.sendMuteEvent(mute, "video");
  4869. //// });
  4870. // }
  4871. //};
  4872. module.exports = Statistics;
  4873. },{"../../service/statistics/Events":84,"../../service/statistics/constants":85,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":43}],25:[function(require,module,exports){
  4874. /**
  4875. /**
  4876. * @const
  4877. */
  4878. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  4879. /**
  4880. * Hexadecimal digits.
  4881. * @const
  4882. */
  4883. var HEX_DIGITS = '0123456789abcdef';
  4884. /**
  4885. * Generates random int within the range [min, max]
  4886. * @param min the minimum value for the generated number
  4887. * @param max the maximum value for the generated number
  4888. * @returns random int number
  4889. */
  4890. function randomInt(min, max) {
  4891. return Math.floor(Math.random() * (max - min + 1)) + min;
  4892. }
  4893. /**
  4894. * Get random element from array or string.
  4895. * @param {Array|string} arr source
  4896. * @returns array element or string character
  4897. */
  4898. function randomElement(arr) {
  4899. return arr[randomInt(0, arr.length - 1)];
  4900. }
  4901. /**
  4902. * Generate random alphanumeric string.
  4903. * @param {number} length expected string length
  4904. * @returns {string} random string of specified length
  4905. */
  4906. function randomAlphanumStr(length) {
  4907. var result = '';
  4908. for (var i = 0; i < length; i += 1) {
  4909. result += randomElement(ALPHANUM);
  4910. }
  4911. return result;
  4912. }
  4913. /**
  4914. * Exported interface.
  4915. */
  4916. var RandomUtil = {
  4917. /**
  4918. * Returns a random hex digit.
  4919. * @returns {*}
  4920. */
  4921. randomHexDigit: function() {
  4922. return randomElement(HEX_DIGITS);
  4923. },
  4924. /**
  4925. * Returns a random string of hex digits with length 'len'.
  4926. * @param len the length.
  4927. */
  4928. randomHexString: function (len) {
  4929. var ret = '';
  4930. while (len--) {
  4931. ret += this.randomHexDigit();
  4932. }
  4933. return ret;
  4934. },
  4935. randomElement: randomElement,
  4936. randomAlphanumStr: randomAlphanumStr
  4937. };
  4938. module.exports = RandomUtil;
  4939. },{}],26:[function(require,module,exports){
  4940. (function (__filename){
  4941. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4942. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4943. var Moderator = require("./moderator");
  4944. var EventEmitter = require("events");
  4945. var parser = {
  4946. packet2JSON: function (packet, nodes) {
  4947. var self = this;
  4948. $(packet).children().each(function (index) {
  4949. var tagName = $(this).prop("tagName");
  4950. var node = {}
  4951. node["tagName"] = tagName;
  4952. node.attributes = {};
  4953. $($(this)[0].attributes).each(function( index, attr ) {
  4954. node.attributes[ attr.name ] = attr.value;
  4955. } );
  4956. var text = Strophe.getText($(this)[0]);
  4957. if(text)
  4958. node.value = text;
  4959. node.children = [];
  4960. nodes.push(node);
  4961. self.packet2JSON($(this), node.children);
  4962. })
  4963. },
  4964. JSON2packet: function (nodes, packet) {
  4965. for(var i = 0; i < nodes.length; i++)
  4966. {
  4967. var node = nodes[i];
  4968. if(!node || node === null){
  4969. continue;
  4970. }
  4971. packet.c(node.tagName, node.attributes);
  4972. if(node.value)
  4973. packet.t(node.value);
  4974. if(node.children)
  4975. this.JSON2packet(node.children, packet);
  4976. packet.up();
  4977. }
  4978. // packet.up();
  4979. }
  4980. };
  4981. /**
  4982. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  4983. * @param pres the presence JSON
  4984. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  4985. */
  4986. function filterNodeFromPresenceJSON(pres, nodeName){
  4987. var res = [];
  4988. for(var i = 0; i < pres.length; i++)
  4989. if(pres[i].tagName === nodeName)
  4990. res.push(pres[i]);
  4991. return res;
  4992. }
  4993. function ChatRoom(connection, jid, password, XMPP, options) {
  4994. this.eventEmitter = new EventEmitter();
  4995. this.xmpp = XMPP;
  4996. this.connection = connection;
  4997. this.roomjid = Strophe.getBareJidFromJid(jid);
  4998. this.myroomjid = jid;
  4999. this.password = password;
  5000. logger.info("Joined MUC as " + this.myroomjid);
  5001. this.members = {};
  5002. this.presMap = {};
  5003. this.presHandlers = {};
  5004. this.joined = false;
  5005. this.role = null;
  5006. this.focusMucJid = null;
  5007. this.bridgeIsDown = false;
  5008. this.options = options || {};
  5009. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5010. this.initPresenceMap();
  5011. this.session = null;
  5012. var self = this;
  5013. this.lastPresences = {};
  5014. }
  5015. ChatRoom.prototype.initPresenceMap = function () {
  5016. this.presMap['to'] = this.myroomjid;
  5017. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5018. this.presMap["nodes"] = [];
  5019. this.presMap["nodes"].push( {
  5020. "tagName": "user-agent",
  5021. "value": navigator.userAgent,
  5022. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5023. });
  5024. };
  5025. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5026. this.presMap["nodes"].push( {
  5027. "tagName": "devices",
  5028. "children": [
  5029. {
  5030. "tagName": "audio",
  5031. "value": devices.audio,
  5032. },
  5033. {
  5034. "tagName": "video",
  5035. "value": devices.video,
  5036. }
  5037. ]
  5038. });
  5039. }
  5040. ChatRoom.prototype.join = function (password, tokenPassword) {
  5041. if(password)
  5042. this.password = password;
  5043. var self = this;
  5044. this.moderator.allocateConferenceFocus(function()
  5045. {
  5046. self.sendPresence(tokenPassword);
  5047. }.bind(this));
  5048. };
  5049. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  5050. if (!this.presMap['to']) {
  5051. // Too early to send presence - not initialized
  5052. return;
  5053. }
  5054. var pres = $pres({to: this.presMap['to'] });
  5055. pres.c('x', {xmlns: this.presMap['xns']});
  5056. if (this.password) {
  5057. pres.c('password').t(this.password).up();
  5058. }
  5059. pres.up();
  5060. // Send XEP-0115 'c' stanza that contains our capabilities info
  5061. if (this.connection.caps) {
  5062. this.connection.caps.node = this.xmpp.options.clientNode;
  5063. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5064. }
  5065. if (tokenPassword) {
  5066. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  5067. .t(tokenPassword).up();
  5068. }
  5069. parser.JSON2packet(this.presMap.nodes, pres);
  5070. this.connection.send(pres);
  5071. };
  5072. ChatRoom.prototype.doLeave = function () {
  5073. logger.log("do leave", this.myroomjid);
  5074. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5075. this.presMap.length = 0;
  5076. this.connection.send(pres);
  5077. };
  5078. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5079. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5080. var getForm = $iq({type: 'get', to: this.roomjid})
  5081. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5082. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5083. var self = this;
  5084. this.connection.sendIQ(getForm, function (form) {
  5085. if (!$(form).find(
  5086. '>query>x[xmlns="jabber:x:data"]' +
  5087. '>field[var="muc#roomconfig_whois"]').length) {
  5088. logger.error('non-anonymous rooms not supported');
  5089. return;
  5090. }
  5091. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5092. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5093. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5094. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5095. .c('value')
  5096. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5097. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5098. .c('value').t('anyone').up().up();
  5099. self.connection.sendIQ(formSubmit);
  5100. }, function (error) {
  5101. logger.error("Error getting room configuration form");
  5102. });
  5103. };
  5104. ChatRoom.prototype.onPresence = function (pres) {
  5105. var from = pres.getAttribute('from');
  5106. // Parse roles.
  5107. var member = {};
  5108. member.show = $(pres).find('>show').text();
  5109. member.status = $(pres).find('>status').text();
  5110. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5111. member.affiliation = tmp.attr('affiliation');
  5112. member.role = tmp.attr('role');
  5113. // Focus recognition
  5114. member.jid = tmp.attr('jid');
  5115. member.isFocus = false;
  5116. if (member.jid
  5117. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  5118. member.isFocus = true;
  5119. }
  5120. $(pres).find(">x").remove();
  5121. var nodes = [];
  5122. parser.packet2JSON(pres, nodes);
  5123. this.lastPresences[from] = nodes;
  5124. for(var i = 0; i < nodes.length; i++)
  5125. {
  5126. var node = nodes[i];
  5127. switch(node.tagName)
  5128. {
  5129. case "nick":
  5130. member.nick = node.value;
  5131. if(!member.isFocus) {
  5132. var displayName = !this.xmpp.options.displayJids
  5133. ? member.nick : Strophe.getResourceFromJid(from);
  5134. if (displayName && displayName.length > 0) {
  5135. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5136. }
  5137. logger.info("Display name: " + displayName, pres);
  5138. }
  5139. break;
  5140. case "userId":
  5141. member.id = node.value;
  5142. break;
  5143. case "email":
  5144. member.email = node.value;
  5145. break;
  5146. case "bridgeIsDown":
  5147. if(!this.bridgeIsDown) {
  5148. this.bridgeIsDown = true;
  5149. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5150. }
  5151. break;
  5152. default :
  5153. this.processNode(node, from);
  5154. }
  5155. }
  5156. if (from == this.myroomjid) {
  5157. if (member.affiliation == 'owner')
  5158. if (this.role !== member.role) {
  5159. this.role = member.role;
  5160. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  5161. member, this.isModerator());
  5162. }
  5163. if (!this.joined) {
  5164. this.joined = true;
  5165. console.log("(TIME) MUC joined:\t", window.performance.now());
  5166. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  5167. }
  5168. } else if (this.members[from] === undefined) {
  5169. // new participant
  5170. this.members[from] = member;
  5171. logger.log('entered', from, member);
  5172. if (member.isFocus) {
  5173. this.focusMucJid = from;
  5174. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5175. }
  5176. else {
  5177. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  5178. }
  5179. } else {
  5180. // Presence update for existing participant
  5181. // Watch role change:
  5182. if (this.members[from].role != member.role) {
  5183. this.members[from].role = member.role;
  5184. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  5185. member.role, member.nick);
  5186. }
  5187. // store the new display name
  5188. if(member.displayName)
  5189. this.members[from].displayName = member.displayName;
  5190. }
  5191. if(!member.isFocus)
  5192. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  5193. // Trigger status message update
  5194. if (member.status) {
  5195. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5196. }
  5197. };
  5198. ChatRoom.prototype.processNode = function (node, from) {
  5199. if(this.presHandlers[node.tagName])
  5200. this.presHandlers[node.tagName](node, from);
  5201. };
  5202. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5203. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5204. msg.c('body', body).up();
  5205. if (nickname) {
  5206. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5207. }
  5208. this.connection.send(msg);
  5209. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5210. };
  5211. ChatRoom.prototype.setSubject = function (subject) {
  5212. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5213. msg.c('subject', subject);
  5214. this.connection.send(msg);
  5215. logger.log("topic changed to " + subject);
  5216. };
  5217. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5218. delete this.lastPresences[jid];
  5219. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5220. this.moderator.onMucMemberLeft(jid);
  5221. };
  5222. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5223. // room destroyed ?
  5224. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5225. '>destroy').length) {
  5226. var reason;
  5227. var reasonSelect = $(pres).find(
  5228. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5229. '>destroy>reason');
  5230. if (reasonSelect.length) {
  5231. reason = reasonSelect.text();
  5232. }
  5233. this.xmpp.disposeConference(false);
  5234. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5235. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  5236. return true;
  5237. }
  5238. // Status code 110 indicates that this notification is "self-presence".
  5239. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5240. delete this.members[from];
  5241. this.onParticipantLeft(from);
  5242. }
  5243. // If the status code is 110 this means we're leaving and we would like
  5244. // to remove everyone else from our view, so we trigger the event.
  5245. else if (Object.keys(this.members).length > 1) {
  5246. for (var i in this.members) {
  5247. var member = this.members[i];
  5248. delete this.members[i];
  5249. this.onParticipantLeft(member);
  5250. }
  5251. }
  5252. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5253. if (this.myroomjid === from) {
  5254. this.xmpp.disposeConference(false);
  5255. this.eventEmitter.emit(XMPPEvents.KICKED);
  5256. }
  5257. }
  5258. };
  5259. ChatRoom.prototype.onMessage = function (msg, from) {
  5260. var nick =
  5261. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5262. .text() ||
  5263. Strophe.getResourceFromJid(from);
  5264. var txt = $(msg).find('>body').text();
  5265. var type = msg.getAttribute("type");
  5266. if (type == "error") {
  5267. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5268. $(msg).find('>text').text(), txt);
  5269. return true;
  5270. }
  5271. var subject = $(msg).find('>subject');
  5272. if (subject.length) {
  5273. var subjectText = subject.text();
  5274. if (subjectText || subjectText == "") {
  5275. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5276. logger.log("Subject is changed to " + subjectText);
  5277. }
  5278. }
  5279. // xep-0203 delay
  5280. var stamp = $(msg).find('>delay').attr('stamp');
  5281. if (!stamp) {
  5282. // or xep-0091 delay, UTC timestamp
  5283. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5284. if (stamp) {
  5285. // the format is CCYYMMDDThh:mm:ss
  5286. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5287. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5288. }
  5289. }
  5290. if (txt) {
  5291. logger.log('chat', nick, txt);
  5292. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5293. from, nick, txt, this.myroomjid, stamp);
  5294. }
  5295. }
  5296. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5297. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5298. logger.log('on password required', from);
  5299. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5300. } else if ($(pres).find(
  5301. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5302. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5303. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5304. // enter the room by replying with 'not-authorized'. This would
  5305. // result in reconnection from authorized domain.
  5306. // We're either missing Jicofo/Prosody config for anonymous
  5307. // domains or something is wrong.
  5308. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5309. } else {
  5310. logger.warn('onPresError ', pres);
  5311. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5312. }
  5313. } else {
  5314. logger.warn('onPresError ', pres);
  5315. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5316. }
  5317. };
  5318. ChatRoom.prototype.kick = function (jid) {
  5319. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5320. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5321. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5322. .c('reason').t('You have been kicked.').up().up().up();
  5323. this.connection.sendIQ(
  5324. kickIQ,
  5325. function (result) {
  5326. logger.log('Kick participant with jid: ', jid, result);
  5327. },
  5328. function (error) {
  5329. logger.log('Kick participant error: ', error);
  5330. });
  5331. };
  5332. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5333. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5334. var ob = this;
  5335. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5336. function (res) {
  5337. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5338. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5339. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5340. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5341. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5342. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5343. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5344. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5345. ob.connection.sendIQ(formsubmit,
  5346. onSuccess,
  5347. onError);
  5348. } else {
  5349. onNotSupported();
  5350. }
  5351. }, onError);
  5352. };
  5353. ChatRoom.prototype.addToPresence = function (key, values) {
  5354. values.tagName = key;
  5355. this.presMap["nodes"].push(values);
  5356. };
  5357. ChatRoom.prototype.removeFromPresence = function (key) {
  5358. for(var i = 0; i < this.presMap.nodes.length; i++)
  5359. {
  5360. if(key === this.presMap.nodes[i].tagName)
  5361. this.presMap.nodes.splice(i, 1);
  5362. }
  5363. };
  5364. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5365. this.presHandlers[name] = handler;
  5366. }
  5367. ChatRoom.prototype.removePresenceListener = function (name) {
  5368. delete this.presHandlers[name];
  5369. }
  5370. ChatRoom.prototype.isModerator = function (jid) {
  5371. return this.role === 'moderator';
  5372. };
  5373. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5374. if (this.members[peerJid]) {
  5375. return this.members[peerJid].role;
  5376. }
  5377. return null;
  5378. };
  5379. ChatRoom.prototype.setJingleSession = function(session){
  5380. this.session = session;
  5381. this.session.room = this;
  5382. };
  5383. ChatRoom.prototype.removeStream = function (stream) {
  5384. if(!this.session)
  5385. return;
  5386. this.session.peerconnection.removeStream(stream)
  5387. }
  5388. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5389. if(this.session) {
  5390. // FIXME: will block switchInProgress on true value in case of exception
  5391. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5392. } else {
  5393. // We are done immediately
  5394. logger.warn("No conference handler or conference not started yet");
  5395. callback();
  5396. }
  5397. };
  5398. ChatRoom.prototype.addStream = function (stream, callback) {
  5399. if(this.session) {
  5400. // FIXME: will block switchInProgress on true value in case of exception
  5401. this.session.addStream(stream, callback);
  5402. } else {
  5403. // We are done immediately
  5404. logger.warn("No conference handler or conference not started yet");
  5405. callback();
  5406. }
  5407. }
  5408. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5409. var self = this;
  5410. var localCallback = function (mute) {
  5411. self.sendVideoInfoPresence(mute);
  5412. if(callback)
  5413. callback(mute)
  5414. };
  5415. if(this.session)
  5416. {
  5417. this.session.setVideoMute(
  5418. mute, localCallback, options);
  5419. }
  5420. else {
  5421. localCallback(mute);
  5422. }
  5423. };
  5424. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5425. //This will be for remote streams only
  5426. // if (this.forceMuted && !mute) {
  5427. // logger.info("Asking focus for unmute");
  5428. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5429. // // FIXME: wait for result before resetting muted status
  5430. // this.forceMuted = false;
  5431. // }
  5432. return this.sendAudioInfoPresence(mute, callback);
  5433. };
  5434. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5435. this.removeFromPresence("audiomuted");
  5436. this.addToPresence("audiomuted",
  5437. {attributes:
  5438. {"audions": "http://jitsi.org/jitmeet/audio"},
  5439. value: mute.toString()});
  5440. }
  5441. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5442. this.addAudioInfoToPresence(mute);
  5443. if(this.connection) {
  5444. this.sendPresence();
  5445. }
  5446. if(callback)
  5447. callback();
  5448. };
  5449. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5450. this.removeFromPresence("videomuted");
  5451. this.addToPresence("videomuted",
  5452. {attributes:
  5453. {"videons": "http://jitsi.org/jitmeet/video"},
  5454. value: mute.toString()});
  5455. }
  5456. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5457. this.addVideoInfoToPresence(mute);
  5458. if(!this.connection)
  5459. return;
  5460. this.sendPresence();
  5461. };
  5462. ChatRoom.prototype.addListener = function(type, listener) {
  5463. this.eventEmitter.on(type, listener);
  5464. };
  5465. ChatRoom.prototype.removeListener = function (type, listener) {
  5466. this.eventEmitter.removeListener(type, listener);
  5467. };
  5468. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5469. if(this.lastPresences[data.peerjid])
  5470. {
  5471. var pres = this.lastPresences[data.peerjid];
  5472. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5473. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5474. data.videomuted = ((videomuted.length > 0
  5475. && videomuted[0]
  5476. && videomuted[0]["value"] === "true")? true : false);
  5477. data.audiomuted = ((audiomuted.length > 0
  5478. && audiomuted[0]
  5479. && audiomuted[0]["value"] === "true")? true : false);
  5480. }
  5481. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5482. }
  5483. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5484. if (!this.session)
  5485. return null;
  5486. return this.session.getSsrcOwner(ssrc);
  5487. };
  5488. module.exports = ChatRoom;
  5489. }).call(this,"/modules/xmpp/ChatRoom.js")
  5490. },{"../../service/xmpp/XMPPEvents":86,"./moderator":34,"events":43,"jitsi-meet-logger":47}],27:[function(require,module,exports){
  5491. (function (__filename){
  5492. /*
  5493. * JingleSession provides an API to manage a single Jingle session. We will
  5494. * have different implementations depending on the underlying interface used
  5495. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  5496. */
  5497. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5498. function JingleSession(me, sid, connection, service, eventEmitter) {
  5499. /**
  5500. * Our JID.
  5501. */
  5502. this.me = me;
  5503. /**
  5504. * The Jingle session identifier.
  5505. */
  5506. this.sid = sid;
  5507. /**
  5508. * The XMPP connection.
  5509. */
  5510. this.connection = connection;
  5511. /**
  5512. * The XMPP service.
  5513. */
  5514. this.service = service;
  5515. /**
  5516. * The event emitter.
  5517. */
  5518. this.eventEmitter = eventEmitter;
  5519. /**
  5520. * Whether to use dripping or not. Dripping is sending trickle candidates
  5521. * not one-by-one.
  5522. * Note: currently we do not support 'false'.
  5523. */
  5524. this.usedrip = true;
  5525. /**
  5526. * When dripping is used, stores ICE candidates which are to be sent.
  5527. */
  5528. this.drip_container = [];
  5529. // Media constraints. Is this WebRTC only?
  5530. this.media_constraints = null;
  5531. // ICE servers config (RTCConfiguration?).
  5532. this.ice_config = {};
  5533. // The chat room instance associated with the session.
  5534. this.room = null;
  5535. }
  5536. /**
  5537. * Prepares this object to initiate a session.
  5538. * @param peerjid the JID of the remote peer.
  5539. * @param isInitiator whether we will be the Jingle initiator.
  5540. * @param media_constraints
  5541. * @param ice_config
  5542. */
  5543. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5544. media_constraints, ice_config) {
  5545. this.media_constraints = media_constraints;
  5546. this.ice_config = ice_config;
  5547. if (this.state !== null) {
  5548. logger.error('attempt to initiate on session ' + this.sid +
  5549. 'in state ' + this.state);
  5550. return;
  5551. }
  5552. this.state = 'pending';
  5553. this.initiator = isInitiator ? this.me : peerjid;
  5554. this.responder = !isInitiator ? this.me : peerjid;
  5555. this.peerjid = peerjid;
  5556. this.doInitialize();
  5557. };
  5558. /**
  5559. * Finishes initialization.
  5560. */
  5561. JingleSession.prototype.doInitialize = function() {};
  5562. /**
  5563. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5564. * Note: currently only used on transport-info
  5565. */
  5566. JingleSession.prototype.addIceCandidates = function(contents) {};
  5567. /**
  5568. * Handles an 'add-source' event.
  5569. *
  5570. * @param contents an array of Jingle 'content' elements.
  5571. */
  5572. JingleSession.prototype.addSources = function(contents) {};
  5573. /**
  5574. * Handles a 'remove-source' event.
  5575. *
  5576. * @param contents an array of Jingle 'content' elements.
  5577. */
  5578. JingleSession.prototype.removeSources = function(contents) {};
  5579. /**
  5580. * Terminates this Jingle session (stops sending media and closes the streams?)
  5581. */
  5582. JingleSession.prototype.terminate = function() {};
  5583. /**
  5584. * Sends a Jingle session-terminate message to the peer and terminates the
  5585. * session.
  5586. * @param reason
  5587. * @param text
  5588. */
  5589. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5590. /**
  5591. * Handles an offer from the remote peer (prepares to accept a session).
  5592. * @param jingle the 'jingle' XML element.
  5593. */
  5594. JingleSession.prototype.setOffer = function(jingle) {};
  5595. /**
  5596. * Handles an answer from the remote peer (prepares to accept a session).
  5597. * @param jingle the 'jingle' XML element.
  5598. */
  5599. JingleSession.prototype.setAnswer = function(jingle) {};
  5600. module.exports = JingleSession;
  5601. }).call(this,"/modules/xmpp/JingleSession.js")
  5602. },{"jitsi-meet-logger":47}],28:[function(require,module,exports){
  5603. (function (__filename){
  5604. /* jshint -W117 */
  5605. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5606. var JingleSession = require("./JingleSession");
  5607. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5608. var SDPDiffer = require("./SDPDiffer");
  5609. var SDPUtil = require("./SDPUtil");
  5610. var SDP = require("./SDP");
  5611. var async = require("async");
  5612. var transform = require("sdp-transform");
  5613. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5614. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5615. var SSRCReplacement = require("./LocalSSRCReplacement");
  5616. var RTC = require("../RTC/RTC");
  5617. // Jingle stuff
  5618. function JingleSessionPC(me, sid, connection, service) {
  5619. JingleSession.call(this, me, sid, connection, service);
  5620. this.initiator = null;
  5621. this.responder = null;
  5622. this.peerjid = null;
  5623. this.state = null;
  5624. this.localSDP = null;
  5625. this.remoteSDP = null;
  5626. this.relayedStreams = [];
  5627. this.usetrickle = true;
  5628. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5629. this.hadstuncandidate = false;
  5630. this.hadturncandidate = false;
  5631. this.lasticecandidate = false;
  5632. this.statsinterval = null;
  5633. this.reason = null;
  5634. this.addssrc = [];
  5635. this.removessrc = [];
  5636. this.pendingop = null;
  5637. this.switchstreams = false;
  5638. this.addingStreams = false;
  5639. this.wait = true;
  5640. this.localStreamsSSRC = null;
  5641. this.ssrcOwners = {};
  5642. this.ssrcVideoTypes = {};
  5643. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  5644. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  5645. /**
  5646. * The indicator which determines whether the (local) video has been muted
  5647. * in response to a user command in contrast to an automatic decision made
  5648. * by the application logic.
  5649. */
  5650. this.videoMuteByUser = false;
  5651. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5652. // We start with the queue paused. We resume it when the signaling state is
  5653. // stable and the ice connection state is connected.
  5654. this.modifySourcesQueue.pause();
  5655. }
  5656. //XXX this is badly broken...
  5657. JingleSessionPC.prototype = JingleSession.prototype;
  5658. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5659. JingleSessionPC.prototype.setOffer = function(offer) {
  5660. this.setRemoteDescription(offer, 'offer');
  5661. };
  5662. JingleSessionPC.prototype.setAnswer = function(answer) {
  5663. this.setRemoteDescription(answer, 'answer');
  5664. };
  5665. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5666. var signalingState = this.peerconnection.signalingState;
  5667. var iceConnectionState = this.peerconnection.iceConnectionState;
  5668. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5669. this.modifySourcesQueue.resume();
  5670. } else {
  5671. this.modifySourcesQueue.pause();
  5672. }
  5673. };
  5674. JingleSessionPC.prototype.doInitialize = function () {
  5675. var self = this;
  5676. this.hadstuncandidate = false;
  5677. this.hadturncandidate = false;
  5678. this.lasticecandidate = false;
  5679. // True if reconnect is in progress
  5680. this.isreconnect = false;
  5681. // Set to true if the connection was ever stable
  5682. this.wasstable = false;
  5683. this.peerconnection = new TraceablePeerConnection(
  5684. this.connection.jingle.ice_config,
  5685. RTC.getPCConstraints(),
  5686. this);
  5687. this.peerconnection.onicecandidate = function (event) {
  5688. var protocol;
  5689. if (event && event.candidate) {
  5690. protocol = (typeof event.candidate.protocol === 'string')
  5691. ? event.candidate.protocol.toLowerCase() : '';
  5692. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  5693. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  5694. return;
  5695. }
  5696. }
  5697. self.sendIceCandidate(event.candidate);
  5698. };
  5699. this.peerconnection.onaddstream = function (event) {
  5700. if (event.stream.id !== 'default') {
  5701. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  5702. self.remoteStreamAdded(event);
  5703. } else {
  5704. // This is a recvonly stream. Clients that implement Unified Plan,
  5705. // such as Firefox use recvonly "streams/channels/tracks" for
  5706. // receiving remote stream/tracks, as opposed to Plan B where there
  5707. // are only 3 channels: audio, video and data.
  5708. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  5709. }
  5710. };
  5711. this.peerconnection.onremovestream = function (event) {
  5712. // Remove the stream from remoteStreams
  5713. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  5714. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  5715. };
  5716. this.peerconnection.onsignalingstatechange = function (event) {
  5717. if (!(self && self.peerconnection)) return;
  5718. if (self.peerconnection.signalingState === 'stable') {
  5719. self.wasstable = true;
  5720. }
  5721. self.updateModifySourcesQueue();
  5722. };
  5723. /**
  5724. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  5725. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  5726. * RTCPeerConnection.iceConnectionState changes.
  5727. *
  5728. * @param event the event containing information about the change
  5729. */
  5730. this.peerconnection.oniceconnectionstatechange = function (event) {
  5731. if (!(self && self.peerconnection)) return;
  5732. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  5733. ":\t", window.performance.now());
  5734. self.updateModifySourcesQueue();
  5735. switch (self.peerconnection.iceConnectionState) {
  5736. case 'connected':
  5737. // Informs interested parties that the connection has been restored.
  5738. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  5739. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  5740. self.isreconnect = false;
  5741. break;
  5742. case 'disconnected':
  5743. self.isreconnect = true;
  5744. // Informs interested parties that the connection has been interrupted.
  5745. if (self.wasstable)
  5746. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  5747. break;
  5748. case 'failed':
  5749. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5750. break;
  5751. }
  5752. onIceConnectionStateChange(self.sid, self);
  5753. };
  5754. this.peerconnection.onnegotiationneeded = function (event) {
  5755. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  5756. };
  5757. this.relayedStreams.forEach(function(stream) {
  5758. self.peerconnection.addStream(stream);
  5759. });
  5760. };
  5761. function onIceConnectionStateChange(sid, session) {
  5762. switch (session.peerconnection.iceConnectionState) {
  5763. case 'checking':
  5764. session.timeChecking = (new Date()).getTime();
  5765. session.firstconnect = true;
  5766. break;
  5767. case 'completed': // on caller side
  5768. case 'connected':
  5769. if (session.firstconnect) {
  5770. session.firstconnect = false;
  5771. var metadata = {};
  5772. metadata.setupTime
  5773. = (new Date()).getTime() - session.timeChecking;
  5774. session.peerconnection.getStats(function (res) {
  5775. if(res && res.result) {
  5776. res.result().forEach(function (report) {
  5777. if (report.type == 'googCandidatePair' &&
  5778. report.stat('googActiveConnection') == 'true') {
  5779. metadata.localCandidateType
  5780. = report.stat('googLocalCandidateType');
  5781. metadata.remoteCandidateType
  5782. = report.stat('googRemoteCandidateType');
  5783. // log pair as well so we can get nice pie
  5784. // charts
  5785. metadata.candidatePair
  5786. = report.stat('googLocalCandidateType') +
  5787. ';' +
  5788. report.stat('googRemoteCandidateType');
  5789. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  5790. {
  5791. metadata.ipv6 = true;
  5792. }
  5793. }
  5794. });
  5795. }
  5796. });
  5797. }
  5798. break;
  5799. }
  5800. }
  5801. JingleSessionPC.prototype.accept = function () {
  5802. this.state = 'active';
  5803. var pranswer = this.peerconnection.localDescription;
  5804. if (!pranswer || pranswer.type != 'pranswer') {
  5805. return;
  5806. }
  5807. logger.log('going from pranswer to answer');
  5808. if (this.usetrickle) {
  5809. // remove candidates already sent from session-accept
  5810. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  5811. for (var i = 0; i < lines.length; i++) {
  5812. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  5813. }
  5814. }
  5815. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  5816. // FIXME: change any inactive to sendrecv or whatever they were originally
  5817. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  5818. }
  5819. var prsdp = new SDP(pranswer.sdp);
  5820. if (self.webrtcIceTcpDisable) {
  5821. prsdp.removeTcpCandidates = true;
  5822. }
  5823. if (self.webrtcIceUdpDisable) {
  5824. prsdp.removeUdpCandidates = true;
  5825. }
  5826. var accept = $iq({to: this.peerjid,
  5827. type: 'set'})
  5828. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5829. action: 'session-accept',
  5830. initiator: this.initiator,
  5831. responder: this.responder,
  5832. sid: this.sid });
  5833. // FIXME why do we generate session-accept in 3 different places ?
  5834. prsdp.toJingle(
  5835. accept,
  5836. this.initiator == this.me ? 'initiator' : 'responder',
  5837. this.localStreamsSSRC);
  5838. var sdp = this.peerconnection.localDescription.sdp;
  5839. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  5840. // FIXME: change any inactive to sendrecv or whatever they were originally
  5841. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  5842. }
  5843. var self = this;
  5844. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  5845. function () {
  5846. //logger.log('setLocalDescription success');
  5847. self.setLocalDescription();
  5848. SSRCReplacement.processSessionInit(accept);
  5849. self.connection.sendIQ(accept,
  5850. function () {
  5851. var ack = {};
  5852. ack.source = 'answer';
  5853. $(document).trigger('ack.jingle', [self.sid, ack]);
  5854. },
  5855. function (stanza) {
  5856. var error = ($(stanza).find('error').length) ? {
  5857. code: $(stanza).find('error').attr('code'),
  5858. reason: $(stanza).find('error :first')[0].tagName
  5859. }:{};
  5860. error.source = 'answer';
  5861. JingleSessionPC.onJingleError(self.sid, error);
  5862. },
  5863. 10000);
  5864. },
  5865. function (e) {
  5866. logger.error('setLocalDescription failed', e);
  5867. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5868. }
  5869. );
  5870. };
  5871. JingleSessionPC.prototype.terminate = function (reason) {
  5872. this.state = 'ended';
  5873. this.reason = reason;
  5874. this.peerconnection.close();
  5875. if (this.statsinterval !== null) {
  5876. window.clearInterval(this.statsinterval);
  5877. this.statsinterval = null;
  5878. }
  5879. };
  5880. JingleSessionPC.prototype.active = function () {
  5881. return this.state == 'active';
  5882. };
  5883. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  5884. var self = this;
  5885. if (candidate && !this.lasticecandidate) {
  5886. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  5887. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  5888. if (!(ice && jcand)) {
  5889. logger.error('failed to get ice && jcand');
  5890. return;
  5891. }
  5892. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5893. if (jcand.type === 'srflx') {
  5894. this.hadstuncandidate = true;
  5895. } else if (jcand.type === 'relay') {
  5896. this.hadturncandidate = true;
  5897. }
  5898. if (this.usetrickle) {
  5899. if (this.usedrip) {
  5900. if (this.drip_container.length === 0) {
  5901. // start 20ms callout
  5902. window.setTimeout(function () {
  5903. if (self.drip_container.length === 0) return;
  5904. self.sendIceCandidates(self.drip_container);
  5905. self.drip_container = [];
  5906. }, 20);
  5907. }
  5908. this.drip_container.push(candidate);
  5909. return;
  5910. } else {
  5911. self.sendIceCandidate([candidate]);
  5912. }
  5913. }
  5914. } else {
  5915. //logger.log('sendIceCandidate: last candidate.');
  5916. if (!this.usetrickle) {
  5917. //logger.log('should send full offer now...');
  5918. //FIXME why do we generate session-accept in 3 different places ?
  5919. var init = $iq({to: this.peerjid,
  5920. type: 'set'})
  5921. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5922. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  5923. initiator: this.initiator,
  5924. sid: this.sid});
  5925. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  5926. if (self.webrtcIceTcpDisable) {
  5927. this.localSDP.removeTcpCandidates = true;
  5928. }
  5929. if (self.webrtcIceUdpDisable) {
  5930. this.localSDP.removeUdpCandidates = true;
  5931. }
  5932. var sendJingle = function (ssrc) {
  5933. if(!ssrc)
  5934. ssrc = {};
  5935. self.localSDP.toJingle(
  5936. init,
  5937. self.initiator == self.me ? 'initiator' : 'responder',
  5938. ssrc);
  5939. SSRCReplacement.processSessionInit(init);
  5940. self.connection.sendIQ(init,
  5941. function () {
  5942. //logger.log('session initiate ack');
  5943. var ack = {};
  5944. ack.source = 'offer';
  5945. $(document).trigger('ack.jingle', [self.sid, ack]);
  5946. },
  5947. function (stanza) {
  5948. self.state = 'error';
  5949. self.peerconnection.close();
  5950. var error = ($(stanza).find('error').length) ? {
  5951. code: $(stanza).find('error').attr('code'),
  5952. reason: $(stanza).find('error :first')[0].tagName,
  5953. }:{};
  5954. error.source = 'offer';
  5955. JingleSessionPC.onJingleError(self.sid, error);
  5956. },
  5957. 10000);
  5958. };
  5959. sendJingle();
  5960. }
  5961. this.lasticecandidate = true;
  5962. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  5963. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  5964. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  5965. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  5966. }
  5967. }
  5968. };
  5969. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  5970. logger.log('sendIceCandidates', candidates);
  5971. var cand = $iq({to: this.peerjid, type: 'set'})
  5972. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5973. action: 'transport-info',
  5974. initiator: this.initiator,
  5975. sid: this.sid});
  5976. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  5977. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  5978. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  5979. if (cands.length > 0) {
  5980. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  5981. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5982. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  5983. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  5984. }).c('transport', ice);
  5985. for (var i = 0; i < cands.length; i++) {
  5986. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  5987. }
  5988. // add fingerprint
  5989. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  5990. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  5991. tmp.required = true;
  5992. cand.c(
  5993. 'fingerprint',
  5994. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  5995. .t(tmp.fingerprint);
  5996. delete tmp.fingerprint;
  5997. cand.attrs(tmp);
  5998. cand.up();
  5999. }
  6000. cand.up(); // transport
  6001. cand.up(); // content
  6002. }
  6003. }
  6004. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6005. //logger.log('was this the last candidate', this.lasticecandidate);
  6006. this.connection.sendIQ(cand,
  6007. function () {
  6008. var ack = {};
  6009. ack.source = 'transportinfo';
  6010. $(document).trigger('ack.jingle', [this.sid, ack]);
  6011. },
  6012. function (stanza) {
  6013. var error = ($(stanza).find('error').length) ? {
  6014. code: $(stanza).find('error').attr('code'),
  6015. reason: $(stanza).find('error :first')[0].tagName,
  6016. }:{};
  6017. error.source = 'transportinfo';
  6018. JingleSessionPC.onJingleError(this.sid, error);
  6019. },
  6020. 10000);
  6021. };
  6022. JingleSessionPC.prototype.sendOffer = function () {
  6023. //logger.log('sendOffer...');
  6024. var self = this;
  6025. this.peerconnection.createOffer(function (sdp) {
  6026. self.createdOffer(sdp);
  6027. },
  6028. function (e) {
  6029. logger.error('createOffer failed', e);
  6030. },
  6031. this.media_constraints
  6032. );
  6033. };
  6034. // FIXME createdOffer is never used in jitsi-meet
  6035. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6036. //logger.log('createdOffer', sdp);
  6037. var self = this;
  6038. this.localSDP = new SDP(sdp.sdp);
  6039. //this.localSDP.mangle();
  6040. var sendJingle = function () {
  6041. var init = $iq({to: this.peerjid,
  6042. type: 'set'})
  6043. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6044. action: 'session-initiate',
  6045. initiator: this.initiator,
  6046. sid: this.sid});
  6047. self.localSDP.toJingle(
  6048. init,
  6049. this.initiator == this.me ? 'initiator' : 'responder',
  6050. this.localStreamsSSRC);
  6051. SSRCReplacement.processSessionInit(init);
  6052. self.connection.sendIQ(init,
  6053. function () {
  6054. var ack = {};
  6055. ack.source = 'offer';
  6056. $(document).trigger('ack.jingle', [self.sid, ack]);
  6057. },
  6058. function (stanza) {
  6059. self.state = 'error';
  6060. self.peerconnection.close();
  6061. var error = ($(stanza).find('error').length) ? {
  6062. code: $(stanza).find('error').attr('code'),
  6063. reason: $(stanza).find('error :first')[0].tagName,
  6064. }:{};
  6065. error.source = 'offer';
  6066. JingleSessionPC.onJingleError(self.sid, error);
  6067. },
  6068. 10000);
  6069. }
  6070. sdp.sdp = this.localSDP.raw;
  6071. this.peerconnection.setLocalDescription(sdp,
  6072. function () {
  6073. if(self.usetrickle)
  6074. {
  6075. sendJingle();
  6076. }
  6077. self.setLocalDescription();
  6078. //logger.log('setLocalDescription success');
  6079. },
  6080. function (e) {
  6081. logger.error('setLocalDescription failed', e);
  6082. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6083. }
  6084. );
  6085. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6086. for (var i = 0; i < cands.length; i++) {
  6087. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6088. if (cand.type == 'srflx') {
  6089. this.hadstuncandidate = true;
  6090. } else if (cand.type == 'relay') {
  6091. this.hadturncandidate = true;
  6092. }
  6093. }
  6094. };
  6095. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6096. var self = this;
  6097. $(contents).each(function (idx, content) {
  6098. var name = $(content).attr('name');
  6099. var mediaType = this.getAttribute('name');
  6100. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6101. ssrcs.each(function () {
  6102. var ssrc = this.getAttribute('ssrc');
  6103. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6104. function () {
  6105. var owner = this.getAttribute('owner');
  6106. self.ssrcOwners[ssrc] = owner;
  6107. }
  6108. );
  6109. });
  6110. });
  6111. };
  6112. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6113. return this.ssrcOwners[ssrc];
  6114. };
  6115. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6116. //logger.log('setting remote description... ', desctype);
  6117. this.remoteSDP = new SDP('');
  6118. if (self.webrtcIceTcpDisable) {
  6119. this.remoteSDP.removeTcpCandidates = true;
  6120. }
  6121. if (self.webrtcIceUdpDisable) {
  6122. this.remoteSDP.removeUdpCandidates = true;
  6123. }
  6124. this.remoteSDP.fromJingle(elem);
  6125. this.readSsrcInfo($(elem).find(">content"));
  6126. if (this.peerconnection.remoteDescription) {
  6127. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6128. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6129. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6130. for (var i = 0; i < pranswer.media.length; i++) {
  6131. // make sure we have ice ufrag and pwd
  6132. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6133. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6134. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6135. } else {
  6136. logger.warn('no ice ufrag?');
  6137. }
  6138. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6139. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6140. } else {
  6141. logger.warn('no ice pwd?');
  6142. }
  6143. }
  6144. // copy over candidates
  6145. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6146. for (var j = 0; j < lines.length; j++) {
  6147. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6148. }
  6149. }
  6150. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6151. }
  6152. }
  6153. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6154. this.peerconnection.setRemoteDescription(remotedesc,
  6155. function () {
  6156. //logger.log('setRemoteDescription success');
  6157. },
  6158. function (e) {
  6159. logger.error('setRemoteDescription error', e);
  6160. JingleSessionPC.onJingleFatalError(self, e);
  6161. }
  6162. );
  6163. };
  6164. /**
  6165. * Adds remote ICE candidates to this Jingle session.
  6166. * @param elem An array of Jingle "content" elements?
  6167. */
  6168. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6169. var self = this;
  6170. if (this.peerconnection.signalingState == 'closed') {
  6171. return;
  6172. }
  6173. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6174. logger.log('trickle ice candidate arriving before session accept...');
  6175. // create a PRANSWER for setRemoteDescription
  6176. if (!this.remoteSDP) {
  6177. var cobbled = 'v=0\r\n' +
  6178. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6179. 's=-\r\n' +
  6180. 't=0 0\r\n';
  6181. // first, take some things from the local description
  6182. for (var i = 0; i < this.localSDP.media.length; i++) {
  6183. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6184. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6185. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6186. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6187. }
  6188. cobbled += 'a=inactive\r\n';
  6189. }
  6190. this.remoteSDP = new SDP(cobbled);
  6191. }
  6192. // then add things like ice and dtls from remote candidate
  6193. elem.each(function () {
  6194. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6195. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6196. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6197. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6198. var tmp = $(this).find('transport');
  6199. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6200. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6201. tmp = $(this).find('transport>fingerprint');
  6202. if (tmp.length) {
  6203. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6204. } else {
  6205. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6206. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6207. }
  6208. break;
  6209. }
  6210. }
  6211. }
  6212. });
  6213. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6214. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6215. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6216. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6217. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6218. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6219. }).length == this.remoteSDP.media.length;
  6220. if (iscomplete) {
  6221. logger.log('setting pranswer');
  6222. try {
  6223. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6224. function() {
  6225. },
  6226. function(e) {
  6227. logger.log('setRemoteDescription pranswer failed', e.toString());
  6228. });
  6229. } catch (e) {
  6230. logger.error('setting pranswer failed', e);
  6231. }
  6232. } else {
  6233. //logger.log('not yet setting pranswer');
  6234. }
  6235. }
  6236. // operate on each content element
  6237. elem.each(function () {
  6238. // would love to deactivate this, but firefox still requires it
  6239. var idx = -1;
  6240. var i;
  6241. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6242. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6243. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6244. idx = i;
  6245. break;
  6246. }
  6247. }
  6248. if (idx == -1) { // fall back to localdescription
  6249. for (i = 0; i < self.localSDP.media.length; i++) {
  6250. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6251. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6252. idx = i;
  6253. break;
  6254. }
  6255. }
  6256. }
  6257. var name = $(this).attr('name');
  6258. // TODO: check ice-pwd and ice-ufrag?
  6259. $(this).find('transport>candidate').each(function () {
  6260. var line, candidate;
  6261. var protocol = this.getAttribute('protocol');
  6262. protocol =
  6263. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6264. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6265. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6266. return;
  6267. }
  6268. line = SDPUtil.candidateFromJingle(this);
  6269. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6270. sdpMid: name,
  6271. candidate: line});
  6272. try {
  6273. self.peerconnection.addIceCandidate(candidate);
  6274. } catch (e) {
  6275. logger.error('addIceCandidate failed', e.toString(), line);
  6276. }
  6277. });
  6278. });
  6279. };
  6280. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6281. //logger.log('createAnswer', provisional);
  6282. var self = this;
  6283. this.peerconnection.createAnswer(
  6284. function (sdp) {
  6285. self.createdAnswer(sdp, provisional);
  6286. },
  6287. function (e) {
  6288. logger.error('createAnswer failed', e);
  6289. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6290. },
  6291. this.media_constraints
  6292. );
  6293. };
  6294. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6295. //logger.log('createAnswer callback');
  6296. var self = this;
  6297. this.localSDP = new SDP(sdp.sdp);
  6298. //this.localSDP.mangle();
  6299. this.usepranswer = provisional === true;
  6300. if (this.usetrickle) {
  6301. if (this.usepranswer) {
  6302. sdp.type = 'pranswer';
  6303. for (var i = 0; i < this.localSDP.media.length; i++) {
  6304. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6305. }
  6306. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6307. }
  6308. }
  6309. var self = this;
  6310. var sendJingle = function (ssrcs) {
  6311. // FIXME why do we generate session-accept in 3 different places ?
  6312. var accept = $iq({to: self.peerjid,
  6313. type: 'set'})
  6314. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6315. action: 'session-accept',
  6316. initiator: self.initiator,
  6317. responder: self.responder,
  6318. sid: self.sid });
  6319. if (self.webrtcIceTcpDisable) {
  6320. self.localSDP.removeTcpCandidates = true;
  6321. }
  6322. if (self.webrtcIceUdpDisable) {
  6323. self.localSDP.removeUdpCandidates = true;
  6324. }
  6325. self.localSDP.toJingle(
  6326. accept,
  6327. self.initiator == self.me ? 'initiator' : 'responder',
  6328. ssrcs);
  6329. SSRCReplacement.processSessionInit(accept);
  6330. self.connection.sendIQ(accept,
  6331. function () {
  6332. var ack = {};
  6333. ack.source = 'answer';
  6334. $(document).trigger('ack.jingle', [self.sid, ack]);
  6335. },
  6336. function (stanza) {
  6337. var error = ($(stanza).find('error').length) ? {
  6338. code: $(stanza).find('error').attr('code'),
  6339. reason: $(stanza).find('error :first')[0].tagName,
  6340. }:{};
  6341. error.source = 'answer';
  6342. JingleSessionPC.onJingleError(self.sid, error);
  6343. },
  6344. 10000);
  6345. }
  6346. sdp.sdp = this.localSDP.raw;
  6347. this.peerconnection.setLocalDescription(sdp,
  6348. function () {
  6349. //logger.log('setLocalDescription success');
  6350. if (self.usetrickle && !self.usepranswer) {
  6351. sendJingle();
  6352. }
  6353. self.setLocalDescription();
  6354. },
  6355. function (e) {
  6356. logger.error('setLocalDescription failed', e);
  6357. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6358. }
  6359. );
  6360. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6361. for (var j = 0; j < cands.length; j++) {
  6362. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6363. if (cand.type == 'srflx') {
  6364. this.hadstuncandidate = true;
  6365. } else if (cand.type == 'relay') {
  6366. this.hadturncandidate = true;
  6367. }
  6368. }
  6369. };
  6370. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  6371. var self = this,
  6372. term = $iq({to: this.peerjid,
  6373. type: 'set'})
  6374. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6375. action: 'session-terminate',
  6376. initiator: this.initiator,
  6377. sid: this.sid})
  6378. .c('reason')
  6379. .c(reason || 'success');
  6380. if (text) {
  6381. term.up().c('text').t(text);
  6382. }
  6383. this.connection.sendIQ(term,
  6384. function () {
  6385. self.peerconnection.close();
  6386. self.peerconnection = null;
  6387. self.terminate();
  6388. var ack = {};
  6389. ack.source = 'terminate';
  6390. $(document).trigger('ack.jingle', [self.sid, ack]);
  6391. },
  6392. function (stanza) {
  6393. var error = ($(stanza).find('error').length) ? {
  6394. code: $(stanza).find('error').attr('code'),
  6395. reason: $(stanza).find('error :first')[0].tagName,
  6396. }:{};
  6397. $(document).trigger('ack.jingle', [self.sid, error]);
  6398. },
  6399. 10000);
  6400. if (this.statsinterval !== null) {
  6401. window.clearInterval(this.statsinterval);
  6402. this.statsinterval = null;
  6403. }
  6404. };
  6405. /**
  6406. * Handles a Jingle source-add message for this Jingle session.
  6407. * @param elem An array of Jingle "content" elements.
  6408. */
  6409. JingleSessionPC.prototype.addSource = function (elem) {
  6410. var self = this;
  6411. // FIXME: dirty waiting
  6412. if (!this.peerconnection.localDescription)
  6413. {
  6414. logger.warn("addSource - localDescription not ready yet")
  6415. setTimeout(function()
  6416. {
  6417. self.addSource(elem);
  6418. },
  6419. 200
  6420. );
  6421. return;
  6422. }
  6423. logger.log('addssrc', new Date().getTime());
  6424. logger.log('ice', this.peerconnection.iceConnectionState);
  6425. this.readSsrcInfo(elem);
  6426. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6427. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6428. $(elem).each(function (idx, content) {
  6429. var name = $(content).attr('name');
  6430. var lines = '';
  6431. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6432. var semantics = this.getAttribute('semantics');
  6433. var ssrcs = $(this).find('>source').map(function () {
  6434. return this.getAttribute('ssrc');
  6435. }).get();
  6436. if (ssrcs.length) {
  6437. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6438. }
  6439. });
  6440. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6441. tmp.each(function () {
  6442. var ssrc = $(this).attr('ssrc');
  6443. if(mySdp.containsSSRC(ssrc)){
  6444. /**
  6445. * This happens when multiple participants change their streams at the same time and
  6446. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  6447. * addssrc are scheduled for update IQ. See
  6448. */
  6449. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  6450. return;
  6451. }
  6452. if (sdp.containsSSRC(ssrc)) {
  6453. logger.warn("Source-add request for existing SSRC: " + ssrc);
  6454. return;
  6455. }
  6456. $(this).find('>parameter').each(function () {
  6457. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6458. if ($(this).attr('value') && $(this).attr('value').length)
  6459. lines += ':' + $(this).attr('value');
  6460. lines += '\r\n';
  6461. });
  6462. });
  6463. sdp.media.forEach(function(media, idx) {
  6464. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6465. return;
  6466. sdp.media[idx] += lines;
  6467. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  6468. self.addssrc[idx] += lines;
  6469. });
  6470. sdp.raw = sdp.session + sdp.media.join('');
  6471. });
  6472. this.modifySourcesQueue.push(function() {
  6473. // When a source is added and if this is FF, a new channel is allocated
  6474. // for receiving the added source. We need to diffuse the SSRC of this
  6475. // new recvonly channel to the rest of the peers.
  6476. logger.log('modify sources done');
  6477. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6478. logger.log("SDPs", mySdp, newSdp);
  6479. self.notifyMySSRCUpdate(mySdp, newSdp);
  6480. });
  6481. };
  6482. /**
  6483. * Handles a Jingle source-remove message for this Jingle session.
  6484. * @param elem An array of Jingle "content" elements.
  6485. */
  6486. JingleSessionPC.prototype.removeSource = function (elem) {
  6487. var self = this;
  6488. // FIXME: dirty waiting
  6489. if (!this.peerconnection.localDescription) {
  6490. logger.warn("removeSource - localDescription not ready yet");
  6491. setTimeout(function() {
  6492. self.removeSource(elem);
  6493. },
  6494. 200
  6495. );
  6496. return;
  6497. }
  6498. logger.log('removessrc', new Date().getTime());
  6499. logger.log('ice', this.peerconnection.iceConnectionState);
  6500. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6501. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6502. $(elem).each(function (idx, content) {
  6503. var name = $(content).attr('name');
  6504. var lines = '';
  6505. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6506. var semantics = this.getAttribute('semantics');
  6507. var ssrcs = $(this).find('>source').map(function () {
  6508. return this.getAttribute('ssrc');
  6509. }).get();
  6510. if (ssrcs.length) {
  6511. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6512. }
  6513. });
  6514. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6515. tmp.each(function () {
  6516. var ssrc = $(this).attr('ssrc');
  6517. // This should never happen, but can be useful for bug detection
  6518. if(mySdp.containsSSRC(ssrc)){
  6519. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  6520. return;
  6521. }
  6522. $(this).find('>parameter').each(function () {
  6523. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6524. if ($(this).attr('value') && $(this).attr('value').length)
  6525. lines += ':' + $(this).attr('value');
  6526. lines += '\r\n';
  6527. });
  6528. });
  6529. sdp.media.forEach(function(media, idx) {
  6530. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6531. return;
  6532. sdp.media[idx] += lines;
  6533. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  6534. self.removessrc[idx] += lines;
  6535. });
  6536. sdp.raw = sdp.session + sdp.media.join('');
  6537. });
  6538. this.modifySourcesQueue.push(function() {
  6539. // When a source is removed and if this is FF, the recvonly channel that
  6540. // receives the remote stream is deactivated . We need to diffuse the
  6541. // recvonly SSRC removal to the rest of the peers.
  6542. logger.log('modify sources done');
  6543. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6544. logger.log("SDPs", mySdp, newSdp);
  6545. self.notifyMySSRCUpdate(mySdp, newSdp);
  6546. });
  6547. };
  6548. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  6549. var self = this;
  6550. if (this.peerconnection.signalingState == 'closed') return;
  6551. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  6552. || this.switchstreams || this.addingStreams)){
  6553. // There is nothing to do since scheduled job might have been executed by another succeeding call
  6554. this.setLocalDescription();
  6555. if(successCallback){
  6556. successCallback();
  6557. }
  6558. queueCallback();
  6559. return;
  6560. }
  6561. // Reset switch streams flags
  6562. this.switchstreams = false;
  6563. this.addingStreams = false;
  6564. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6565. // add sources
  6566. this.addssrc.forEach(function(lines, idx) {
  6567. sdp.media[idx] += lines;
  6568. });
  6569. this.addssrc = [];
  6570. // remove sources
  6571. this.removessrc.forEach(function(lines, idx) {
  6572. lines = lines.split('\r\n');
  6573. lines.pop(); // remove empty last element;
  6574. lines.forEach(function(line) {
  6575. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6576. });
  6577. });
  6578. this.removessrc = [];
  6579. sdp.raw = sdp.session + sdp.media.join('');
  6580. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6581. function() {
  6582. if(self.signalingState == 'closed') {
  6583. logger.error("createAnswer attempt on closed state");
  6584. queueCallback("createAnswer attempt on closed state");
  6585. return;
  6586. }
  6587. self.peerconnection.createAnswer(
  6588. function(modifiedAnswer) {
  6589. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6590. if (self.pendingop !== null) {
  6591. var sdp = new SDP(modifiedAnswer.sdp);
  6592. if (sdp.media.length > 1) {
  6593. switch(self.pendingop) {
  6594. case 'mute':
  6595. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6596. break;
  6597. case 'unmute':
  6598. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6599. break;
  6600. }
  6601. sdp.raw = sdp.session + sdp.media.join('');
  6602. modifiedAnswer.sdp = sdp.raw;
  6603. }
  6604. self.pendingop = null;
  6605. }
  6606. // FIXME: pushing down an answer while ice connection state
  6607. // is still checking is bad...
  6608. //logger.log(self.peerconnection.iceConnectionState);
  6609. // trying to work around another chrome bug
  6610. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6611. self.peerconnection.setLocalDescription(modifiedAnswer,
  6612. function() {
  6613. //logger.log('modified setLocalDescription ok');
  6614. self.setLocalDescription();
  6615. if(successCallback){
  6616. successCallback();
  6617. }
  6618. queueCallback();
  6619. },
  6620. function(error) {
  6621. logger.error('modified setLocalDescription failed', error);
  6622. queueCallback(error);
  6623. }
  6624. );
  6625. },
  6626. function(error) {
  6627. logger.error('modified answer failed', error);
  6628. queueCallback(error);
  6629. }
  6630. );
  6631. },
  6632. function(error) {
  6633. logger.error('modify failed', error);
  6634. queueCallback(error);
  6635. }
  6636. );
  6637. };
  6638. /**
  6639. * Switches video streams.
  6640. * @param newStream new stream that will be used as video of this session.
  6641. * @param oldStream old video stream of this session.
  6642. * @param successCallback callback executed after successful stream switch.
  6643. * @param isAudio whether the streams are audio (if true) or video (if false).
  6644. */
  6645. JingleSessionPC.prototype.switchStreams =
  6646. function (newStream, oldStream, successCallback, isAudio) {
  6647. var self = this;
  6648. var sender, newTrack;
  6649. var senderKind = isAudio ? 'audio' : 'video';
  6650. // Remember SDP to figure out added/removed SSRCs
  6651. var oldSdp = null;
  6652. if (self.peerconnection) {
  6653. if (self.peerconnection.localDescription) {
  6654. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6655. }
  6656. if (RTCBrowserType.getBrowserType() ===
  6657. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  6658. // On Firefox we don't replace MediaStreams as this messes up the
  6659. // m-lines (which can't be removed in Plan Unified) and brings a lot
  6660. // of complications. Instead, we use the RTPSender and replace just
  6661. // the track.
  6662. // Find the right sender (for audio or video)
  6663. self.peerconnection.peerconnection.getSenders().some(function (s) {
  6664. if (s.track && s.track.kind === senderKind) {
  6665. sender = s;
  6666. return true;
  6667. }
  6668. });
  6669. if (sender) {
  6670. // We assume that our streams have a single track, either audio
  6671. // or video.
  6672. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  6673. newStream.getVideoTracks()[0];
  6674. sender.replaceTrack(newTrack)
  6675. .then(function() {
  6676. console.log("Replaced a track, isAudio=" + isAudio);
  6677. })
  6678. .catch(function(err) {
  6679. console.log("Failed to replace a track: " + err);
  6680. });
  6681. } else {
  6682. console.log("Cannot switch tracks: no RTPSender.");
  6683. }
  6684. } else {
  6685. self.peerconnection.removeStream(oldStream, true);
  6686. if (newStream) {
  6687. self.peerconnection.addStream(newStream);
  6688. }
  6689. }
  6690. }
  6691. // Conference is not active
  6692. if (!oldSdp) {
  6693. successCallback();
  6694. return;
  6695. }
  6696. self.switchstreams = true;
  6697. self.modifySourcesQueue.push(function() {
  6698. logger.log('modify sources done');
  6699. successCallback();
  6700. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6701. logger.log("SDPs", oldSdp, newSdp);
  6702. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6703. });
  6704. };
  6705. /**
  6706. * Adds streams.
  6707. * @param stream new stream that will be added.
  6708. * @param success_callback callback executed after successful stream addition.
  6709. */
  6710. JingleSessionPC.prototype.addStream = function (stream, callback) {
  6711. var self = this;
  6712. // Remember SDP to figure out added/removed SSRCs
  6713. var oldSdp = null;
  6714. if(this.peerconnection) {
  6715. if(this.peerconnection.localDescription) {
  6716. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  6717. }
  6718. if(stream)
  6719. this.peerconnection.addStream(stream);
  6720. }
  6721. // Conference is not active
  6722. if(!oldSdp || !this.peerconnection) {
  6723. callback();
  6724. return;
  6725. }
  6726. this.addingStreams = true;
  6727. this.modifySourcesQueue.push(function() {
  6728. logger.log('modify sources done');
  6729. callback();
  6730. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6731. logger.log("SDPs", oldSdp, newSdp);
  6732. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6733. });
  6734. }
  6735. /**
  6736. * Figures out added/removed ssrcs and send update IQs.
  6737. * @param old_sdp SDP object for old description.
  6738. * @param new_sdp SDP object for new description.
  6739. */
  6740. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  6741. if (!(this.peerconnection.signalingState == 'stable' &&
  6742. this.peerconnection.iceConnectionState == 'connected')){
  6743. logger.log("Too early to send updates");
  6744. return;
  6745. }
  6746. // send source-remove IQ.
  6747. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  6748. var remove = $iq({to: this.peerjid, type: 'set'})
  6749. .c('jingle', {
  6750. xmlns: 'urn:xmpp:jingle:1',
  6751. action: 'source-remove',
  6752. initiator: this.initiator,
  6753. sid: this.sid
  6754. }
  6755. );
  6756. var removed = sdpDiffer.toJingle(remove);
  6757. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  6758. // it in the current form
  6759. if (removed)
  6760. remove = SSRCReplacement.processSourceRemove(remove);
  6761. if (removed && remove) {
  6762. logger.info("Sending source-remove", remove);
  6763. this.connection.sendIQ(remove,
  6764. function (res) {
  6765. logger.info('got remove result', res);
  6766. },
  6767. function (err) {
  6768. logger.error('got remove error', err);
  6769. }
  6770. );
  6771. } else {
  6772. logger.log('removal not necessary');
  6773. }
  6774. // send source-add IQ.
  6775. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  6776. var add = $iq({to: this.peerjid, type: 'set'})
  6777. .c('jingle', {
  6778. xmlns: 'urn:xmpp:jingle:1',
  6779. action: 'source-add',
  6780. initiator: this.initiator,
  6781. sid: this.sid
  6782. }
  6783. );
  6784. var added = sdpDiffer.toJingle(add);
  6785. // Let 'source-add' IQ through the hack and see if we're allowed to send
  6786. // it in the current form
  6787. if (added)
  6788. add = SSRCReplacement.processSourceAdd(add);
  6789. if (added && add) {
  6790. logger.info("Sending source-add", add);
  6791. this.connection.sendIQ(add,
  6792. function (res) {
  6793. logger.info('got add result', res);
  6794. },
  6795. function (err) {
  6796. logger.error('got add error', err);
  6797. }
  6798. );
  6799. } else {
  6800. logger.log('addition not necessary');
  6801. }
  6802. };
  6803. /**
  6804. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  6805. *
  6806. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  6807. * tracks; otherwise, <tt>false</tt>
  6808. * @param callback a function to be invoked with <tt>mute</tt> after all video
  6809. * tracks have been enabled/disabled. The function may, optionally, return
  6810. * another function which is to be invoked after the whole mute/unmute operation
  6811. * has completed successfully.
  6812. * @param options an object which specifies optional arguments such as the
  6813. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  6814. * specifies whether the method was initiated in response to a user command (in
  6815. * contrast to an automatic decision made by the application logic)
  6816. */
  6817. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  6818. var byUser;
  6819. if (options) {
  6820. byUser = options.byUser;
  6821. if (typeof byUser === 'undefined') {
  6822. byUser = true;
  6823. }
  6824. } else {
  6825. byUser = true;
  6826. }
  6827. // The user's command to mute the (local) video takes precedence over any
  6828. // automatic decision made by the application logic.
  6829. if (byUser) {
  6830. this.videoMuteByUser = mute;
  6831. } else if (this.videoMuteByUser) {
  6832. return;
  6833. }
  6834. this.hardMuteVideo(mute);
  6835. var self = this;
  6836. var oldSdp = null;
  6837. if(self.peerconnection) {
  6838. if(self.peerconnection.localDescription) {
  6839. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6840. }
  6841. }
  6842. this.modifySourcesQueue.push(function() {
  6843. logger.log('modify sources done');
  6844. callback(mute);
  6845. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6846. logger.log("SDPs", oldSdp, newSdp);
  6847. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6848. });
  6849. };
  6850. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  6851. this.pendingop = muted ? 'mute' : 'unmute';
  6852. };
  6853. JingleSessionPC.prototype.sendMute = function (muted, content) {
  6854. var info = $iq({to: this.peerjid,
  6855. type: 'set'})
  6856. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6857. action: 'session-info',
  6858. initiator: this.initiator,
  6859. sid: this.sid });
  6860. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6861. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  6862. if (content) {
  6863. info.attrs({'name': content});
  6864. }
  6865. this.connection.send(info);
  6866. };
  6867. JingleSessionPC.prototype.sendRinging = function () {
  6868. var info = $iq({to: this.peerjid,
  6869. type: 'set'})
  6870. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6871. action: 'session-info',
  6872. initiator: this.initiator,
  6873. sid: this.sid });
  6874. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6875. this.connection.send(info);
  6876. };
  6877. JingleSessionPC.prototype.getStats = function (interval) {
  6878. var self = this;
  6879. var recv = {audio: 0, video: 0};
  6880. var lost = {audio: 0, video: 0};
  6881. var lastrecv = {audio: 0, video: 0};
  6882. var lastlost = {audio: 0, video: 0};
  6883. var loss = {audio: 0, video: 0};
  6884. var delta = {audio: 0, video: 0};
  6885. this.statsinterval = window.setInterval(function () {
  6886. if (self && self.peerconnection && self.peerconnection.getStats) {
  6887. self.peerconnection.getStats(function (stats) {
  6888. var results = stats.result();
  6889. // TODO: there are so much statistics you can get from this..
  6890. for (var i = 0; i < results.length; ++i) {
  6891. if (results[i].type == 'ssrc') {
  6892. var packetsrecv = results[i].stat('packetsReceived');
  6893. var packetslost = results[i].stat('packetsLost');
  6894. if (packetsrecv && packetslost) {
  6895. packetsrecv = parseInt(packetsrecv, 10);
  6896. packetslost = parseInt(packetslost, 10);
  6897. if (results[i].stat('googFrameRateReceived')) {
  6898. lastlost.video = lost.video;
  6899. lastrecv.video = recv.video;
  6900. recv.video = packetsrecv;
  6901. lost.video = packetslost;
  6902. } else {
  6903. lastlost.audio = lost.audio;
  6904. lastrecv.audio = recv.audio;
  6905. recv.audio = packetsrecv;
  6906. lost.audio = packetslost;
  6907. }
  6908. }
  6909. }
  6910. }
  6911. delta.audio = recv.audio - lastrecv.audio;
  6912. delta.video = recv.video - lastrecv.video;
  6913. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  6914. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  6915. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  6916. });
  6917. }
  6918. }, interval || 3000);
  6919. return this.statsinterval;
  6920. };
  6921. JingleSessionPC.onJingleError = function (session, error)
  6922. {
  6923. logger.error("Jingle error", error);
  6924. }
  6925. JingleSessionPC.onJingleFatalError = function (session, error)
  6926. {
  6927. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6928. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  6929. }
  6930. JingleSessionPC.prototype.setLocalDescription = function () {
  6931. var self = this;
  6932. var newssrcs = [];
  6933. if(!this.peerconnection.localDescription)
  6934. return;
  6935. var session = transform.parse(this.peerconnection.localDescription.sdp);
  6936. var i;
  6937. session.media.forEach(function (media) {
  6938. if (media.ssrcs && media.ssrcs.length > 0) {
  6939. // TODO(gp) maybe exclude FID streams?
  6940. media.ssrcs.forEach(function (ssrc) {
  6941. if (ssrc.attribute !== 'cname') {
  6942. return;
  6943. }
  6944. newssrcs.push({
  6945. 'ssrc': ssrc.id,
  6946. 'type': media.type
  6947. });
  6948. });
  6949. }
  6950. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  6951. {
  6952. newssrcs.push({
  6953. 'ssrc': self.localStreamsSSRC[media.type],
  6954. 'type': media.type
  6955. });
  6956. }
  6957. });
  6958. logger.log('new ssrcs', newssrcs);
  6959. // Bind us as local SSRCs owner
  6960. if (newssrcs.length > 0) {
  6961. for (i = 0; i < newssrcs.length; i++) {
  6962. var ssrc = newssrcs[i].ssrc;
  6963. var myJid = self.connection.emuc.myroomjid;
  6964. self.ssrcOwners[ssrc] = myJid;
  6965. }
  6966. }
  6967. }
  6968. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  6969. JingleSessionPC.prototype.sendKeyframe = function () {
  6970. var pc = this.peerconnection;
  6971. logger.log('sendkeyframe', pc.iceConnectionState);
  6972. if (pc.iceConnectionState !== 'connected') return; // safe...
  6973. var self = this;
  6974. pc.setRemoteDescription(
  6975. pc.remoteDescription,
  6976. function () {
  6977. pc.createAnswer(
  6978. function (modifiedAnswer) {
  6979. pc.setLocalDescription(
  6980. modifiedAnswer,
  6981. function () {
  6982. // noop
  6983. },
  6984. function (error) {
  6985. logger.log('triggerKeyframe setLocalDescription failed', error);
  6986. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  6987. }
  6988. );
  6989. },
  6990. function (error) {
  6991. logger.log('triggerKeyframe createAnswer failed', error);
  6992. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  6993. }
  6994. );
  6995. },
  6996. function (error) {
  6997. logger.log('triggerKeyframe setRemoteDescription failed', error);
  6998. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  6999. }
  7000. );
  7001. }
  7002. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7003. var self = this;
  7004. var thessrc;
  7005. var streamId = RTC.getStreamID(data.stream);
  7006. // look up an associated JID for a stream id
  7007. if (!streamId) {
  7008. logger.error("No stream ID for", data.stream);
  7009. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7010. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7011. var ssrclines = this.peerconnection.remoteDescription?
  7012. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7013. ssrclines = ssrclines.filter(function (line) {
  7014. // NOTE(gp) previously we filtered on the mslabel, but that property
  7015. // is not always present.
  7016. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7017. if (RTCBrowserType.isTemasysPluginUsed()) {
  7018. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7019. } else {
  7020. return ((line.indexOf('msid:' + streamId) !== -1));
  7021. }
  7022. });
  7023. if (ssrclines.length) {
  7024. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7025. if (!self.ssrcOwners[thessrc]) {
  7026. logger.error("No SSRC owner known for: " + thessrc);
  7027. return;
  7028. }
  7029. data.peerjid = self.ssrcOwners[thessrc];
  7030. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7031. } else {
  7032. logger.error("No SSRC lines for ", streamId);
  7033. }
  7034. }
  7035. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7036. var isVideo = data.stream.getVideoTracks().length > 0;
  7037. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7038. if (isVideo &&
  7039. data.peerjid && this.peerjid === data.peerjid &&
  7040. data.stream.getVideoTracks().length === 0 &&
  7041. RTC.localVideo.getTracks().length > 0) {
  7042. window.setTimeout(function () {
  7043. self.sendKeyframe();
  7044. }, 3000);
  7045. }
  7046. }
  7047. module.exports = JingleSessionPC;
  7048. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7049. },{"../../service/xmpp/XMPPEvents":86,"../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){
  7050. (function (__filename){
  7051. /* global $ */
  7052. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7053. /*
  7054. Here we do modifications of local video SSRCs. There are 2 situations we have
  7055. to handle:
  7056. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7057. have no local camera and it is not generated automatically, but SSRC=1 is
  7058. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7059. and we won't be able to request video key frames correctly.
  7060. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7061. in future. It turned out that Chrome may keep on using the SSRC of removed
  7062. video stream in RTCP even though a new one has been created. So we just
  7063. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7064. notifications are blocked once first video SSRC is advertised to the focus.
  7065. What this hack does:
  7066. 1. Stores the SSRC of the first video stream created by
  7067. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7068. b) watching for 'source-add' for new video stream if it has not been
  7069. created in step a)
  7070. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7071. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7072. returned to the other parts of the application.
  7073. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7074. blocks those notifications. This makes Jicofo and all participants think
  7075. that it exists all the time even if the video stream has been removed or
  7076. replaced locally. Thanks to that there is no additional signaling activity
  7077. on video mute or when switching to the desktop stream.
  7078. */
  7079. var SDP = require('./SDP');
  7080. var RandomUtil = require('../util/RandomUtil');
  7081. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7082. /**
  7083. * The hack is enabled on all browsers except FF by default
  7084. * FIXME finish the hack once removeStream method is implemented in FF
  7085. * @type {boolean}
  7086. */
  7087. var isEnabled = !RTCBrowserType.isFirefox();
  7088. /**
  7089. * Stored SSRC of local video stream.
  7090. */
  7091. var localVideoSSRC;
  7092. /**
  7093. * SSRC, msid, mslabel, label used for recvonly video stream when we have no local camera.
  7094. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7095. * instead of 1.
  7096. */
  7097. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  7098. /**
  7099. * cname for <tt>localRecvOnlySSRC</tt>
  7100. */
  7101. var localRecvOnlyCName;
  7102. /**
  7103. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7104. * from given Jingle IQ.
  7105. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7106. * @param actionName display name of the action which will be printed in log
  7107. * messages.
  7108. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7109. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7110. * other SSRCs left to be signaled after removing it.
  7111. */
  7112. var filterOutSource = function (modifyIq, actionName) {
  7113. var modifyIqTree = $(modifyIq.tree());
  7114. if (!localVideoSSRC)
  7115. return modifyIqTree[0];
  7116. var videoSSRC = modifyIqTree.find(
  7117. '>jingle>content[name="video"]' +
  7118. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7119. if (!videoSSRC.length) {
  7120. return modifyIqTree[0];
  7121. }
  7122. logger.info(
  7123. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7124. videoSSRC.remove();
  7125. // Check if any sources still left to be added/removed
  7126. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7127. return modifyIqTree[0];
  7128. } else {
  7129. return null;
  7130. }
  7131. };
  7132. /**
  7133. * Scans given Jingle IQ for video SSRC and stores it.
  7134. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7135. */
  7136. var storeLocalVideoSSRC = function (jingleIq) {
  7137. var videoSSRCs =
  7138. $(jingleIq.tree())
  7139. .find('>jingle>content[name="video"]>description>source');
  7140. videoSSRCs.each(function (idx, ssrcElem) {
  7141. if (localVideoSSRC)
  7142. return;
  7143. // We consider SSRC real only if it has msid attribute
  7144. // recvonly streams in FF do not have it as well as local SSRCs
  7145. // we generate for recvonly streams in Chrome
  7146. var ssrSel = $(ssrcElem);
  7147. var msid = ssrSel.find('>parameter[name="msid"]');
  7148. if (msid.length) {
  7149. var ssrcVal = ssrSel.attr('ssrc');
  7150. if (ssrcVal) {
  7151. localVideoSSRC = ssrcVal;
  7152. logger.info('Stored local video SSRC' +
  7153. ' for future re-use: ' + localVideoSSRC);
  7154. }
  7155. }
  7156. });
  7157. };
  7158. /**
  7159. * Generates new label/mslabel attribute
  7160. * @returns {string} label/mslabel attribute
  7161. */
  7162. function generateLabel() {
  7163. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  7164. "-" + RandomUtil.randomHexString(4) + "-" +
  7165. RandomUtil.randomHexString(4) + "-" + RandomUtil.randomHexString(12);
  7166. }
  7167. /**
  7168. * Generates new SSRC, CNAME, mslabel, label and msid for local video recvonly stream.
  7169. * FIXME what about eventual SSRC collision ?
  7170. */
  7171. function generateRecvonlySSRC() {
  7172. localRecvOnlySSRC =
  7173. Math.random().toString(10).substring(2, 11);
  7174. localRecvOnlyCName =
  7175. Math.random().toString(36).substring(2);
  7176. localRecvOnlyMSLabel = generateLabel();
  7177. localRecvOnlyLabel = generateLabel();
  7178. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  7179. logger.info(
  7180. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7181. ", cname: " + localRecvOnlyCName);
  7182. }
  7183. var LocalSSRCReplacement = {
  7184. /**
  7185. * Method must be called before 'session-initiate' or 'session-invite' is
  7186. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7187. *
  7188. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7189. * which will be scanned for local video SSRC.
  7190. */
  7191. processSessionInit: function (sessionInit) {
  7192. if (!isEnabled)
  7193. return;
  7194. if (localVideoSSRC) {
  7195. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7196. return;
  7197. }
  7198. storeLocalVideoSSRC(sessionInit);
  7199. },
  7200. /**
  7201. * If we have local video SSRC stored searched given
  7202. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7203. * with the stored one.
  7204. * @param localDescription local description object that will have local
  7205. * video SSRC replaced with the stored one
  7206. * @returns modified <tt>localDescription</tt> object.
  7207. */
  7208. mungeLocalVideoSSRC: function (localDescription) {
  7209. if (!isEnabled)
  7210. return localDescription;
  7211. if (!localDescription) {
  7212. logger.warn("localDescription is null or undefined");
  7213. return localDescription;
  7214. }
  7215. // IF we have local video SSRC stored make sure it is replaced
  7216. // with old SSRC
  7217. if (localVideoSSRC) {
  7218. var newSdp = new SDP(localDescription.sdp);
  7219. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7220. !newSdp.containsSSRC(localVideoSSRC)) {
  7221. // Get new video SSRC
  7222. var map = newSdp.getMediaSsrcMap();
  7223. var videoPart = map[1];
  7224. var videoSSRCs = videoPart.ssrcs;
  7225. var newSSRC = Object.keys(videoSSRCs)[0];
  7226. logger.info(
  7227. "Replacing new video SSRC: " + newSSRC +
  7228. " with " + localVideoSSRC);
  7229. localDescription.sdp =
  7230. newSdp.raw.replace(
  7231. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7232. 'a=ssrc:' + localVideoSSRC);
  7233. }
  7234. } else {
  7235. // Make sure we have any SSRC for recvonly video stream
  7236. var sdp = new SDP(localDescription.sdp);
  7237. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7238. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7239. if (!localRecvOnlySSRC) {
  7240. generateRecvonlySSRC();
  7241. }
  7242. localVideoSSRC = localRecvOnlySSRC;
  7243. logger.info('No SSRC in video recvonly stream' +
  7244. ' - adding SSRC: ' + localRecvOnlySSRC);
  7245. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7246. ' cname:' + localRecvOnlyCName + '\r\n' +
  7247. 'a=ssrc:' + localRecvOnlySSRC +
  7248. ' msid:' + localRecvOnlyMSID + '\r\n' +
  7249. 'a=ssrc:' + localRecvOnlySSRC +
  7250. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  7251. 'a=ssrc:' + localRecvOnlySSRC +
  7252. ' label:' + localRecvOnlyLabel + '\r\n';
  7253. localDescription.sdp = sdp.session + sdp.media.join('');
  7254. }
  7255. }
  7256. return localDescription;
  7257. },
  7258. /**
  7259. * Method must be called before 'source-add' notification is sent. In case
  7260. * we have local video SSRC advertised already it will be removed from the
  7261. * notification. If no other SSRCs are described by given IQ null will be
  7262. * returned which means that there is no point in sending the notification.
  7263. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7264. * @returns modified 'source-add' IQ which can be sent to the focus or
  7265. * <tt>null</tt> if no notification shall be sent. It is no longer
  7266. * a Strophe IQ Builder instance, but DOM element tree.
  7267. */
  7268. processSourceAdd: function (sourceAdd) {
  7269. if (!isEnabled)
  7270. return sourceAdd;
  7271. if (!localVideoSSRC) {
  7272. // Store local SSRC if available
  7273. storeLocalVideoSSRC(sourceAdd);
  7274. return sourceAdd;
  7275. } else {
  7276. return filterOutSource(sourceAdd, 'source-add');
  7277. }
  7278. },
  7279. /**
  7280. * Method must be called before 'source-remove' notification is sent.
  7281. * Removes local video SSRC from the notification. If there are no other
  7282. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  7283. * means that there is no point in sending the notification.
  7284. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  7285. * @returns modified 'source-remove' IQ which can be sent to the focus or
  7286. * <tt>null</tt> if no notification shall be sent. It is no longer
  7287. * a Strophe IQ Builder instance, but DOM element tree.
  7288. */
  7289. processSourceRemove: function (sourceRemove) {
  7290. if (!isEnabled)
  7291. return sourceRemove;
  7292. return filterOutSource(sourceRemove, 'source-remove');
  7293. },
  7294. /**
  7295. * Turns the hack on or off
  7296. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  7297. * to disable it
  7298. */
  7299. setEnabled: function (enabled) {
  7300. isEnabled = enabled;
  7301. }
  7302. };
  7303. module.exports = LocalSSRCReplacement;
  7304. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7305. },{"../RTC/RTCBrowserType":17,"../util/RandomUtil":25,"./SDP":30,"jitsi-meet-logger":47}],30:[function(require,module,exports){
  7306. (function (__filename){
  7307. /* jshint -W117 */
  7308. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7309. var SDPUtil = require("./SDPUtil");
  7310. // SDP STUFF
  7311. function SDP(sdp) {
  7312. /**
  7313. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7314. * @type {boolean}
  7315. */
  7316. this.removeTcpCandidates = false;
  7317. /**
  7318. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7319. * @type {boolean}
  7320. */
  7321. this.removeUdpCandidates = false;
  7322. this.media = sdp.split('\r\nm=');
  7323. for (var i = 1; i < this.media.length; i++) {
  7324. this.media[i] = 'm=' + this.media[i];
  7325. if (i != this.media.length - 1) {
  7326. this.media[i] += '\r\n';
  7327. }
  7328. }
  7329. this.session = this.media.shift() + '\r\n';
  7330. this.raw = this.session + this.media.join('');
  7331. }
  7332. /**
  7333. * Returns map of MediaChannel mapped per channel idx.
  7334. */
  7335. SDP.prototype.getMediaSsrcMap = function() {
  7336. var self = this;
  7337. var media_ssrcs = {};
  7338. var tmp;
  7339. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7340. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7341. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7342. var media = {
  7343. mediaindex: mediaindex,
  7344. mid: mid,
  7345. ssrcs: {},
  7346. ssrcGroups: []
  7347. };
  7348. media_ssrcs[mediaindex] = media;
  7349. tmp.forEach(function (line) {
  7350. var linessrc = line.substring(7).split(' ')[0];
  7351. // allocate new ChannelSsrc
  7352. if(!media.ssrcs[linessrc]) {
  7353. media.ssrcs[linessrc] = {
  7354. ssrc: linessrc,
  7355. lines: []
  7356. };
  7357. }
  7358. media.ssrcs[linessrc].lines.push(line);
  7359. });
  7360. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7361. tmp.forEach(function(line){
  7362. var idx = line.indexOf(' ');
  7363. var semantics = line.substr(0, idx).substr(13);
  7364. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7365. if (ssrcs.length) {
  7366. media.ssrcGroups.push({
  7367. semantics: semantics,
  7368. ssrcs: ssrcs
  7369. });
  7370. }
  7371. });
  7372. }
  7373. return media_ssrcs;
  7374. };
  7375. /**
  7376. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7377. * @param ssrc the ssrc to check.
  7378. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7379. */
  7380. SDP.prototype.containsSSRC = function(ssrc) {
  7381. var medias = this.getMediaSsrcMap();
  7382. Object.keys(medias).forEach(function(mediaindex){
  7383. var media = medias[mediaindex];
  7384. //logger.log("Check", channel, ssrc);
  7385. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  7386. return true;
  7387. }
  7388. });
  7389. return false;
  7390. };
  7391. // remove iSAC and CN from SDP
  7392. SDP.prototype.mangle = function () {
  7393. var i, j, mline, lines, rtpmap, newdesc;
  7394. for (i = 0; i < this.media.length; i++) {
  7395. lines = this.media[i].split('\r\n');
  7396. lines.pop(); // remove empty last element
  7397. mline = SDPUtil.parse_mline(lines.shift());
  7398. if (mline.media != 'audio')
  7399. continue;
  7400. newdesc = '';
  7401. mline.fmt.length = 0;
  7402. for (j = 0; j < lines.length; j++) {
  7403. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  7404. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  7405. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  7406. continue;
  7407. mline.fmt.push(rtpmap.id);
  7408. newdesc += lines[j] + '\r\n';
  7409. } else {
  7410. newdesc += lines[j] + '\r\n';
  7411. }
  7412. }
  7413. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  7414. this.media[i] += newdesc;
  7415. }
  7416. this.raw = this.session + this.media.join('');
  7417. };
  7418. // remove lines matching prefix from session section
  7419. SDP.prototype.removeSessionLines = function(prefix) {
  7420. var self = this;
  7421. var lines = SDPUtil.find_lines(this.session, prefix);
  7422. lines.forEach(function(line) {
  7423. self.session = self.session.replace(line + '\r\n', '');
  7424. });
  7425. this.raw = this.session + this.media.join('');
  7426. return lines;
  7427. }
  7428. // remove lines matching prefix from a media section specified by mediaindex
  7429. // TODO: non-numeric mediaindex could match mid
  7430. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  7431. var self = this;
  7432. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  7433. lines.forEach(function(line) {
  7434. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  7435. });
  7436. this.raw = this.session + this.media.join('');
  7437. return lines;
  7438. }
  7439. // add content's to a jingle element
  7440. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  7441. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  7442. var self = this;
  7443. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  7444. // new bundle plan
  7445. if (SDPUtil.find_line(this.session, 'a=group:')) {
  7446. lines = SDPUtil.find_lines(this.session, 'a=group:');
  7447. for (i = 0; i < lines.length; i++) {
  7448. tmp = lines[i].split(' ');
  7449. var semantics = tmp.shift().substr(8);
  7450. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  7451. for (j = 0; j < tmp.length; j++) {
  7452. elem.c('content', {name: tmp[j]}).up();
  7453. }
  7454. elem.up();
  7455. }
  7456. }
  7457. for (i = 0; i < this.media.length; i++) {
  7458. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  7459. if (!(mline.media === 'audio' ||
  7460. mline.media === 'video' ||
  7461. mline.media === 'application'))
  7462. {
  7463. continue;
  7464. }
  7465. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  7466. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  7467. } else {
  7468. if(ssrcs && ssrcs[mline.media]) {
  7469. ssrc = ssrcs[mline.media];
  7470. } else {
  7471. ssrc = false;
  7472. }
  7473. }
  7474. elem.c('content', {creator: thecreator, name: mline.media});
  7475. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  7476. // prefer identifier from a=mid if present
  7477. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  7478. elem.attrs({ name: mid });
  7479. }
  7480. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  7481. elem.c('description',
  7482. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  7483. media: mline.media });
  7484. if (ssrc) {
  7485. elem.attrs({ssrc: ssrc});
  7486. }
  7487. for (j = 0; j < mline.fmt.length; j++) {
  7488. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  7489. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  7490. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  7491. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  7492. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  7493. for (k = 0; k < tmp.length; k++) {
  7494. elem.c('parameter', tmp[k]).up();
  7495. }
  7496. }
  7497. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  7498. elem.up();
  7499. }
  7500. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  7501. elem.c('encryption', {required: 1});
  7502. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  7503. crypto.forEach(function(line) {
  7504. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  7505. });
  7506. elem.up(); // end of encryption
  7507. }
  7508. if (ssrc) {
  7509. // new style mapping
  7510. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7511. // FIXME: group by ssrc and support multiple different ssrcs
  7512. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  7513. if(ssrclines.length > 0) {
  7514. ssrclines.forEach(function (line) {
  7515. var idx = line.indexOf(' ');
  7516. var linessrc = line.substr(0, idx).substr(7);
  7517. if (linessrc != ssrc) {
  7518. elem.up();
  7519. ssrc = linessrc;
  7520. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7521. }
  7522. var kv = line.substr(idx + 1);
  7523. elem.c('parameter');
  7524. if (kv.indexOf(':') == -1) {
  7525. elem.attrs({ name: kv });
  7526. } else {
  7527. var k = kv.split(':', 2)[0];
  7528. elem.attrs({ name: k });
  7529. var v = kv.split(':', 2)[1];
  7530. v = SDPUtil.filter_special_chars(v);
  7531. elem.attrs({ value: v });
  7532. }
  7533. elem.up();
  7534. });
  7535. } else {
  7536. elem.up();
  7537. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7538. elem.c('parameter');
  7539. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  7540. elem.up();
  7541. var msid = null;
  7542. if(mline.media == "audio")
  7543. {
  7544. msid = APP.RTC.localAudio.getId();
  7545. }
  7546. else
  7547. {
  7548. msid = APP.RTC.localVideo.getId();
  7549. }
  7550. if(msid != null)
  7551. {
  7552. msid = SDPUtil.filter_special_chars(msid);
  7553. elem.c('parameter');
  7554. elem.attrs({name: "msid", value:msid});
  7555. elem.up();
  7556. elem.c('parameter');
  7557. elem.attrs({name: "mslabel", value:msid});
  7558. elem.up();
  7559. elem.c('parameter');
  7560. elem.attrs({name: "label", value:msid});
  7561. elem.up();
  7562. }
  7563. }
  7564. elem.up();
  7565. // XEP-0339 handle ssrc-group attributes
  7566. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  7567. ssrc_group_lines.forEach(function(line) {
  7568. var idx = line.indexOf(' ');
  7569. var semantics = line.substr(0, idx).substr(13);
  7570. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7571. if (ssrcs.length) {
  7572. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7573. ssrcs.forEach(function(ssrc) {
  7574. elem.c('source', { ssrc: ssrc })
  7575. .up();
  7576. });
  7577. elem.up();
  7578. }
  7579. });
  7580. }
  7581. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  7582. elem.c('rtcp-mux').up();
  7583. }
  7584. // XEP-0293 -- map a=rtcp-fb:*
  7585. this.rtcpFbToJingle(i, elem, '*');
  7586. // XEP-0294
  7587. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  7588. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  7589. for (j = 0; j < lines.length; j++) {
  7590. tmp = SDPUtil.parse_extmap(lines[j]);
  7591. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  7592. uri: tmp.uri,
  7593. id: tmp.value });
  7594. if (tmp.hasOwnProperty('direction')) {
  7595. switch (tmp.direction) {
  7596. case 'sendonly':
  7597. elem.attrs({senders: 'responder'});
  7598. break;
  7599. case 'recvonly':
  7600. elem.attrs({senders: 'initiator'});
  7601. break;
  7602. case 'sendrecv':
  7603. elem.attrs({senders: 'both'});
  7604. break;
  7605. case 'inactive':
  7606. elem.attrs({senders: 'none'});
  7607. break;
  7608. }
  7609. }
  7610. // TODO: handle params
  7611. elem.up();
  7612. }
  7613. }
  7614. elem.up(); // end of description
  7615. }
  7616. // map ice-ufrag/pwd, dtls fingerprint, candidates
  7617. this.transportToJingle(i, elem);
  7618. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7619. elem.attrs({senders: 'both'});
  7620. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7621. elem.attrs({senders: 'initiator'});
  7622. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7623. elem.attrs({senders: 'responder'});
  7624. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7625. elem.attrs({senders: 'none'});
  7626. }
  7627. if (mline.port == '0') {
  7628. // estos hack to reject an m-line
  7629. elem.attrs({senders: 'rejected'});
  7630. }
  7631. elem.up(); // end of content
  7632. }
  7633. elem.up();
  7634. return elem;
  7635. };
  7636. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  7637. var tmp, sctpmap, sctpAttrs, fingerprints;
  7638. var self = this;
  7639. elem.c('transport');
  7640. // XEP-0343 DTLS/SCTP
  7641. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  7642. {
  7643. sctpmap = SDPUtil.find_line(
  7644. this.media[mediaindex], 'a=sctpmap:', self.session);
  7645. if (sctpmap)
  7646. {
  7647. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  7648. elem.c('sctpmap',
  7649. {
  7650. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  7651. number: sctpAttrs[0], /* SCTP port */
  7652. protocol: sctpAttrs[1] /* protocol */
  7653. });
  7654. // Optional stream count attribute
  7655. if (sctpAttrs.length > 2)
  7656. elem.attrs({ streams: sctpAttrs[2]});
  7657. elem.up();
  7658. }
  7659. }
  7660. // XEP-0320
  7661. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  7662. fingerprints.forEach(function(line) {
  7663. tmp = SDPUtil.parse_fingerprint(line);
  7664. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  7665. elem.c('fingerprint').t(tmp.fingerprint);
  7666. delete tmp.fingerprint;
  7667. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  7668. if (line) {
  7669. tmp.setup = line.substr(8);
  7670. }
  7671. elem.attrs(tmp);
  7672. elem.up(); // end of fingerprint
  7673. });
  7674. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  7675. if (tmp) {
  7676. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7677. elem.attrs(tmp);
  7678. // XEP-0176
  7679. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  7680. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  7681. lines.forEach(function (line) {
  7682. var candidate = SDPUtil.candidateToJingle(line);
  7683. var protocol = (candidate &&
  7684. typeof candidate.protocol === 'string')
  7685. ? candidate.protocol.toLowerCase() : '';
  7686. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  7687. (self.removeUdpCandidates && protocol === 'udp')) {
  7688. return;
  7689. }
  7690. elem.c('candidate', candidate).up();
  7691. });
  7692. }
  7693. }
  7694. elem.up(); // end of transport
  7695. }
  7696. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  7697. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  7698. lines.forEach(function (line) {
  7699. var tmp = SDPUtil.parse_rtcpfb(line);
  7700. if (tmp.type == 'trr-int') {
  7701. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  7702. elem.up();
  7703. } else {
  7704. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  7705. if (tmp.params.length > 0) {
  7706. elem.attrs({'subtype': tmp.params[0]});
  7707. }
  7708. elem.up();
  7709. }
  7710. });
  7711. };
  7712. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  7713. var media = '';
  7714. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7715. if (tmp.length) {
  7716. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  7717. if (tmp.attr('value')) {
  7718. media += tmp.attr('value');
  7719. } else {
  7720. media += '0';
  7721. }
  7722. media += '\r\n';
  7723. }
  7724. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7725. tmp.each(function () {
  7726. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  7727. if ($(this).attr('subtype')) {
  7728. media += ' ' + $(this).attr('subtype');
  7729. }
  7730. media += '\r\n';
  7731. });
  7732. return media;
  7733. };
  7734. // construct an SDP from a jingle stanza
  7735. SDP.prototype.fromJingle = function (jingle) {
  7736. var self = this;
  7737. this.raw = 'v=0\r\n' +
  7738. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  7739. 's=-\r\n' +
  7740. 't=0 0\r\n';
  7741. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  7742. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  7743. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  7744. var contents = $(group).find('>content').map(function (idx, content) {
  7745. return content.getAttribute('name');
  7746. }).get();
  7747. if (contents.length > 0) {
  7748. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  7749. }
  7750. });
  7751. }
  7752. this.session = this.raw;
  7753. jingle.find('>content').each(function () {
  7754. var m = self.jingle2media($(this));
  7755. self.media.push(m);
  7756. });
  7757. // reconstruct msid-semantic -- apparently not necessary
  7758. /*
  7759. var msid = SDPUtil.parse_ssrc(this.raw);
  7760. if (msid.hasOwnProperty('mslabel')) {
  7761. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  7762. }
  7763. */
  7764. this.raw = this.session + this.media.join('');
  7765. };
  7766. // translate a jingle content element into an an SDP media part
  7767. SDP.prototype.jingle2media = function (content) {
  7768. var media = '',
  7769. desc = content.find('description'),
  7770. ssrc = desc.attr('ssrc'),
  7771. self = this,
  7772. tmp;
  7773. var sctp = content.find(
  7774. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  7775. tmp = { media: desc.attr('media') };
  7776. tmp.port = '1';
  7777. if (content.attr('senders') == 'rejected') {
  7778. // estos hack to reject an m-line.
  7779. tmp.port = '0';
  7780. }
  7781. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  7782. if (sctp.length)
  7783. tmp.proto = 'DTLS/SCTP';
  7784. else
  7785. tmp.proto = 'RTP/SAVPF';
  7786. } else {
  7787. tmp.proto = 'RTP/AVPF';
  7788. }
  7789. if (!sctp.length) {
  7790. tmp.fmt = desc.find('payload-type').map(
  7791. function () { return this.getAttribute('id'); }).get();
  7792. media += SDPUtil.build_mline(tmp) + '\r\n';
  7793. } else {
  7794. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  7795. media += 'a=sctpmap:' + sctp.attr('number') +
  7796. ' ' + sctp.attr('protocol');
  7797. var streamCount = sctp.attr('streams');
  7798. if (streamCount)
  7799. media += ' ' + streamCount + '\r\n';
  7800. else
  7801. media += '\r\n';
  7802. }
  7803. media += 'c=IN IP4 0.0.0.0\r\n';
  7804. if (!sctp.length)
  7805. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  7806. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  7807. if (tmp.length) {
  7808. if (tmp.attr('ufrag')) {
  7809. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  7810. }
  7811. if (tmp.attr('pwd')) {
  7812. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  7813. }
  7814. tmp.find('>fingerprint').each(function () {
  7815. // FIXME: check namespace at some point
  7816. media += 'a=fingerprint:' + this.getAttribute('hash');
  7817. media += ' ' + $(this).text();
  7818. media += '\r\n';
  7819. if (this.getAttribute('setup')) {
  7820. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  7821. }
  7822. });
  7823. }
  7824. switch (content.attr('senders')) {
  7825. case 'initiator':
  7826. media += 'a=sendonly\r\n';
  7827. break;
  7828. case 'responder':
  7829. media += 'a=recvonly\r\n';
  7830. break;
  7831. case 'none':
  7832. media += 'a=inactive\r\n';
  7833. break;
  7834. case 'both':
  7835. media += 'a=sendrecv\r\n';
  7836. break;
  7837. }
  7838. media += 'a=mid:' + content.attr('name') + '\r\n';
  7839. // <description><rtcp-mux/></description>
  7840. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  7841. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  7842. if (desc.find('rtcp-mux').length) {
  7843. media += 'a=rtcp-mux\r\n';
  7844. }
  7845. if (desc.find('encryption').length) {
  7846. desc.find('encryption>crypto').each(function () {
  7847. media += 'a=crypto:' + this.getAttribute('tag');
  7848. media += ' ' + this.getAttribute('crypto-suite');
  7849. media += ' ' + this.getAttribute('key-params');
  7850. if (this.getAttribute('session-params')) {
  7851. media += ' ' + this.getAttribute('session-params');
  7852. }
  7853. media += '\r\n';
  7854. });
  7855. }
  7856. desc.find('payload-type').each(function () {
  7857. media += SDPUtil.build_rtpmap(this) + '\r\n';
  7858. if ($(this).find('>parameter').length) {
  7859. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  7860. media += $(this).find('parameter').map(function () {
  7861. return (this.getAttribute('name')
  7862. ? (this.getAttribute('name') + '=') : '') +
  7863. this.getAttribute('value');
  7864. }).get().join('; ');
  7865. media += '\r\n';
  7866. }
  7867. // xep-0293
  7868. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  7869. });
  7870. // xep-0293
  7871. media += self.rtcpFbFromJingle(desc, '*');
  7872. // xep-0294
  7873. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  7874. tmp.each(function () {
  7875. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  7876. });
  7877. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  7878. var protocol = this.getAttribute('protocol');
  7879. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  7880. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  7881. (self.removeUdpCandidates && protocol === 'udp')) {
  7882. return;
  7883. }
  7884. media += SDPUtil.candidateFromJingle(this);
  7885. });
  7886. // XEP-0339 handle ssrc-group attributes
  7887. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7888. var semantics = this.getAttribute('semantics');
  7889. var ssrcs = $(this).find('>source').map(function() {
  7890. return this.getAttribute('ssrc');
  7891. }).get();
  7892. if (ssrcs.length) {
  7893. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7894. }
  7895. });
  7896. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7897. tmp.each(function () {
  7898. var ssrc = this.getAttribute('ssrc');
  7899. $(this).find('>parameter').each(function () {
  7900. var name = this.getAttribute('name');
  7901. var value = this.getAttribute('value');
  7902. value = SDPUtil.filter_special_chars(value);
  7903. media += 'a=ssrc:' + ssrc + ' ' + name;
  7904. if (value && value.length)
  7905. media += ':' + value;
  7906. media += '\r\n';
  7907. });
  7908. });
  7909. return media;
  7910. };
  7911. module.exports = SDP;
  7912. }).call(this,"/modules/xmpp/SDP.js")
  7913. },{"./SDPUtil":32,"jitsi-meet-logger":47}],31:[function(require,module,exports){
  7914. var SDPUtil = require("./SDPUtil");
  7915. function SDPDiffer(mySDP, otherSDP)
  7916. {
  7917. this.mySDP = mySDP;
  7918. this.otherSDP = otherSDP;
  7919. }
  7920. /**
  7921. * Returns map of MediaChannel that contains media contained in
  7922. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  7923. */
  7924. SDPDiffer.prototype.getNewMedia = function() {
  7925. // this could be useful in Array.prototype.
  7926. function arrayEquals(array) {
  7927. // if the other array is a falsy value, return
  7928. if (!array)
  7929. return false;
  7930. // compare lengths - can save a lot of time
  7931. if (this.length != array.length)
  7932. return false;
  7933. for (var i = 0, l=this.length; i < l; i++) {
  7934. // Check if we have nested arrays
  7935. if (this[i] instanceof Array && array[i] instanceof Array) {
  7936. // recurse into the nested arrays
  7937. if (!this[i].equals(array[i]))
  7938. return false;
  7939. }
  7940. else if (this[i] != array[i]) {
  7941. // Warning - two different object instances will never be
  7942. // equal: {x:20} != {x:20}
  7943. return false;
  7944. }
  7945. }
  7946. return true;
  7947. }
  7948. var myMedias = this.mySDP.getMediaSsrcMap();
  7949. var othersMedias = this.otherSDP.getMediaSsrcMap();
  7950. var newMedia = {};
  7951. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  7952. var myMedia = myMedias[othersMediaIdx];
  7953. var othersMedia = othersMedias[othersMediaIdx];
  7954. if(!myMedia && othersMedia) {
  7955. // Add whole channel
  7956. newMedia[othersMediaIdx] = othersMedia;
  7957. return;
  7958. }
  7959. // Look for new ssrcs across the channel
  7960. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  7961. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  7962. // Allocate channel if we've found ssrc that doesn't exist in
  7963. // our channel
  7964. if(!newMedia[othersMediaIdx]){
  7965. newMedia[othersMediaIdx] = {
  7966. mediaindex: othersMedia.mediaindex,
  7967. mid: othersMedia.mid,
  7968. ssrcs: {},
  7969. ssrcGroups: []
  7970. };
  7971. }
  7972. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  7973. }
  7974. });
  7975. // Look for new ssrc groups across the channels
  7976. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  7977. // try to match the other ssrc-group with an ssrc-group of ours
  7978. var matched = false;
  7979. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  7980. var mySsrcGroup = myMedia.ssrcGroups[i];
  7981. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  7982. arrayEquals.apply(otherSsrcGroup.ssrcs,
  7983. [mySsrcGroup.ssrcs])) {
  7984. matched = true;
  7985. break;
  7986. }
  7987. }
  7988. if (!matched) {
  7989. // Allocate channel if we've found an ssrc-group that doesn't
  7990. // exist in our channel
  7991. if(!newMedia[othersMediaIdx]){
  7992. newMedia[othersMediaIdx] = {
  7993. mediaindex: othersMedia.mediaindex,
  7994. mid: othersMedia.mid,
  7995. ssrcs: {},
  7996. ssrcGroups: []
  7997. };
  7998. }
  7999. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  8000. }
  8001. });
  8002. });
  8003. return newMedia;
  8004. };
  8005. /**
  8006. * TODO: document!
  8007. */
  8008. SDPDiffer.prototype.toJingle = function(modify) {
  8009. var sdpMediaSsrcs = this.getNewMedia();
  8010. var modified = false;
  8011. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8012. modified = true;
  8013. var media = sdpMediaSsrcs[mediaindex];
  8014. modify.c('content', {name: media.mid});
  8015. modify.c('description',
  8016. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8017. // FIXME: not completely sure this operates on blocks and / or handles
  8018. // different ssrcs correctly
  8019. // generate sources from lines
  8020. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8021. var mediaSsrc = media.ssrcs[ssrcNum];
  8022. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8023. modify.attrs({ssrc: mediaSsrc.ssrc});
  8024. // iterate over ssrc lines
  8025. mediaSsrc.lines.forEach(function (line) {
  8026. var idx = line.indexOf(' ');
  8027. var kv = line.substr(idx + 1);
  8028. modify.c('parameter');
  8029. if (kv.indexOf(':') == -1) {
  8030. modify.attrs({ name: kv });
  8031. } else {
  8032. var nv = kv.split(':', 2);
  8033. var name = nv[0];
  8034. var value = SDPUtil.filter_special_chars(nv[1]);
  8035. modify.attrs({ name: name });
  8036. modify.attrs({ value: value });
  8037. }
  8038. modify.up(); // end of parameter
  8039. });
  8040. modify.up(); // end of source
  8041. });
  8042. // generate source groups from lines
  8043. media.ssrcGroups.forEach(function(ssrcGroup) {
  8044. if (ssrcGroup.ssrcs.length) {
  8045. modify.c('ssrc-group', {
  8046. semantics: ssrcGroup.semantics,
  8047. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8048. });
  8049. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8050. modify.c('source', { ssrc: ssrc })
  8051. .up(); // end of source
  8052. });
  8053. modify.up(); // end of ssrc-group
  8054. }
  8055. });
  8056. modify.up(); // end of description
  8057. modify.up(); // end of content
  8058. });
  8059. return modified;
  8060. };
  8061. module.exports = SDPDiffer;
  8062. },{"./SDPUtil":32}],32:[function(require,module,exports){
  8063. (function (__filename){
  8064. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8065. var RTCBrowserType = require("../RTC/RTCBrowserType");
  8066. SDPUtil = {
  8067. filter_special_chars: function (text) {
  8068. return text.replace(/[\\\/\{,\}\+]/g, "");
  8069. },
  8070. iceparams: function (mediadesc, sessiondesc) {
  8071. var data = null;
  8072. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8073. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8074. data = {
  8075. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8076. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8077. };
  8078. }
  8079. return data;
  8080. },
  8081. parse_iceufrag: function (line) {
  8082. return line.substring(12);
  8083. },
  8084. build_iceufrag: function (frag) {
  8085. return 'a=ice-ufrag:' + frag;
  8086. },
  8087. parse_icepwd: function (line) {
  8088. return line.substring(10);
  8089. },
  8090. build_icepwd: function (pwd) {
  8091. return 'a=ice-pwd:' + pwd;
  8092. },
  8093. parse_mid: function (line) {
  8094. return line.substring(6);
  8095. },
  8096. parse_mline: function (line) {
  8097. var parts = line.substring(2).split(' '),
  8098. data = {};
  8099. data.media = parts.shift();
  8100. data.port = parts.shift();
  8101. data.proto = parts.shift();
  8102. if (parts[parts.length - 1] === '') { // trailing whitespace
  8103. parts.pop();
  8104. }
  8105. data.fmt = parts;
  8106. return data;
  8107. },
  8108. build_mline: function (mline) {
  8109. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8110. },
  8111. parse_rtpmap: function (line) {
  8112. var parts = line.substring(9).split(' '),
  8113. data = {};
  8114. data.id = parts.shift();
  8115. parts = parts[0].split('/');
  8116. data.name = parts.shift();
  8117. data.clockrate = parts.shift();
  8118. data.channels = parts.length ? parts.shift() : '1';
  8119. return data;
  8120. },
  8121. /**
  8122. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8123. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8124. * @returns [SCTP port number, protocol, streams]
  8125. */
  8126. parse_sctpmap: function (line)
  8127. {
  8128. var parts = line.substring(10).split(' ');
  8129. var sctpPort = parts[0];
  8130. var protocol = parts[1];
  8131. // Stream count is optional
  8132. var streamCount = parts.length > 2 ? parts[2] : null;
  8133. return [sctpPort, protocol, streamCount];// SCTP port
  8134. },
  8135. build_rtpmap: function (el) {
  8136. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8137. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8138. line += '/' + el.getAttribute('channels');
  8139. }
  8140. return line;
  8141. },
  8142. parse_crypto: function (line) {
  8143. var parts = line.substring(9).split(' '),
  8144. data = {};
  8145. data.tag = parts.shift();
  8146. data['crypto-suite'] = parts.shift();
  8147. data['key-params'] = parts.shift();
  8148. if (parts.length) {
  8149. data['session-params'] = parts.join(' ');
  8150. }
  8151. return data;
  8152. },
  8153. parse_fingerprint: function (line) { // RFC 4572
  8154. var parts = line.substring(14).split(' '),
  8155. data = {};
  8156. data.hash = parts.shift();
  8157. data.fingerprint = parts.shift();
  8158. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8159. return data;
  8160. },
  8161. parse_fmtp: function (line) {
  8162. var parts = line.split(' '),
  8163. i, key, value,
  8164. data = [];
  8165. parts.shift();
  8166. parts = parts.join(' ').split(';');
  8167. for (i = 0; i < parts.length; i++) {
  8168. key = parts[i].split('=')[0];
  8169. while (key.length && key[0] == ' ') {
  8170. key = key.substring(1);
  8171. }
  8172. value = parts[i].split('=')[1];
  8173. if (key && value) {
  8174. data.push({name: key, value: value});
  8175. } else if (key) {
  8176. // rfc 4733 (DTMF) style stuff
  8177. data.push({name: '', value: key});
  8178. }
  8179. }
  8180. return data;
  8181. },
  8182. parse_icecandidate: function (line) {
  8183. var candidate = {},
  8184. elems = line.split(' ');
  8185. candidate.foundation = elems[0].substring(12);
  8186. candidate.component = elems[1];
  8187. candidate.protocol = elems[2].toLowerCase();
  8188. candidate.priority = elems[3];
  8189. candidate.ip = elems[4];
  8190. candidate.port = elems[5];
  8191. // elems[6] => "typ"
  8192. candidate.type = elems[7];
  8193. candidate.generation = 0; // default value, may be overwritten below
  8194. for (var i = 8; i < elems.length; i += 2) {
  8195. switch (elems[i]) {
  8196. case 'raddr':
  8197. candidate['rel-addr'] = elems[i + 1];
  8198. break;
  8199. case 'rport':
  8200. candidate['rel-port'] = elems[i + 1];
  8201. break;
  8202. case 'generation':
  8203. candidate.generation = elems[i + 1];
  8204. break;
  8205. case 'tcptype':
  8206. candidate.tcptype = elems[i + 1];
  8207. break;
  8208. default: // TODO
  8209. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8210. }
  8211. }
  8212. candidate.network = '1';
  8213. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8214. return candidate;
  8215. },
  8216. build_icecandidate: function (cand) {
  8217. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8218. line += ' ';
  8219. switch (cand.type) {
  8220. case 'srflx':
  8221. case 'prflx':
  8222. case 'relay':
  8223. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8224. line += 'raddr';
  8225. line += ' ';
  8226. line += cand['rel-addr'];
  8227. line += ' ';
  8228. line += 'rport';
  8229. line += ' ';
  8230. line += cand['rel-port'];
  8231. line += ' ';
  8232. }
  8233. break;
  8234. }
  8235. if (cand.hasOwnAttribute('tcptype')) {
  8236. line += 'tcptype';
  8237. line += ' ';
  8238. line += cand.tcptype;
  8239. line += ' ';
  8240. }
  8241. line += 'generation';
  8242. line += ' ';
  8243. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8244. return line;
  8245. },
  8246. parse_ssrc: function (desc) {
  8247. // proprietary mapping of a=ssrc lines
  8248. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8249. // and parse according to that
  8250. var lines = desc.split('\r\n'),
  8251. data = {};
  8252. for (var i = 0; i < lines.length; i++) {
  8253. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8254. var idx = lines[i].indexOf(' ');
  8255. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8256. }
  8257. }
  8258. return data;
  8259. },
  8260. parse_rtcpfb: function (line) {
  8261. var parts = line.substr(10).split(' ');
  8262. var data = {};
  8263. data.pt = parts.shift();
  8264. data.type = parts.shift();
  8265. data.params = parts;
  8266. return data;
  8267. },
  8268. parse_extmap: function (line) {
  8269. var parts = line.substr(9).split(' ');
  8270. var data = {};
  8271. data.value = parts.shift();
  8272. if (data.value.indexOf('/') != -1) {
  8273. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8274. data.value = data.value.substr(0, data.value.indexOf('/'));
  8275. } else {
  8276. data.direction = 'both';
  8277. }
  8278. data.uri = parts.shift();
  8279. data.params = parts;
  8280. return data;
  8281. },
  8282. find_line: function (haystack, needle, sessionpart) {
  8283. var lines = haystack.split('\r\n');
  8284. for (var i = 0; i < lines.length; i++) {
  8285. if (lines[i].substring(0, needle.length) == needle) {
  8286. return lines[i];
  8287. }
  8288. }
  8289. if (!sessionpart) {
  8290. return false;
  8291. }
  8292. // search session part
  8293. lines = sessionpart.split('\r\n');
  8294. for (var j = 0; j < lines.length; j++) {
  8295. if (lines[j].substring(0, needle.length) == needle) {
  8296. return lines[j];
  8297. }
  8298. }
  8299. return false;
  8300. },
  8301. find_lines: function (haystack, needle, sessionpart) {
  8302. var lines = haystack.split('\r\n'),
  8303. needles = [];
  8304. for (var i = 0; i < lines.length; i++) {
  8305. if (lines[i].substring(0, needle.length) == needle)
  8306. needles.push(lines[i]);
  8307. }
  8308. if (needles.length || !sessionpart) {
  8309. return needles;
  8310. }
  8311. // search session part
  8312. lines = sessionpart.split('\r\n');
  8313. for (var j = 0; j < lines.length; j++) {
  8314. if (lines[j].substring(0, needle.length) == needle) {
  8315. needles.push(lines[j]);
  8316. }
  8317. }
  8318. return needles;
  8319. },
  8320. candidateToJingle: function (line) {
  8321. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8322. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8323. if (line.indexOf('candidate:') === 0) {
  8324. line = 'a=' + line;
  8325. } else if (line.substring(0, 12) != 'a=candidate:') {
  8326. logger.log('parseCandidate called with a line that is not a candidate line');
  8327. logger.log(line);
  8328. return null;
  8329. }
  8330. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8331. line = line.substring(0, line.length - 2);
  8332. var candidate = {},
  8333. elems = line.split(' '),
  8334. i;
  8335. if (elems[6] != 'typ') {
  8336. logger.log('did not find typ in the right place');
  8337. logger.log(line);
  8338. return null;
  8339. }
  8340. candidate.foundation = elems[0].substring(12);
  8341. candidate.component = elems[1];
  8342. candidate.protocol = elems[2].toLowerCase();
  8343. candidate.priority = elems[3];
  8344. candidate.ip = elems[4];
  8345. candidate.port = elems[5];
  8346. // elems[6] => "typ"
  8347. candidate.type = elems[7];
  8348. candidate.generation = '0'; // default, may be overwritten below
  8349. for (i = 8; i < elems.length; i += 2) {
  8350. switch (elems[i]) {
  8351. case 'raddr':
  8352. candidate['rel-addr'] = elems[i + 1];
  8353. break;
  8354. case 'rport':
  8355. candidate['rel-port'] = elems[i + 1];
  8356. break;
  8357. case 'generation':
  8358. candidate.generation = elems[i + 1];
  8359. break;
  8360. case 'tcptype':
  8361. candidate.tcptype = elems[i + 1];
  8362. break;
  8363. default: // TODO
  8364. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8365. }
  8366. }
  8367. candidate.network = '1';
  8368. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8369. return candidate;
  8370. },
  8371. candidateFromJingle: function (cand) {
  8372. var line = 'a=candidate:';
  8373. line += cand.getAttribute('foundation');
  8374. line += ' ';
  8375. line += cand.getAttribute('component');
  8376. line += ' ';
  8377. var protocol = cand.getAttribute('protocol');
  8378. // use tcp candidates for FF
  8379. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  8380. protocol = 'tcp';
  8381. }
  8382. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  8383. line += ' ';
  8384. line += cand.getAttribute('priority');
  8385. line += ' ';
  8386. line += cand.getAttribute('ip');
  8387. line += ' ';
  8388. line += cand.getAttribute('port');
  8389. line += ' ';
  8390. line += 'typ';
  8391. line += ' ' + cand.getAttribute('type');
  8392. line += ' ';
  8393. switch (cand.getAttribute('type')) {
  8394. case 'srflx':
  8395. case 'prflx':
  8396. case 'relay':
  8397. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  8398. line += 'raddr';
  8399. line += ' ';
  8400. line += cand.getAttribute('rel-addr');
  8401. line += ' ';
  8402. line += 'rport';
  8403. line += ' ';
  8404. line += cand.getAttribute('rel-port');
  8405. line += ' ';
  8406. }
  8407. break;
  8408. }
  8409. if (protocol.toLowerCase() == 'tcp') {
  8410. line += 'tcptype';
  8411. line += ' ';
  8412. line += cand.getAttribute('tcptype');
  8413. line += ' ';
  8414. }
  8415. line += 'generation';
  8416. line += ' ';
  8417. line += cand.getAttribute('generation') || '0';
  8418. return line + '\r\n';
  8419. }
  8420. };
  8421. module.exports = SDPUtil;
  8422. }).call(this,"/modules/xmpp/SDPUtil.js")
  8423. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],33:[function(require,module,exports){
  8424. (function (__filename){
  8425. /* global $ */
  8426. var RTC = require('../RTC/RTC');
  8427. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8428. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  8429. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8430. var SSRCReplacement = require("./LocalSSRCReplacement");
  8431. function TraceablePeerConnection(ice_config, constraints, session) {
  8432. var self = this;
  8433. this.session = session;
  8434. var RTCPeerConnectionType = null;
  8435. if (RTCBrowserType.isFirefox()) {
  8436. RTCPeerConnectionType = mozRTCPeerConnection;
  8437. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  8438. RTCPeerConnectionType = RTCPeerConnection;
  8439. } else {
  8440. RTCPeerConnectionType = webkitRTCPeerConnection;
  8441. }
  8442. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  8443. this.updateLog = [];
  8444. this.stats = {};
  8445. this.statsinterval = null;
  8446. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  8447. var Interop = require('sdp-interop').Interop;
  8448. this.interop = new Interop();
  8449. var Simulcast = require('sdp-simulcast');
  8450. this.simulcast = new Simulcast({numOfLayers: 2, explodeRemoteSimulcast: false});
  8451. // override as desired
  8452. this.trace = function (what, info) {
  8453. /*logger.warn('WTRACE', what, info);
  8454. if (info && RTCBrowserType.isIExplorer()) {
  8455. if (info.length > 1024) {
  8456. logger.warn('WTRACE', what, info.substr(1024));
  8457. }
  8458. if (info.length > 2048) {
  8459. logger.warn('WTRACE', what, info.substr(2048));
  8460. }
  8461. }*/
  8462. self.updateLog.push({
  8463. time: new Date(),
  8464. type: what,
  8465. value: info || ""
  8466. });
  8467. };
  8468. this.onicecandidate = null;
  8469. this.peerconnection.onicecandidate = function (event) {
  8470. // FIXME: this causes stack overflow with Temasys Plugin
  8471. if (!RTCBrowserType.isTemasysPluginUsed())
  8472. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  8473. if (self.onicecandidate !== null) {
  8474. self.onicecandidate(event);
  8475. }
  8476. };
  8477. this.onaddstream = null;
  8478. this.peerconnection.onaddstream = function (event) {
  8479. self.trace('onaddstream', event.stream.id);
  8480. if (self.onaddstream !== null) {
  8481. self.onaddstream(event);
  8482. }
  8483. };
  8484. this.onremovestream = null;
  8485. this.peerconnection.onremovestream = function (event) {
  8486. self.trace('onremovestream', event.stream.id);
  8487. if (self.onremovestream !== null) {
  8488. self.onremovestream(event);
  8489. }
  8490. };
  8491. this.onsignalingstatechange = null;
  8492. this.peerconnection.onsignalingstatechange = function (event) {
  8493. self.trace('onsignalingstatechange', self.signalingState);
  8494. if (self.onsignalingstatechange !== null) {
  8495. self.onsignalingstatechange(event);
  8496. }
  8497. };
  8498. this.oniceconnectionstatechange = null;
  8499. this.peerconnection.oniceconnectionstatechange = function (event) {
  8500. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  8501. if (self.oniceconnectionstatechange !== null) {
  8502. self.oniceconnectionstatechange(event);
  8503. }
  8504. };
  8505. this.onnegotiationneeded = null;
  8506. this.peerconnection.onnegotiationneeded = function (event) {
  8507. self.trace('onnegotiationneeded');
  8508. if (self.onnegotiationneeded !== null) {
  8509. self.onnegotiationneeded(event);
  8510. }
  8511. };
  8512. self.ondatachannel = null;
  8513. this.peerconnection.ondatachannel = function (event) {
  8514. self.trace('ondatachannel', event);
  8515. if (self.ondatachannel !== null) {
  8516. self.ondatachannel(event);
  8517. }
  8518. };
  8519. // XXX: do all non-firefox browsers which we support also support this?
  8520. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  8521. this.statsinterval = window.setInterval(function() {
  8522. self.peerconnection.getStats(function(stats) {
  8523. var results = stats.result();
  8524. var now = new Date();
  8525. for (var i = 0; i < results.length; ++i) {
  8526. results[i].names().forEach(function (name) {
  8527. var id = results[i].id + '-' + name;
  8528. if (!self.stats[id]) {
  8529. self.stats[id] = {
  8530. startTime: now,
  8531. endTime: now,
  8532. values: [],
  8533. times: []
  8534. };
  8535. }
  8536. self.stats[id].values.push(results[i].stat(name));
  8537. self.stats[id].times.push(now.getTime());
  8538. if (self.stats[id].values.length > self.maxstats) {
  8539. self.stats[id].values.shift();
  8540. self.stats[id].times.shift();
  8541. }
  8542. self.stats[id].endTime = now;
  8543. });
  8544. }
  8545. });
  8546. }, 1000);
  8547. }
  8548. }
  8549. /**
  8550. * Returns a string representation of a SessionDescription object.
  8551. */
  8552. var dumpSDP = function(description) {
  8553. if (typeof description === 'undefined' || description == null) {
  8554. return '';
  8555. }
  8556. return 'type: ' + description.type + '\r\n' + description.sdp;
  8557. };
  8558. /**
  8559. * Takes a SessionDescription object and returns a "normalized" version.
  8560. * Currently it only takes care of ordering the a=ssrc lines.
  8561. */
  8562. var normalizePlanB = function(desc) {
  8563. if (typeof desc !== 'object' || desc === null ||
  8564. typeof desc.sdp !== 'string') {
  8565. logger.warn('An empty description was passed as an argument.');
  8566. return desc;
  8567. }
  8568. var transform = require('sdp-transform');
  8569. var session = transform.parse(desc.sdp);
  8570. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  8571. Array.isArray(session.media)) {
  8572. session.media.forEach(function (mLine) {
  8573. // Chrome appears to be picky about the order in which a=ssrc lines
  8574. // are listed in an m-line when rtx is enabled (and thus there are
  8575. // a=ssrc-group lines with FID semantics). Specifically if we have
  8576. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  8577. // the "a=ssrc:S1" lines, SRD fails.
  8578. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  8579. // first.
  8580. var firstSsrcs = [];
  8581. var newSsrcLines = [];
  8582. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  8583. mLine.ssrcGroups.forEach(function (group) {
  8584. if (typeof group.semantics !== 'undefined' &&
  8585. group.semantics === 'FID') {
  8586. if (typeof group.ssrcs !== 'undefined') {
  8587. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  8588. }
  8589. }
  8590. });
  8591. }
  8592. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  8593. var i;
  8594. for (i = 0; i<mLine.ssrcs.length; i++){
  8595. if (typeof mLine.ssrcs[i] === 'object'
  8596. && typeof mLine.ssrcs[i].id !== 'undefined'
  8597. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  8598. newSsrcLines.push(mLine.ssrcs[i]);
  8599. delete mLine.ssrcs[i];
  8600. }
  8601. }
  8602. for (i = 0; i<mLine.ssrcs.length; i++){
  8603. if (typeof mLine.ssrcs[i] !== 'undefined') {
  8604. newSsrcLines.push(mLine.ssrcs[i]);
  8605. }
  8606. }
  8607. mLine.ssrcs = newSsrcLines;
  8608. }
  8609. });
  8610. }
  8611. var resStr = transform.write(session);
  8612. return new RTCSessionDescription({
  8613. type: desc.type,
  8614. sdp: resStr
  8615. });
  8616. };
  8617. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  8618. TraceablePeerConnection.prototype.__defineGetter__(
  8619. 'signalingState',
  8620. function() { return this.peerconnection.signalingState; });
  8621. TraceablePeerConnection.prototype.__defineGetter__(
  8622. 'iceConnectionState',
  8623. function() { return this.peerconnection.iceConnectionState; });
  8624. TraceablePeerConnection.prototype.__defineGetter__(
  8625. 'localDescription',
  8626. function() {
  8627. var desc = this.peerconnection.localDescription;
  8628. // FIXME this should probably be after the Unified Plan -> Plan B
  8629. // transformation.
  8630. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  8631. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  8632. // if we're running on FF, transform to Plan B first.
  8633. if (RTCBrowserType.usesUnifiedPlan()) {
  8634. desc = this.interop.toPlanB(desc);
  8635. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  8636. }
  8637. return desc;
  8638. });
  8639. TraceablePeerConnection.prototype.__defineGetter__(
  8640. 'remoteDescription',
  8641. function() {
  8642. var desc = this.peerconnection.remoteDescription;
  8643. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  8644. // if we're running on FF, transform to Plan B first.
  8645. if (RTCBrowserType.usesUnifiedPlan()) {
  8646. desc = this.interop.toPlanB(desc);
  8647. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  8648. }
  8649. return desc;
  8650. });
  8651. }
  8652. TraceablePeerConnection.prototype.addStream = function (stream) {
  8653. this.trace('addStream', stream.id);
  8654. try
  8655. {
  8656. this.peerconnection.addStream(stream);
  8657. }
  8658. catch (e)
  8659. {
  8660. logger.error(e);
  8661. }
  8662. };
  8663. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  8664. this.trace('removeStream', stream.id);
  8665. if(stopStreams) {
  8666. RTC.stopMediaStream(stream);
  8667. }
  8668. try {
  8669. // FF doesn't support this yet.
  8670. if (this.peerconnection.removeStream)
  8671. this.peerconnection.removeStream(stream);
  8672. } catch (e) {
  8673. logger.error(e);
  8674. }
  8675. };
  8676. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  8677. this.trace('createDataChannel', label, opts);
  8678. return this.peerconnection.createDataChannel(label, opts);
  8679. };
  8680. TraceablePeerConnection.prototype.setLocalDescription
  8681. = function (description, successCallback, failureCallback) {
  8682. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  8683. // if we're running on FF, transform to Plan A first.
  8684. if (RTCBrowserType.usesUnifiedPlan()) {
  8685. description = this.interop.toUnifiedPlan(description);
  8686. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  8687. }
  8688. var self = this;
  8689. this.peerconnection.setLocalDescription(description,
  8690. function () {
  8691. self.trace('setLocalDescriptionOnSuccess');
  8692. successCallback();
  8693. },
  8694. function (err) {
  8695. self.trace('setLocalDescriptionOnFailure', err);
  8696. failureCallback(err);
  8697. }
  8698. );
  8699. /*
  8700. if (this.statsinterval === null && this.maxstats > 0) {
  8701. // start gathering stats
  8702. }
  8703. */
  8704. };
  8705. TraceablePeerConnection.prototype.setRemoteDescription
  8706. = function (description, successCallback, failureCallback) {
  8707. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  8708. // TODO the focus should squeze or explode the remote simulcast
  8709. description = this.simulcast.mungeRemoteDescription(description);
  8710. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  8711. // if we're running on FF, transform to Plan A first.
  8712. if (RTCBrowserType.usesUnifiedPlan()) {
  8713. description = this.interop.toUnifiedPlan(description);
  8714. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  8715. }
  8716. if (RTCBrowserType.usesPlanB()) {
  8717. description = normalizePlanB(description);
  8718. }
  8719. var self = this;
  8720. this.peerconnection.setRemoteDescription(description,
  8721. function () {
  8722. self.trace('setRemoteDescriptionOnSuccess');
  8723. successCallback();
  8724. },
  8725. function (err) {
  8726. self.trace('setRemoteDescriptionOnFailure', err);
  8727. failureCallback(err);
  8728. }
  8729. );
  8730. /*
  8731. if (this.statsinterval === null && this.maxstats > 0) {
  8732. // start gathering stats
  8733. }
  8734. */
  8735. };
  8736. TraceablePeerConnection.prototype.close = function () {
  8737. this.trace('stop');
  8738. if (this.statsinterval !== null) {
  8739. window.clearInterval(this.statsinterval);
  8740. this.statsinterval = null;
  8741. }
  8742. this.peerconnection.close();
  8743. };
  8744. TraceablePeerConnection.prototype.createOffer
  8745. = function (successCallback, failureCallback, constraints) {
  8746. var self = this;
  8747. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  8748. this.peerconnection.createOffer(
  8749. function (offer) {
  8750. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  8751. // NOTE this is not tested because in meet the focus generates the
  8752. // offer.
  8753. // if we're running on FF, transform to Plan B first.
  8754. if (RTCBrowserType.usesUnifiedPlan()) {
  8755. offer = self.interop.toPlanB(offer);
  8756. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  8757. }
  8758. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  8759. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8760. offer = self.simulcast.mungeLocalDescription(offer);
  8761. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  8762. }
  8763. successCallback(offer);
  8764. },
  8765. function(err) {
  8766. self.trace('createOfferOnFailure', err);
  8767. failureCallback(err);
  8768. },
  8769. constraints
  8770. );
  8771. };
  8772. TraceablePeerConnection.prototype.createAnswer
  8773. = function (successCallback, failureCallback, constraints) {
  8774. var self = this;
  8775. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  8776. this.peerconnection.createAnswer(
  8777. function (answer) {
  8778. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  8779. // if we're running on FF, transform to Plan A first.
  8780. if (RTCBrowserType.usesUnifiedPlan()) {
  8781. answer = self.interop.toPlanB(answer);
  8782. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  8783. }
  8784. // munge local video SSRC
  8785. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  8786. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8787. answer = self.simulcast.mungeLocalDescription(answer);
  8788. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  8789. }
  8790. successCallback(answer);
  8791. },
  8792. function(err) {
  8793. self.trace('createAnswerOnFailure', err);
  8794. failureCallback(err);
  8795. },
  8796. constraints
  8797. );
  8798. };
  8799. TraceablePeerConnection.prototype.addIceCandidate
  8800. = function (candidate, successCallback, failureCallback) {
  8801. //var self = this;
  8802. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  8803. this.peerconnection.addIceCandidate(candidate);
  8804. /* maybe later
  8805. this.peerconnection.addIceCandidate(candidate,
  8806. function () {
  8807. self.trace('addIceCandidateOnSuccess');
  8808. successCallback();
  8809. },
  8810. function (err) {
  8811. self.trace('addIceCandidateOnFailure', err);
  8812. failureCallback(err);
  8813. }
  8814. );
  8815. */
  8816. };
  8817. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  8818. // TODO: Is this the correct way to handle Opera, Temasys?
  8819. if (RTCBrowserType.isFirefox()) {
  8820. // ignore for now...
  8821. if(!errback)
  8822. errback = function () {};
  8823. this.peerconnection.getStats(null, callback, errback);
  8824. } else {
  8825. this.peerconnection.getStats(callback);
  8826. }
  8827. };
  8828. module.exports = TraceablePeerConnection;
  8829. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  8830. },{"../../service/xmpp/XMPPEvents":86,"../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){
  8831. (function (__filename){
  8832. /* global $, $iq, APP, config, messageHandler,
  8833. roomName, sessionTerminated, Strophe, Util */
  8834. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8835. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8836. var Settings = require("../settings/Settings");
  8837. var AuthenticationEvents
  8838. = require("../../service/authentication/AuthenticationEvents");
  8839. function createExpBackoffTimer(step) {
  8840. var count = 1;
  8841. return function (reset) {
  8842. // Reset call
  8843. if (reset) {
  8844. count = 1;
  8845. return;
  8846. }
  8847. // Calculate next timeout
  8848. var timeout = Math.pow(2, count - 1);
  8849. count += 1;
  8850. return timeout * step;
  8851. };
  8852. }
  8853. function Moderator(roomName, xmpp, emitter) {
  8854. this.roomName = roomName;
  8855. this.xmppService = xmpp;
  8856. this.getNextTimeout = createExpBackoffTimer(1000);
  8857. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  8858. // External authentication stuff
  8859. this.externalAuthEnabled = false;
  8860. this.settings = new Settings(roomName);
  8861. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  8862. // it will be enabled automatically if focus detects the component through
  8863. // service discovery.
  8864. this.sipGatewayEnabled =
  8865. this.xmppService.options.hosts.call_control !== undefined;
  8866. this.eventEmitter = emitter;
  8867. this.connection = this.xmppService.connection;
  8868. this.focusUserJid;
  8869. //FIXME:
  8870. // Message listener that talks to POPUP window
  8871. function listener(event) {
  8872. if (event.data && event.data.sessionId) {
  8873. if (event.origin !== window.location.origin) {
  8874. logger.warn("Ignoring sessionId from different origin: " +
  8875. event.origin);
  8876. return;
  8877. }
  8878. localStorage.setItem('sessionId', event.data.sessionId);
  8879. // After popup is closed we will authenticate
  8880. }
  8881. }
  8882. // Register
  8883. if (window.addEventListener) {
  8884. window.addEventListener("message", listener, false);
  8885. } else {
  8886. window.attachEvent("onmessage", listener);
  8887. }
  8888. }
  8889. Moderator.prototype.isExternalAuthEnabled = function () {
  8890. return this.externalAuthEnabled;
  8891. };
  8892. Moderator.prototype.isSipGatewayEnabled = function () {
  8893. return this.sipGatewayEnabled;
  8894. };
  8895. Moderator.prototype.onMucMemberLeft = function (jid) {
  8896. logger.info("Someone left is it focus ? " + jid);
  8897. var resource = Strophe.getResourceFromJid(jid);
  8898. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  8899. logger.info(
  8900. "Focus has left the room - leaving conference");
  8901. //hangUp();
  8902. // We'd rather reload to have everything re-initialized
  8903. //FIXME: show some message before reload
  8904. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  8905. }
  8906. };
  8907. Moderator.prototype.setFocusUserJid = function (focusJid) {
  8908. if (!this.focusUserJid) {
  8909. this.focusUserJid = focusJid;
  8910. logger.info("Focus jid set to: " + this.focusUserJid);
  8911. }
  8912. };
  8913. Moderator.prototype.getFocusUserJid = function () {
  8914. return this.focusUserJid;
  8915. };
  8916. Moderator.prototype.getFocusComponent = function () {
  8917. // Get focus component address
  8918. var focusComponent = this.xmppService.options.hosts.focus;
  8919. // If not specified use default: 'focus.domain'
  8920. if (!focusComponent) {
  8921. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  8922. }
  8923. return focusComponent;
  8924. };
  8925. Moderator.prototype.createConferenceIq = function () {
  8926. // Generate create conference IQ
  8927. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  8928. // Session Id used for authentication
  8929. var sessionId = localStorage.getItem('sessionId');
  8930. var machineUID = this.settings.getSettings().uid;
  8931. logger.info(
  8932. "Session ID: " + sessionId + " machine UID: " + machineUID);
  8933. elem.c('conference', {
  8934. xmlns: 'http://jitsi.org/protocol/focus',
  8935. room: this.roomName,
  8936. 'machine-uid': machineUID
  8937. });
  8938. if (sessionId) {
  8939. elem.attrs({ 'session-id': sessionId});
  8940. }
  8941. if (this.xmppService.options.hosts.bridge !== undefined) {
  8942. elem.c(
  8943. 'property', {
  8944. name: 'bridge',
  8945. value: this.xmppService.options.hosts.bridge
  8946. }).up();
  8947. }
  8948. // Tell the focus we have Jigasi configured
  8949. if (this.xmppService.options.hosts.call_control !== undefined) {
  8950. elem.c(
  8951. 'property', {
  8952. name: 'call_control',
  8953. value: this.xmppService.options.hosts.call_control
  8954. }).up();
  8955. }
  8956. if (this.xmppService.options.channelLastN !== undefined) {
  8957. elem.c(
  8958. 'property', {
  8959. name: 'channelLastN',
  8960. value: this.xmppService.options.channelLastN
  8961. }).up();
  8962. }
  8963. if (this.xmppService.options.adaptiveLastN !== undefined) {
  8964. elem.c(
  8965. 'property', {
  8966. name: 'adaptiveLastN',
  8967. value: this.xmppService.options.adaptiveLastN
  8968. }).up();
  8969. }
  8970. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  8971. elem.c(
  8972. 'property', {
  8973. name: 'adaptiveSimulcast',
  8974. value: this.xmppService.options.adaptiveSimulcast
  8975. }).up();
  8976. }
  8977. if (this.xmppService.options.openSctp !== undefined) {
  8978. elem.c(
  8979. 'property', {
  8980. name: 'openSctp',
  8981. value: this.xmppService.options.openSctp
  8982. }).up();
  8983. }
  8984. if (this.xmppService.options.startAudioMuted !== undefined)
  8985. {
  8986. elem.c(
  8987. 'property', {
  8988. name: 'startAudioMuted',
  8989. value: this.xmppService.options.startAudioMuted
  8990. }).up();
  8991. }
  8992. if (this.xmppService.options.startVideoMuted !== undefined)
  8993. {
  8994. elem.c(
  8995. 'property', {
  8996. name: 'startVideoMuted',
  8997. value: this.xmppService.options.startVideoMuted
  8998. }).up();
  8999. }
  9000. elem.c(
  9001. 'property', {
  9002. name: 'simulcastMode',
  9003. value: 'rewriting'
  9004. }).up();
  9005. elem.up();
  9006. return elem;
  9007. };
  9008. Moderator.prototype.parseSessionId = function (resultIq) {
  9009. var sessionId = $(resultIq).find('conference').attr('session-id');
  9010. if (sessionId) {
  9011. logger.info('Received sessionId: ' + sessionId);
  9012. localStorage.setItem('sessionId', sessionId);
  9013. }
  9014. };
  9015. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9016. this.setFocusUserJid(
  9017. $(resultIq).find('conference').attr('focusjid'));
  9018. var authenticationEnabled
  9019. = $(resultIq).find(
  9020. '>conference>property' +
  9021. '[name=\'authentication\'][value=\'true\']').length > 0;
  9022. logger.info("Authentication enabled: " + authenticationEnabled);
  9023. this.externalAuthEnabled = $(resultIq).find(
  9024. '>conference>property' +
  9025. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9026. console.info(
  9027. 'External authentication enabled: ' + this.externalAuthEnabled);
  9028. if (!this.externalAuthEnabled) {
  9029. // We expect to receive sessionId in 'internal' authentication mode
  9030. this.parseSessionId(resultIq);
  9031. }
  9032. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9033. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9034. authenticationEnabled, authIdentity);
  9035. // Check if focus has auto-detected Jigasi component(this will be also
  9036. // included if we have passed our host from the config)
  9037. if ($(resultIq).find(
  9038. '>conference>property' +
  9039. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9040. this.sipGatewayEnabled = true;
  9041. }
  9042. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9043. };
  9044. // FIXME = we need to show the fact that we're waiting for the focus
  9045. // to the user(or that focus is not available)
  9046. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9047. // Try to use focus user JID from the config
  9048. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9049. // Send create conference IQ
  9050. var iq = this.createConferenceIq();
  9051. var self = this;
  9052. this.connection.sendIQ(
  9053. iq,
  9054. function (result) {
  9055. // Setup config options
  9056. self.parseConfigOptions(result);
  9057. if ('true' === $(result).find('conference').attr('ready')) {
  9058. // Reset both timers
  9059. self.getNextTimeout(true);
  9060. self.getNextErrorTimeout(true);
  9061. // Exec callback
  9062. callback();
  9063. } else {
  9064. var waitMs = self.getNextTimeout();
  9065. logger.info("Waiting for the focus... " + waitMs);
  9066. // Reset error timeout
  9067. self.getNextErrorTimeout(true);
  9068. window.setTimeout(
  9069. function () {
  9070. self.allocateConferenceFocus(callback);
  9071. }, waitMs);
  9072. }
  9073. },
  9074. function (error) {
  9075. // Invalid session ? remove and try again
  9076. // without session ID to get a new one
  9077. var invalidSession
  9078. = $(error).find('>error>session-invalid').length;
  9079. if (invalidSession) {
  9080. logger.info("Session expired! - removing");
  9081. localStorage.removeItem("sessionId");
  9082. }
  9083. if ($(error).find('>error>graceful-shutdown').length) {
  9084. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9085. return;
  9086. }
  9087. // Check for error returned by the reservation system
  9088. var reservationErr = $(error).find('>error>reservation-error');
  9089. if (reservationErr.length) {
  9090. // Trigger error event
  9091. var errorCode = reservationErr.attr('error-code');
  9092. var errorMsg;
  9093. if ($(error).find('>error>text')) {
  9094. errorMsg = $(error).find('>error>text').text();
  9095. }
  9096. self.eventEmitter.emit(
  9097. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9098. return;
  9099. }
  9100. // Not authorized to create new room
  9101. if ($(error).find('>error>not-authorized').length) {
  9102. logger.warn("Unauthorized to start the conference", error);
  9103. var toDomain
  9104. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9105. if (toDomain !==
  9106. this.xmppService.options.hosts.anonymousdomain) {
  9107. //FIXME: "is external" should come either from
  9108. // the focus or config.js
  9109. self.externalAuthEnabled = true;
  9110. }
  9111. self.eventEmitter.emit(
  9112. XMPPEvents.AUTHENTICATION_REQUIRED,
  9113. function () {
  9114. self.allocateConferenceFocus(
  9115. callback);
  9116. });
  9117. return;
  9118. }
  9119. var waitMs = self.getNextErrorTimeout();
  9120. logger.error("Focus error, retry after " + waitMs, error);
  9121. // Show message
  9122. var focusComponent = self.getFocusComponent();
  9123. var retrySec = waitMs / 1000;
  9124. //FIXME: message is duplicated ?
  9125. // Do not show in case of session invalid
  9126. // which means just a retry
  9127. if (!invalidSession) {
  9128. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9129. focusComponent, retrySec);
  9130. }
  9131. // Reset response timeout
  9132. self.getNextTimeout(true);
  9133. window.setTimeout(
  9134. function () {
  9135. self.allocateConferenceFocus(callback);
  9136. }, waitMs);
  9137. }
  9138. );
  9139. };
  9140. Moderator.prototype.getLoginUrl = function (urlCallback) {
  9141. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9142. iq.c('login-url', {
  9143. xmlns: 'http://jitsi.org/protocol/focus',
  9144. room: this.roomName,
  9145. 'machine-uid': this.settings.getSettings().uid
  9146. });
  9147. this.connection.sendIQ(
  9148. iq,
  9149. function (result) {
  9150. var url = $(result).find('login-url').attr('url');
  9151. url = url = decodeURIComponent(url);
  9152. if (url) {
  9153. logger.info("Got auth url: " + url);
  9154. urlCallback(url);
  9155. } else {
  9156. logger.error(
  9157. "Failed to get auth url from the focus", result);
  9158. }
  9159. },
  9160. function (error) {
  9161. logger.error("Get auth url error", error);
  9162. }
  9163. );
  9164. };
  9165. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  9166. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9167. iq.c('login-url', {
  9168. xmlns: 'http://jitsi.org/protocol/focus',
  9169. room: this.roomName,
  9170. 'machine-uid': this.settings.getSettings().uid,
  9171. popup: true
  9172. });
  9173. this.connection.sendIQ(
  9174. iq,
  9175. function (result) {
  9176. var url = $(result).find('login-url').attr('url');
  9177. url = url = decodeURIComponent(url);
  9178. if (url) {
  9179. logger.info("Got POPUP auth url: " + url);
  9180. urlCallback(url);
  9181. } else {
  9182. logger.error(
  9183. "Failed to get POPUP auth url from the focus", result);
  9184. }
  9185. },
  9186. function (error) {
  9187. logger.error('Get POPUP auth url error', error);
  9188. }
  9189. );
  9190. };
  9191. Moderator.prototype.logout = function (callback) {
  9192. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9193. var sessionId = localStorage.getItem('sessionId');
  9194. if (!sessionId) {
  9195. callback();
  9196. return;
  9197. }
  9198. iq.c('logout', {
  9199. xmlns: 'http://jitsi.org/protocol/focus',
  9200. 'session-id': sessionId
  9201. });
  9202. this.connection.sendIQ(
  9203. iq,
  9204. function (result) {
  9205. var logoutUrl = $(result).find('logout').attr('logout-url');
  9206. if (logoutUrl) {
  9207. logoutUrl = decodeURIComponent(logoutUrl);
  9208. }
  9209. logger.info("Log out OK, url: " + logoutUrl, result);
  9210. localStorage.removeItem('sessionId');
  9211. callback(logoutUrl);
  9212. },
  9213. function (error) {
  9214. logger.error("Logout error", error);
  9215. }
  9216. );
  9217. };
  9218. module.exports = Moderator;
  9219. }).call(this,"/modules/xmpp/moderator.js")
  9220. },{"../../service/authentication/AuthenticationEvents":82,"../../service/xmpp/XMPPEvents":86,"../settings/Settings":21,"jitsi-meet-logger":47}],35:[function(require,module,exports){
  9221. (function (__filename){
  9222. /* jshint -W117 */
  9223. /* a simple MUC connection plugin
  9224. * can only handle a single MUC room
  9225. */
  9226. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9227. var ChatRoom = require("./ChatRoom");
  9228. module.exports = function(XMPP) {
  9229. Strophe.addConnectionPlugin('emuc', {
  9230. connection: null,
  9231. rooms: {},//map with the rooms
  9232. init: function (conn) {
  9233. this.connection = conn;
  9234. // add handlers (just once)
  9235. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  9236. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  9237. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  9238. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  9239. },
  9240. createRoom: function (jid, password, options) {
  9241. var roomJid = Strophe.getBareJidFromJid(jid);
  9242. if (this.rooms[roomJid]) {
  9243. logger.error("You are already in the room!");
  9244. return;
  9245. }
  9246. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  9247. return this.rooms[roomJid];
  9248. },
  9249. doLeave: function (jid) {
  9250. this.rooms[jid].doLeave();
  9251. delete this.rooms[jid];
  9252. },
  9253. onPresence: function (pres) {
  9254. var from = pres.getAttribute('from');
  9255. // What is this for? A workaround for something?
  9256. if (pres.getAttribute('type')) {
  9257. return true;
  9258. }
  9259. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9260. if(!room)
  9261. return;
  9262. // Parse status.
  9263. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  9264. room.createNonAnonymousRoom();
  9265. }
  9266. room.onPresence(pres);
  9267. return true;
  9268. },
  9269. onPresenceUnavailable: function (pres) {
  9270. var from = pres.getAttribute('from');
  9271. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9272. if(!room)
  9273. return;
  9274. room.onPresenceUnavailable(pres, from);
  9275. return true;
  9276. },
  9277. onPresenceError: function (pres) {
  9278. var from = pres.getAttribute('from');
  9279. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9280. if(!room)
  9281. return;
  9282. room.onPresenceError(pres, from);
  9283. return true;
  9284. },
  9285. onMessage: function (msg) {
  9286. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  9287. var from = msg.getAttribute('from');
  9288. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9289. if(!room)
  9290. return;
  9291. room.onMessage(msg, from);
  9292. return true;
  9293. },
  9294. setJingleSession: function (from, session) {
  9295. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9296. if(!room)
  9297. return;
  9298. room.setJingleSession(session);
  9299. }
  9300. });
  9301. };
  9302. }).call(this,"/modules/xmpp/strophe.emuc.js")
  9303. },{"./ChatRoom":26,"jitsi-meet-logger":47}],36:[function(require,module,exports){
  9304. (function (__filename){
  9305. /* jshint -W117 */
  9306. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9307. var JingleSession = require("./JingleSessionPC");
  9308. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9309. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9310. module.exports = function(XMPP, eventEmitter) {
  9311. Strophe.addConnectionPlugin('jingle', {
  9312. connection: null,
  9313. sessions: {},
  9314. jid2session: {},
  9315. ice_config: {iceServers: []},
  9316. media_constraints: {
  9317. mandatory: {
  9318. 'OfferToReceiveAudio': true,
  9319. 'OfferToReceiveVideo': true
  9320. }
  9321. // MozDontOfferDataChannel: true when this is firefox
  9322. },
  9323. init: function (conn) {
  9324. this.connection = conn;
  9325. if (this.connection.disco) {
  9326. // http://xmpp.org/extensions/xep-0167.html#support
  9327. // http://xmpp.org/extensions/xep-0176.html#support
  9328. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  9329. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  9330. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  9331. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  9332. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  9333. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  9334. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  9335. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  9336. || RTCBrowserType.isTemasysPluginUsed()) {
  9337. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  9338. }
  9339. // this is dealt with by SDP O/A so we don't need to announce this
  9340. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  9341. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  9342. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  9343. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  9344. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  9345. }
  9346. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  9347. },
  9348. onJingle: function (iq) {
  9349. var sid = $(iq).find('jingle').attr('sid');
  9350. var action = $(iq).find('jingle').attr('action');
  9351. var fromJid = iq.getAttribute('from');
  9352. // send ack first
  9353. var ack = $iq({type: 'result',
  9354. to: fromJid,
  9355. id: iq.getAttribute('id')
  9356. });
  9357. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  9358. var sess = this.sessions[sid];
  9359. if ('session-initiate' != action) {
  9360. if (sess === null) {
  9361. ack.type = 'error';
  9362. ack.c('error', {type: 'cancel'})
  9363. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9364. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9365. this.connection.send(ack);
  9366. return true;
  9367. }
  9368. // local jid is not checked
  9369. if (fromJid != sess.peerjid) {
  9370. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  9371. ack.type = 'error';
  9372. ack.c('error', {type: 'cancel'})
  9373. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9374. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9375. this.connection.send(ack);
  9376. return true;
  9377. }
  9378. } else if (sess !== undefined) {
  9379. // existing session with same session id
  9380. // this might be out-of-order if the sess.peerjid is the same as from
  9381. ack.type = 'error';
  9382. ack.c('error', {type: 'cancel'})
  9383. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  9384. logger.warn('duplicate session id', sid);
  9385. this.connection.send(ack);
  9386. return true;
  9387. }
  9388. // FIXME: check for a defined action
  9389. this.connection.send(ack);
  9390. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  9391. switch (action) {
  9392. case 'session-initiate':
  9393. console.log("(TIME) received session-initiate:\t",
  9394. window.performance.now());
  9395. var startMuted = $(iq).find('jingle>startmuted');
  9396. if (startMuted && startMuted.length > 0) {
  9397. var audioMuted = startMuted.attr("audio");
  9398. var videoMuted = startMuted.attr("video");
  9399. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  9400. audioMuted === "true", videoMuted === "true");
  9401. }
  9402. sess = new JingleSession(
  9403. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  9404. this.connection, XMPP);
  9405. // configure session
  9406. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  9407. this.connection.emuc.setJingleSession(fromBareJid, sess);
  9408. sess.media_constraints = this.media_constraints;
  9409. sess.ice_config = this.ice_config;
  9410. sess.initialize(fromJid, false);
  9411. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  9412. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  9413. sess.setOffer($(iq).find('>jingle'));
  9414. this.sessions[sess.sid] = sess;
  9415. this.jid2session[sess.peerjid] = sess;
  9416. // the callback should either
  9417. // .sendAnswer and .accept
  9418. // or .sendTerminate -- not necessarily synchronous
  9419. sess.sendAnswer();
  9420. sess.accept();
  9421. break;
  9422. case 'session-accept':
  9423. sess.setAnswer($(iq).find('>jingle'));
  9424. sess.accept();
  9425. break;
  9426. case 'session-terminate':
  9427. // If this is not the focus sending the terminate, we have
  9428. // nothing more to do here.
  9429. if (Object.keys(this.sessions).length < 1
  9430. || !(this.sessions[Object.keys(this.sessions)[0]]
  9431. instanceof JingleSession))
  9432. {
  9433. break;
  9434. }
  9435. logger.log('terminating...', sess.sid);
  9436. sess.terminate();
  9437. this.terminate(sess.sid);
  9438. if ($(iq).find('>jingle>reason').length) {
  9439. $(document).trigger('callterminated.jingle', [
  9440. sess.sid,
  9441. sess.peerjid,
  9442. $(iq).find('>jingle>reason>:first')[0].tagName,
  9443. $(iq).find('>jingle>reason>text').text()
  9444. ]);
  9445. } else {
  9446. $(document).trigger('callterminated.jingle',
  9447. [sess.sid, sess.peerjid]);
  9448. }
  9449. break;
  9450. case 'transport-info':
  9451. sess.addIceCandidate($(iq).find('>jingle>content'));
  9452. break;
  9453. case 'session-info':
  9454. var affected;
  9455. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9456. $(document).trigger('ringing.jingle', [sess.sid]);
  9457. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9458. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9459. $(document).trigger('mute.jingle', [sess.sid, affected]);
  9460. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9461. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9462. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  9463. }
  9464. break;
  9465. case 'addsource': // FIXME: proprietary, un-jingleish
  9466. case 'source-add': // FIXME: proprietary
  9467. sess.addSource($(iq).find('>jingle>content'));
  9468. break;
  9469. case 'removesource': // FIXME: proprietary, un-jingleish
  9470. case 'source-remove': // FIXME: proprietary
  9471. sess.removeSource($(iq).find('>jingle>content'));
  9472. break;
  9473. default:
  9474. logger.warn('jingle action not implemented', action);
  9475. break;
  9476. }
  9477. return true;
  9478. },
  9479. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  9480. if (sid === null || sid === undefined) {
  9481. for (sid in this.sessions) {
  9482. if (this.sessions[sid].state != 'ended') {
  9483. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9484. this.sessions[sid].terminate();
  9485. }
  9486. delete this.jid2session[this.sessions[sid].peerjid];
  9487. delete this.sessions[sid];
  9488. }
  9489. } else if (this.sessions.hasOwnProperty(sid)) {
  9490. if (this.sessions[sid].state != 'ended') {
  9491. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9492. this.sessions[sid].terminate();
  9493. }
  9494. delete this.jid2session[this.sessions[sid].peerjid];
  9495. delete this.sessions[sid];
  9496. }
  9497. },
  9498. getStunAndTurnCredentials: function () {
  9499. // get stun and turn configuration from server via xep-0215
  9500. // uses time-limited credentials as described in
  9501. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  9502. //
  9503. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  9504. // for a prosody module which implements this
  9505. //
  9506. // currently, this doesn't work with updateIce and therefore credentials with a long
  9507. // validity have to be fetched before creating the peerconnection
  9508. // TODO: implement refresh via updateIce as described in
  9509. // https://code.google.com/p/webrtc/issues/detail?id=1650
  9510. var self = this;
  9511. this.connection.sendIQ(
  9512. $iq({type: 'get', to: this.connection.domain})
  9513. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  9514. function (res) {
  9515. var iceservers = [];
  9516. $(res).find('>services>service').each(function (idx, el) {
  9517. el = $(el);
  9518. var dict = {};
  9519. var type = el.attr('type');
  9520. switch (type) {
  9521. case 'stun':
  9522. dict.url = 'stun:' + el.attr('host');
  9523. if (el.attr('port')) {
  9524. dict.url += ':' + el.attr('port');
  9525. }
  9526. iceservers.push(dict);
  9527. break;
  9528. case 'turn':
  9529. case 'turns':
  9530. dict.url = type + ':';
  9531. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  9532. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  9533. dict.url += el.attr('username') + '@';
  9534. } else {
  9535. dict.username = el.attr('username'); // only works in M28
  9536. }
  9537. }
  9538. dict.url += el.attr('host');
  9539. if (el.attr('port') && el.attr('port') != '3478') {
  9540. dict.url += ':' + el.attr('port');
  9541. }
  9542. if (el.attr('transport') && el.attr('transport') != 'udp') {
  9543. dict.url += '?transport=' + el.attr('transport');
  9544. }
  9545. if (el.attr('password')) {
  9546. dict.credential = el.attr('password');
  9547. }
  9548. iceservers.push(dict);
  9549. break;
  9550. }
  9551. });
  9552. self.ice_config.iceServers = iceservers;
  9553. },
  9554. function (err) {
  9555. logger.warn('getting turn credentials failed', err);
  9556. logger.warn('is mod_turncredentials or similar installed?');
  9557. }
  9558. );
  9559. // implement push?
  9560. },
  9561. /**
  9562. * Returns the data saved in 'updateLog' in a format to be logged.
  9563. */
  9564. getLog: function () {
  9565. var data = {};
  9566. var self = this;
  9567. Object.keys(this.sessions).forEach(function (sid) {
  9568. var session = self.sessions[sid];
  9569. if (session.peerconnection && session.peerconnection.updateLog) {
  9570. // FIXME: should probably be a .dump call
  9571. data["jingle_" + session.sid] = {
  9572. updateLog: session.peerconnection.updateLog,
  9573. stats: session.peerconnection.stats,
  9574. url: window.location.href
  9575. };
  9576. }
  9577. });
  9578. return data;
  9579. }
  9580. });
  9581. };
  9582. }).call(this,"/modules/xmpp/strophe.jingle.js")
  9583. },{"../../service/xmpp/XMPPEvents":86,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":47}],37:[function(require,module,exports){
  9584. /* global Strophe */
  9585. module.exports = function () {
  9586. Strophe.addConnectionPlugin('logger', {
  9587. // logs raw stanzas and makes them available for download as JSON
  9588. connection: null,
  9589. log: [],
  9590. init: function (conn) {
  9591. this.connection = conn;
  9592. this.connection.rawInput = this.log_incoming.bind(this);
  9593. this.connection.rawOutput = this.log_outgoing.bind(this);
  9594. },
  9595. log_incoming: function (stanza) {
  9596. this.log.push([new Date().getTime(), 'incoming', stanza]);
  9597. },
  9598. log_outgoing: function (stanza) {
  9599. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  9600. }
  9601. });
  9602. };
  9603. },{}],38:[function(require,module,exports){
  9604. (function (__filename){
  9605. /* global $, $iq, Strophe */
  9606. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9607. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9608. /**
  9609. * Ping every 20 sec
  9610. */
  9611. var PING_INTERVAL = 20000;
  9612. /**
  9613. * Ping timeout error after 15 sec of waiting.
  9614. */
  9615. var PING_TIMEOUT = 15000;
  9616. /**
  9617. * Will close the connection after 3 consecutive ping errors.
  9618. */
  9619. var PING_THRESHOLD = 3;
  9620. /**
  9621. * XEP-0199 ping plugin.
  9622. *
  9623. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  9624. */
  9625. module.exports = function (XMPP, eventEmitter) {
  9626. Strophe.addConnectionPlugin('ping', {
  9627. connection: null,
  9628. failedPings: 0,
  9629. /**
  9630. * Initializes the plugin. Method called by Strophe.
  9631. * @param connection Strophe connection instance.
  9632. */
  9633. init: function (connection) {
  9634. this.connection = connection;
  9635. Strophe.addNamespace('PING', "urn:xmpp:ping");
  9636. },
  9637. /**
  9638. * Sends "ping" to given <tt>jid</tt>
  9639. * @param jid the JID to which ping request will be sent.
  9640. * @param success callback called on success.
  9641. * @param error callback called on error.
  9642. * @param timeout ms how long are we going to wait for the response. On
  9643. * timeout <tt>error<//t> callback is called with undefined error
  9644. * argument.
  9645. */
  9646. ping: function (jid, success, error, timeout) {
  9647. var iq = $iq({type: 'get', to: jid});
  9648. iq.c('ping', {xmlns: Strophe.NS.PING});
  9649. this.connection.sendIQ(iq, success, error, timeout);
  9650. },
  9651. /**
  9652. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  9653. * @param jid the JID to be checked for ping support.
  9654. * @param callback function with boolean argument which will be
  9655. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  9656. */
  9657. hasPingSupport: function (jid, callback) {
  9658. this.connection.disco.info(
  9659. jid, null,
  9660. function (result) {
  9661. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  9662. callback(ping.length > 0);
  9663. },
  9664. function (error) {
  9665. logger.error("Ping feature discovery error", error);
  9666. callback(false);
  9667. }
  9668. );
  9669. },
  9670. /**
  9671. * Starts to send ping in given interval to specified remote JID.
  9672. * This plugin supports only one such task and <tt>stopInterval</tt>
  9673. * must be called before starting a new one.
  9674. * @param remoteJid remote JID to which ping requests will be sent to.
  9675. * @param interval task interval in ms.
  9676. */
  9677. startInterval: function (remoteJid, interval) {
  9678. if (this.intervalId) {
  9679. logger.error("Ping task scheduled already");
  9680. return;
  9681. }
  9682. if (!interval)
  9683. interval = PING_INTERVAL;
  9684. var self = this;
  9685. this.intervalId = window.setInterval(function () {
  9686. self.ping(remoteJid,
  9687. function (result) {
  9688. // Ping OK
  9689. self.failedPings = 0;
  9690. },
  9691. function (error) {
  9692. self.failedPings += 1;
  9693. logger.error(
  9694. "Ping " + (error ? "error" : "timeout"), error);
  9695. if (self.failedPings >= PING_THRESHOLD) {
  9696. self.connection.disconnect();
  9697. }
  9698. }, PING_TIMEOUT);
  9699. }, interval);
  9700. logger.info("XMPP pings will be sent every " + interval + " ms");
  9701. },
  9702. /**
  9703. * Stops current "ping" interval task.
  9704. */
  9705. stopInterval: function () {
  9706. if (this.intervalId) {
  9707. window.clearInterval(this.intervalId);
  9708. this.intervalId = null;
  9709. this.failedPings = 0;
  9710. logger.info("Ping interval cleared");
  9711. }
  9712. }
  9713. });
  9714. };
  9715. }).call(this,"/modules/xmpp/strophe.ping.js")
  9716. },{"../../service/xmpp/XMPPEvents":86,"jitsi-meet-logger":47}],39:[function(require,module,exports){
  9717. (function (__filename){
  9718. /* jshint -W117 */
  9719. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9720. module.exports = function() {
  9721. Strophe.addConnectionPlugin('rayo',
  9722. {
  9723. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  9724. connection: null,
  9725. init: function (conn) {
  9726. this.connection = conn;
  9727. if (this.connection.disco) {
  9728. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  9729. }
  9730. this.connection.addHandler(
  9731. this.onRayo.bind(this),
  9732. this.RAYO_XMLNS, 'iq', 'set', null, null);
  9733. },
  9734. onRayo: function (iq) {
  9735. logger.info("Rayo IQ", iq);
  9736. },
  9737. dial: function (to, from, roomName, roomPass) {
  9738. var self = this;
  9739. var req = $iq(
  9740. {
  9741. type: 'set',
  9742. to: this.connection.emuc.focusMucJid
  9743. }
  9744. );
  9745. req.c('dial',
  9746. {
  9747. xmlns: this.RAYO_XMLNS,
  9748. to: to,
  9749. from: from
  9750. });
  9751. req.c('header',
  9752. {
  9753. name: 'JvbRoomName',
  9754. value: roomName
  9755. }).up();
  9756. if (roomPass !== null && roomPass.length) {
  9757. req.c('header',
  9758. {
  9759. name: 'JvbRoomPassword',
  9760. value: roomPass
  9761. }).up();
  9762. }
  9763. this.connection.sendIQ(
  9764. req,
  9765. function (result) {
  9766. logger.info('Dial result ', result);
  9767. var resource = $(result).find('ref').attr('uri');
  9768. this.call_resource = resource.substr('xmpp:'.length);
  9769. logger.info(
  9770. "Received call resource: " + this.call_resource);
  9771. },
  9772. function (error) {
  9773. logger.info('Dial error ', error);
  9774. }
  9775. );
  9776. },
  9777. hang_up: function () {
  9778. if (!this.call_resource) {
  9779. logger.warn("No call in progress");
  9780. return;
  9781. }
  9782. var self = this;
  9783. var req = $iq(
  9784. {
  9785. type: 'set',
  9786. to: this.call_resource
  9787. }
  9788. );
  9789. req.c('hangup',
  9790. {
  9791. xmlns: this.RAYO_XMLNS
  9792. });
  9793. this.connection.sendIQ(
  9794. req,
  9795. function (result) {
  9796. logger.info('Hangup result ', result);
  9797. self.call_resource = null;
  9798. },
  9799. function (error) {
  9800. logger.info('Hangup error ', error);
  9801. self.call_resource = null;
  9802. }
  9803. );
  9804. }
  9805. }
  9806. );
  9807. };
  9808. }).call(this,"/modules/xmpp/strophe.rayo.js")
  9809. },{"jitsi-meet-logger":47}],40:[function(require,module,exports){
  9810. (function (__filename){
  9811. /* global Strophe */
  9812. /**
  9813. * Strophe logger implementation. Logs from level WARN and above.
  9814. */
  9815. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9816. module.exports = function () {
  9817. Strophe.log = function (level, msg) {
  9818. switch (level) {
  9819. case Strophe.LogLevel.WARN:
  9820. logger.warn("Strophe: " + msg);
  9821. break;
  9822. case Strophe.LogLevel.ERROR:
  9823. case Strophe.LogLevel.FATAL:
  9824. logger.error("Strophe: " + msg);
  9825. break;
  9826. }
  9827. };
  9828. Strophe.getStatusString = function (status) {
  9829. switch (status) {
  9830. case Strophe.Status.ERROR:
  9831. return "ERROR";
  9832. case Strophe.Status.CONNECTING:
  9833. return "CONNECTING";
  9834. case Strophe.Status.CONNFAIL:
  9835. return "CONNFAIL";
  9836. case Strophe.Status.AUTHENTICATING:
  9837. return "AUTHENTICATING";
  9838. case Strophe.Status.AUTHFAIL:
  9839. return "AUTHFAIL";
  9840. case Strophe.Status.CONNECTED:
  9841. return "CONNECTED";
  9842. case Strophe.Status.DISCONNECTED:
  9843. return "DISCONNECTED";
  9844. case Strophe.Status.DISCONNECTING:
  9845. return "DISCONNECTING";
  9846. case Strophe.Status.ATTACHED:
  9847. return "ATTACHED";
  9848. default:
  9849. return "unknown";
  9850. }
  9851. };
  9852. };
  9853. }).call(this,"/modules/xmpp/strophe.util.js")
  9854. },{"jitsi-meet-logger":47}],41:[function(require,module,exports){
  9855. (function (__filename){
  9856. /* global $, APP, config, Strophe*/
  9857. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9858. var EventEmitter = require("events");
  9859. var Pako = require("pako");
  9860. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  9861. var RTCEvents = require("../../service/RTC/RTCEvents");
  9862. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9863. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  9864. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  9865. var RTC = require("../RTC/RTC");
  9866. var authenticatedUser = false;
  9867. function createConnection(bosh) {
  9868. bosh = bosh || '/http-bind';
  9869. return new Strophe.Connection(bosh);
  9870. };
  9871. //!!!!!!!!!! FIXME: ...
  9872. function initStrophePlugins(XMPP)
  9873. {
  9874. require("./strophe.emuc")(XMPP);
  9875. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  9876. // require("./strophe.moderate")(XMPP, eventEmitter);
  9877. require("./strophe.util")();
  9878. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  9879. require("./strophe.rayo")();
  9880. require("./strophe.logger")();
  9881. }
  9882. //!!!!!!!!!! FIXME: ...
  9883. ///**
  9884. // * If given <tt>localStream</tt> is video one this method will advertise it's
  9885. // * video type in MUC presence.
  9886. // * @param localStream new or modified <tt>LocalStream</tt>.
  9887. // */
  9888. //function broadcastLocalVideoType(localStream) {
  9889. // if (localStream.videoType)
  9890. // XMPP.addToPresence('videoType', localStream.videoType);
  9891. //}
  9892. //
  9893. //function registerListeners() {
  9894. // RTC.addStreamListener(
  9895. // broadcastLocalVideoType,
  9896. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  9897. // );
  9898. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  9899. // XMPP.addToPresence("devices", devices);
  9900. // });
  9901. //}
  9902. function XMPP(options) {
  9903. this.eventEmitter = new EventEmitter();
  9904. this.connection = null;
  9905. this.disconnectInProgress = false;
  9906. this.forceMuted = false;
  9907. this.options = options;
  9908. initStrophePlugins(this);
  9909. // registerListeners();
  9910. this.connection = createConnection(options.bosh);
  9911. }
  9912. XMPP.prototype.getConnection = function(){ return connection; };
  9913. XMPP.prototype._connect = function (jid, password) {
  9914. var self = this;
  9915. // connection.connect() starts the connection process.
  9916. //
  9917. // As the connection process proceeds, the user supplied callback will
  9918. // be triggered multiple times with status updates. The callback should
  9919. // take two arguments - the status code and the error condition.
  9920. //
  9921. // The status code will be one of the values in the Strophe.Status
  9922. // constants. The error condition will be one of the conditions defined
  9923. // in RFC 3920 or the condition ‘strophe-parsererror’.
  9924. //
  9925. // The Parameters wait, hold and route are optional and only relevant
  9926. // for BOSH connections. Please see XEP 124 for a more detailed
  9927. // explanation of the optional parameters.
  9928. //
  9929. // Connection status constants for use by the connection handler
  9930. // callback.
  9931. //
  9932. // Status.ERROR - An error has occurred (websockets specific)
  9933. // Status.CONNECTING - The connection is currently being made
  9934. // Status.CONNFAIL - The connection attempt failed
  9935. // Status.AUTHENTICATING - The connection is authenticating
  9936. // Status.AUTHFAIL - The authentication attempt failed
  9937. // Status.CONNECTED - The connection has succeeded
  9938. // Status.DISCONNECTED - The connection has been terminated
  9939. // Status.DISCONNECTING - The connection is currently being terminated
  9940. // Status.ATTACHED - The connection has been attached
  9941. var anonymousConnectionFailed = false;
  9942. var connectionFailed = false;
  9943. var lastErrorMsg;
  9944. this.connection.connect(jid, password, function (status, msg) {
  9945. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  9946. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  9947. if (status === Strophe.Status.CONNECTED) {
  9948. if (self.options.useStunTurn) {
  9949. self.connection.jingle.getStunAndTurnCredentials();
  9950. }
  9951. logger.info("My Jabber ID: " + self.connection.jid);
  9952. // Schedule ping ?
  9953. var pingJid = self.connection.domain;
  9954. self.connection.ping.hasPingSupport(
  9955. pingJid,
  9956. function (hasPing) {
  9957. if (hasPing)
  9958. self.connection.ping.startInterval(pingJid);
  9959. else
  9960. logger.warn("Ping NOT supported by " + pingJid);
  9961. }
  9962. );
  9963. if (password)
  9964. authenticatedUser = true;
  9965. if (self.connection && self.connection.connected &&
  9966. Strophe.getResourceFromJid(self.connection.jid)) {
  9967. // .connected is true while connecting?
  9968. // self.connection.send($pres());
  9969. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  9970. Strophe.getResourceFromJid(self.connection.jid));
  9971. }
  9972. } else if (status === Strophe.Status.CONNFAIL) {
  9973. if (msg === 'x-strophe-bad-non-anon-jid') {
  9974. anonymousConnectionFailed = true;
  9975. }
  9976. else
  9977. {
  9978. connectionFailed = true;
  9979. }
  9980. lastErrorMsg = msg;
  9981. } else if (status === Strophe.Status.DISCONNECTED) {
  9982. // Stop ping interval
  9983. self.connection.ping.stopInterval();
  9984. self.disconnectInProgress = false;
  9985. if (anonymousConnectionFailed) {
  9986. // prompt user for username and password
  9987. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9988. JitsiConnectionErrors.PASSWORD_REQUIRED);
  9989. } else if(connectionFailed) {
  9990. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9991. JitsiConnectionErrors.OTHER_ERROR,
  9992. msg ? msg : lastErrorMsg);
  9993. } else {
  9994. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  9995. msg ? msg : lastErrorMsg);
  9996. }
  9997. } else if (status === Strophe.Status.AUTHFAIL) {
  9998. // wrong password or username, prompt user
  9999. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  10000. JitsiConnectionErrors.PASSWORD_REQUIRED);
  10001. }
  10002. });
  10003. }
  10004. XMPP.prototype.connect = function (jid, password) {
  10005. if(!jid) {
  10006. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  10007. // Force authenticated domain if room is appended with '?login=true'
  10008. if (this.options.hosts.anonymousdomain &&
  10009. window.location.search.indexOf("login=true") !== -1) {
  10010. configDomain = this.options.hosts.domain;
  10011. }
  10012. jid = configDomain || window.location.hostname;
  10013. }
  10014. return this._connect(jid, password);
  10015. };
  10016. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  10017. var roomjid = roomName + '@' + this.options.hosts.muc;
  10018. if (useNicks) {
  10019. if (nick) {
  10020. roomjid += '/' + nick;
  10021. } else {
  10022. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10023. }
  10024. } else {
  10025. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10026. if(!authenticatedUser)
  10027. tmpJid = tmpJid.substr(0, 8);
  10028. roomjid += '/' + tmpJid;
  10029. }
  10030. return this.connection.emuc.createRoom(roomjid, null, options);
  10031. }
  10032. XMPP.prototype.addListener = function(type, listener) {
  10033. this.eventEmitter.on(type, listener);
  10034. };
  10035. XMPP.prototype.removeListener = function (type, listener) {
  10036. this.eventEmitter.removeListener(type, listener);
  10037. };
  10038. //FIXME: this should work with the room
  10039. XMPP.prototype.leaveRoom = function (jid) {
  10040. var handler = this.connection.jingle.jid2session[jid];
  10041. if (handler && handler.peerconnection) {
  10042. // FIXME: probably removing streams is not required and close() should
  10043. // be enough
  10044. if (RTC.localAudio) {
  10045. handler.peerconnection.removeStream(
  10046. RTC.localAudio.getOriginalStream(), true);
  10047. }
  10048. if (RTC.localVideo) {
  10049. handler.peerconnection.removeStream(
  10050. RTC.localVideo.getOriginalStream(), true);
  10051. }
  10052. handler.peerconnection.close();
  10053. }
  10054. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10055. this.connection.emuc.doLeave(jid);
  10056. };
  10057. /**
  10058. * Sends 'data' as a log message to the focus. Returns true iff a message
  10059. * was sent.
  10060. * @param data
  10061. * @returns {boolean} true iff a message was sent.
  10062. */
  10063. XMPP.prototype.sendLogs = function (data) {
  10064. if(!this.connection.emuc.focusMucJid)
  10065. return false;
  10066. var deflate = true;
  10067. var content = JSON.stringify(data);
  10068. if (deflate) {
  10069. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10070. }
  10071. content = Base64.encode(content);
  10072. // XEP-0337-ish
  10073. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  10074. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  10075. id: 'PeerConnectionStats'});
  10076. message.c('message').t(content).up();
  10077. if (deflate) {
  10078. message.c('tag', {name: "deflated", value: "true"}).up();
  10079. }
  10080. message.up();
  10081. this.connection.send(message);
  10082. return true;
  10083. };
  10084. // Gets the logs from strophe.jingle.
  10085. XMPP.prototype.getJingleLog = function () {
  10086. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  10087. };
  10088. // Gets the logs from strophe.
  10089. XMPP.prototype.getXmppLog = function () {
  10090. return this.connection.logger ? this.connection.logger.log : null;
  10091. };
  10092. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  10093. this.connection.rayo.dial(to, from, roomName,roomPass);
  10094. };
  10095. XMPP.prototype.setMute = function (jid, mute) {
  10096. this.connection.moderate.setMute(jid, mute);
  10097. };
  10098. XMPP.prototype.eject = function (jid) {
  10099. this.connection.moderate.eject(jid);
  10100. };
  10101. XMPP.prototype.getSessions = function () {
  10102. return this.connection.jingle.sessions;
  10103. };
  10104. XMPP.prototype.disconnect = function () {
  10105. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  10106. {
  10107. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  10108. return;
  10109. }
  10110. this.disconnectInProgress = true;
  10111. this.connection.disconnect();
  10112. };
  10113. module.exports = XMPP;
  10114. }).call(this,"/modules/xmpp/xmpp.js")
  10115. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":79,"../../service/RTC/StreamEventTypes":81,"../../service/xmpp/XMPPEvents":86,"../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){
  10116. (function (process){
  10117. /*!
  10118. * async
  10119. * https://github.com/caolan/async
  10120. *
  10121. * Copyright 2010-2014 Caolan McMahon
  10122. * Released under the MIT license
  10123. */
  10124. /*jshint onevar: false, indent:4 */
  10125. /*global setImmediate: false, setTimeout: false, console: false */
  10126. (function () {
  10127. var async = {};
  10128. // global on the server, window in the browser
  10129. var root, previous_async;
  10130. root = this;
  10131. if (root != null) {
  10132. previous_async = root.async;
  10133. }
  10134. async.noConflict = function () {
  10135. root.async = previous_async;
  10136. return async;
  10137. };
  10138. function only_once(fn) {
  10139. var called = false;
  10140. return function() {
  10141. if (called) throw new Error("Callback was already called.");
  10142. called = true;
  10143. fn.apply(root, arguments);
  10144. }
  10145. }
  10146. //// cross-browser compatiblity functions ////
  10147. var _toString = Object.prototype.toString;
  10148. var _isArray = Array.isArray || function (obj) {
  10149. return _toString.call(obj) === '[object Array]';
  10150. };
  10151. var _each = function (arr, iterator) {
  10152. if (arr.forEach) {
  10153. return arr.forEach(iterator);
  10154. }
  10155. for (var i = 0; i < arr.length; i += 1) {
  10156. iterator(arr[i], i, arr);
  10157. }
  10158. };
  10159. var _map = function (arr, iterator) {
  10160. if (arr.map) {
  10161. return arr.map(iterator);
  10162. }
  10163. var results = [];
  10164. _each(arr, function (x, i, a) {
  10165. results.push(iterator(x, i, a));
  10166. });
  10167. return results;
  10168. };
  10169. var _reduce = function (arr, iterator, memo) {
  10170. if (arr.reduce) {
  10171. return arr.reduce(iterator, memo);
  10172. }
  10173. _each(arr, function (x, i, a) {
  10174. memo = iterator(memo, x, i, a);
  10175. });
  10176. return memo;
  10177. };
  10178. var _keys = function (obj) {
  10179. if (Object.keys) {
  10180. return Object.keys(obj);
  10181. }
  10182. var keys = [];
  10183. for (var k in obj) {
  10184. if (obj.hasOwnProperty(k)) {
  10185. keys.push(k);
  10186. }
  10187. }
  10188. return keys;
  10189. };
  10190. //// exported async module functions ////
  10191. //// nextTick implementation with browser-compatible fallback ////
  10192. if (typeof process === 'undefined' || !(process.nextTick)) {
  10193. if (typeof setImmediate === 'function') {
  10194. async.nextTick = function (fn) {
  10195. // not a direct alias for IE10 compatibility
  10196. setImmediate(fn);
  10197. };
  10198. async.setImmediate = async.nextTick;
  10199. }
  10200. else {
  10201. async.nextTick = function (fn) {
  10202. setTimeout(fn, 0);
  10203. };
  10204. async.setImmediate = async.nextTick;
  10205. }
  10206. }
  10207. else {
  10208. async.nextTick = process.nextTick;
  10209. if (typeof setImmediate !== 'undefined') {
  10210. async.setImmediate = function (fn) {
  10211. // not a direct alias for IE10 compatibility
  10212. setImmediate(fn);
  10213. };
  10214. }
  10215. else {
  10216. async.setImmediate = async.nextTick;
  10217. }
  10218. }
  10219. async.each = function (arr, iterator, callback) {
  10220. callback = callback || function () {};
  10221. if (!arr.length) {
  10222. return callback();
  10223. }
  10224. var completed = 0;
  10225. _each(arr, function (x) {
  10226. iterator(x, only_once(done) );
  10227. });
  10228. function done(err) {
  10229. if (err) {
  10230. callback(err);
  10231. callback = function () {};
  10232. }
  10233. else {
  10234. completed += 1;
  10235. if (completed >= arr.length) {
  10236. callback();
  10237. }
  10238. }
  10239. }
  10240. };
  10241. async.forEach = async.each;
  10242. async.eachSeries = function (arr, iterator, callback) {
  10243. callback = callback || function () {};
  10244. if (!arr.length) {
  10245. return callback();
  10246. }
  10247. var completed = 0;
  10248. var iterate = function () {
  10249. iterator(arr[completed], function (err) {
  10250. if (err) {
  10251. callback(err);
  10252. callback = function () {};
  10253. }
  10254. else {
  10255. completed += 1;
  10256. if (completed >= arr.length) {
  10257. callback();
  10258. }
  10259. else {
  10260. iterate();
  10261. }
  10262. }
  10263. });
  10264. };
  10265. iterate();
  10266. };
  10267. async.forEachSeries = async.eachSeries;
  10268. async.eachLimit = function (arr, limit, iterator, callback) {
  10269. var fn = _eachLimit(limit);
  10270. fn.apply(null, [arr, iterator, callback]);
  10271. };
  10272. async.forEachLimit = async.eachLimit;
  10273. var _eachLimit = function (limit) {
  10274. return function (arr, iterator, callback) {
  10275. callback = callback || function () {};
  10276. if (!arr.length || limit <= 0) {
  10277. return callback();
  10278. }
  10279. var completed = 0;
  10280. var started = 0;
  10281. var running = 0;
  10282. (function replenish () {
  10283. if (completed >= arr.length) {
  10284. return callback();
  10285. }
  10286. while (running < limit && started < arr.length) {
  10287. started += 1;
  10288. running += 1;
  10289. iterator(arr[started - 1], function (err) {
  10290. if (err) {
  10291. callback(err);
  10292. callback = function () {};
  10293. }
  10294. else {
  10295. completed += 1;
  10296. running -= 1;
  10297. if (completed >= arr.length) {
  10298. callback();
  10299. }
  10300. else {
  10301. replenish();
  10302. }
  10303. }
  10304. });
  10305. }
  10306. })();
  10307. };
  10308. };
  10309. var doParallel = function (fn) {
  10310. return function () {
  10311. var args = Array.prototype.slice.call(arguments);
  10312. return fn.apply(null, [async.each].concat(args));
  10313. };
  10314. };
  10315. var doParallelLimit = function(limit, fn) {
  10316. return function () {
  10317. var args = Array.prototype.slice.call(arguments);
  10318. return fn.apply(null, [_eachLimit(limit)].concat(args));
  10319. };
  10320. };
  10321. var doSeries = function (fn) {
  10322. return function () {
  10323. var args = Array.prototype.slice.call(arguments);
  10324. return fn.apply(null, [async.eachSeries].concat(args));
  10325. };
  10326. };
  10327. var _asyncMap = function (eachfn, arr, iterator, callback) {
  10328. arr = _map(arr, function (x, i) {
  10329. return {index: i, value: x};
  10330. });
  10331. if (!callback) {
  10332. eachfn(arr, function (x, callback) {
  10333. iterator(x.value, function (err) {
  10334. callback(err);
  10335. });
  10336. });
  10337. } else {
  10338. var results = [];
  10339. eachfn(arr, function (x, callback) {
  10340. iterator(x.value, function (err, v) {
  10341. results[x.index] = v;
  10342. callback(err);
  10343. });
  10344. }, function (err) {
  10345. callback(err, results);
  10346. });
  10347. }
  10348. };
  10349. async.map = doParallel(_asyncMap);
  10350. async.mapSeries = doSeries(_asyncMap);
  10351. async.mapLimit = function (arr, limit, iterator, callback) {
  10352. return _mapLimit(limit)(arr, iterator, callback);
  10353. };
  10354. var _mapLimit = function(limit) {
  10355. return doParallelLimit(limit, _asyncMap);
  10356. };
  10357. // reduce only has a series version, as doing reduce in parallel won't
  10358. // work in many situations.
  10359. async.reduce = function (arr, memo, iterator, callback) {
  10360. async.eachSeries(arr, function (x, callback) {
  10361. iterator(memo, x, function (err, v) {
  10362. memo = v;
  10363. callback(err);
  10364. });
  10365. }, function (err) {
  10366. callback(err, memo);
  10367. });
  10368. };
  10369. // inject alias
  10370. async.inject = async.reduce;
  10371. // foldl alias
  10372. async.foldl = async.reduce;
  10373. async.reduceRight = function (arr, memo, iterator, callback) {
  10374. var reversed = _map(arr, function (x) {
  10375. return x;
  10376. }).reverse();
  10377. async.reduce(reversed, memo, iterator, callback);
  10378. };
  10379. // foldr alias
  10380. async.foldr = async.reduceRight;
  10381. var _filter = function (eachfn, arr, iterator, callback) {
  10382. var results = [];
  10383. arr = _map(arr, function (x, i) {
  10384. return {index: i, value: x};
  10385. });
  10386. eachfn(arr, function (x, callback) {
  10387. iterator(x.value, function (v) {
  10388. if (v) {
  10389. results.push(x);
  10390. }
  10391. callback();
  10392. });
  10393. }, function (err) {
  10394. callback(_map(results.sort(function (a, b) {
  10395. return a.index - b.index;
  10396. }), function (x) {
  10397. return x.value;
  10398. }));
  10399. });
  10400. };
  10401. async.filter = doParallel(_filter);
  10402. async.filterSeries = doSeries(_filter);
  10403. // select alias
  10404. async.select = async.filter;
  10405. async.selectSeries = async.filterSeries;
  10406. var _reject = function (eachfn, arr, iterator, callback) {
  10407. var results = [];
  10408. arr = _map(arr, function (x, i) {
  10409. return {index: i, value: x};
  10410. });
  10411. eachfn(arr, function (x, callback) {
  10412. iterator(x.value, function (v) {
  10413. if (!v) {
  10414. results.push(x);
  10415. }
  10416. callback();
  10417. });
  10418. }, function (err) {
  10419. callback(_map(results.sort(function (a, b) {
  10420. return a.index - b.index;
  10421. }), function (x) {
  10422. return x.value;
  10423. }));
  10424. });
  10425. };
  10426. async.reject = doParallel(_reject);
  10427. async.rejectSeries = doSeries(_reject);
  10428. var _detect = function (eachfn, arr, iterator, main_callback) {
  10429. eachfn(arr, function (x, callback) {
  10430. iterator(x, function (result) {
  10431. if (result) {
  10432. main_callback(x);
  10433. main_callback = function () {};
  10434. }
  10435. else {
  10436. callback();
  10437. }
  10438. });
  10439. }, function (err) {
  10440. main_callback();
  10441. });
  10442. };
  10443. async.detect = doParallel(_detect);
  10444. async.detectSeries = doSeries(_detect);
  10445. async.some = function (arr, iterator, main_callback) {
  10446. async.each(arr, function (x, callback) {
  10447. iterator(x, function (v) {
  10448. if (v) {
  10449. main_callback(true);
  10450. main_callback = function () {};
  10451. }
  10452. callback();
  10453. });
  10454. }, function (err) {
  10455. main_callback(false);
  10456. });
  10457. };
  10458. // any alias
  10459. async.any = async.some;
  10460. async.every = function (arr, iterator, main_callback) {
  10461. async.each(arr, function (x, callback) {
  10462. iterator(x, function (v) {
  10463. if (!v) {
  10464. main_callback(false);
  10465. main_callback = function () {};
  10466. }
  10467. callback();
  10468. });
  10469. }, function (err) {
  10470. main_callback(true);
  10471. });
  10472. };
  10473. // all alias
  10474. async.all = async.every;
  10475. async.sortBy = function (arr, iterator, callback) {
  10476. async.map(arr, function (x, callback) {
  10477. iterator(x, function (err, criteria) {
  10478. if (err) {
  10479. callback(err);
  10480. }
  10481. else {
  10482. callback(null, {value: x, criteria: criteria});
  10483. }
  10484. });
  10485. }, function (err, results) {
  10486. if (err) {
  10487. return callback(err);
  10488. }
  10489. else {
  10490. var fn = function (left, right) {
  10491. var a = left.criteria, b = right.criteria;
  10492. return a < b ? -1 : a > b ? 1 : 0;
  10493. };
  10494. callback(null, _map(results.sort(fn), function (x) {
  10495. return x.value;
  10496. }));
  10497. }
  10498. });
  10499. };
  10500. async.auto = function (tasks, callback) {
  10501. callback = callback || function () {};
  10502. var keys = _keys(tasks);
  10503. var remainingTasks = keys.length
  10504. if (!remainingTasks) {
  10505. return callback();
  10506. }
  10507. var results = {};
  10508. var listeners = [];
  10509. var addListener = function (fn) {
  10510. listeners.unshift(fn);
  10511. };
  10512. var removeListener = function (fn) {
  10513. for (var i = 0; i < listeners.length; i += 1) {
  10514. if (listeners[i] === fn) {
  10515. listeners.splice(i, 1);
  10516. return;
  10517. }
  10518. }
  10519. };
  10520. var taskComplete = function () {
  10521. remainingTasks--
  10522. _each(listeners.slice(0), function (fn) {
  10523. fn();
  10524. });
  10525. };
  10526. addListener(function () {
  10527. if (!remainingTasks) {
  10528. var theCallback = callback;
  10529. // prevent final callback from calling itself if it errors
  10530. callback = function () {};
  10531. theCallback(null, results);
  10532. }
  10533. });
  10534. _each(keys, function (k) {
  10535. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  10536. var taskCallback = function (err) {
  10537. var args = Array.prototype.slice.call(arguments, 1);
  10538. if (args.length <= 1) {
  10539. args = args[0];
  10540. }
  10541. if (err) {
  10542. var safeResults = {};
  10543. _each(_keys(results), function(rkey) {
  10544. safeResults[rkey] = results[rkey];
  10545. });
  10546. safeResults[k] = args;
  10547. callback(err, safeResults);
  10548. // stop subsequent errors hitting callback multiple times
  10549. callback = function () {};
  10550. }
  10551. else {
  10552. results[k] = args;
  10553. async.setImmediate(taskComplete);
  10554. }
  10555. };
  10556. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  10557. var ready = function () {
  10558. return _reduce(requires, function (a, x) {
  10559. return (a && results.hasOwnProperty(x));
  10560. }, true) && !results.hasOwnProperty(k);
  10561. };
  10562. if (ready()) {
  10563. task[task.length - 1](taskCallback, results);
  10564. }
  10565. else {
  10566. var listener = function () {
  10567. if (ready()) {
  10568. removeListener(listener);
  10569. task[task.length - 1](taskCallback, results);
  10570. }
  10571. };
  10572. addListener(listener);
  10573. }
  10574. });
  10575. };
  10576. async.retry = function(times, task, callback) {
  10577. var DEFAULT_TIMES = 5;
  10578. var attempts = [];
  10579. // Use defaults if times not passed
  10580. if (typeof times === 'function') {
  10581. callback = task;
  10582. task = times;
  10583. times = DEFAULT_TIMES;
  10584. }
  10585. // Make sure times is a number
  10586. times = parseInt(times, 10) || DEFAULT_TIMES;
  10587. var wrappedTask = function(wrappedCallback, wrappedResults) {
  10588. var retryAttempt = function(task, finalAttempt) {
  10589. return function(seriesCallback) {
  10590. task(function(err, result){
  10591. seriesCallback(!err || finalAttempt, {err: err, result: result});
  10592. }, wrappedResults);
  10593. };
  10594. };
  10595. while (times) {
  10596. attempts.push(retryAttempt(task, !(times-=1)));
  10597. }
  10598. async.series(attempts, function(done, data){
  10599. data = data[data.length - 1];
  10600. (wrappedCallback || callback)(data.err, data.result);
  10601. });
  10602. }
  10603. // If a callback is passed, run this as a controll flow
  10604. return callback ? wrappedTask() : wrappedTask
  10605. };
  10606. async.waterfall = function (tasks, callback) {
  10607. callback = callback || function () {};
  10608. if (!_isArray(tasks)) {
  10609. var err = new Error('First argument to waterfall must be an array of functions');
  10610. return callback(err);
  10611. }
  10612. if (!tasks.length) {
  10613. return callback();
  10614. }
  10615. var wrapIterator = function (iterator) {
  10616. return function (err) {
  10617. if (err) {
  10618. callback.apply(null, arguments);
  10619. callback = function () {};
  10620. }
  10621. else {
  10622. var args = Array.prototype.slice.call(arguments, 1);
  10623. var next = iterator.next();
  10624. if (next) {
  10625. args.push(wrapIterator(next));
  10626. }
  10627. else {
  10628. args.push(callback);
  10629. }
  10630. async.setImmediate(function () {
  10631. iterator.apply(null, args);
  10632. });
  10633. }
  10634. };
  10635. };
  10636. wrapIterator(async.iterator(tasks))();
  10637. };
  10638. var _parallel = function(eachfn, tasks, callback) {
  10639. callback = callback || function () {};
  10640. if (_isArray(tasks)) {
  10641. eachfn.map(tasks, function (fn, callback) {
  10642. if (fn) {
  10643. fn(function (err) {
  10644. var args = Array.prototype.slice.call(arguments, 1);
  10645. if (args.length <= 1) {
  10646. args = args[0];
  10647. }
  10648. callback.call(null, err, args);
  10649. });
  10650. }
  10651. }, callback);
  10652. }
  10653. else {
  10654. var results = {};
  10655. eachfn.each(_keys(tasks), function (k, callback) {
  10656. tasks[k](function (err) {
  10657. var args = Array.prototype.slice.call(arguments, 1);
  10658. if (args.length <= 1) {
  10659. args = args[0];
  10660. }
  10661. results[k] = args;
  10662. callback(err);
  10663. });
  10664. }, function (err) {
  10665. callback(err, results);
  10666. });
  10667. }
  10668. };
  10669. async.parallel = function (tasks, callback) {
  10670. _parallel({ map: async.map, each: async.each }, tasks, callback);
  10671. };
  10672. async.parallelLimit = function(tasks, limit, callback) {
  10673. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  10674. };
  10675. async.series = function (tasks, callback) {
  10676. callback = callback || function () {};
  10677. if (_isArray(tasks)) {
  10678. async.mapSeries(tasks, function (fn, callback) {
  10679. if (fn) {
  10680. fn(function (err) {
  10681. var args = Array.prototype.slice.call(arguments, 1);
  10682. if (args.length <= 1) {
  10683. args = args[0];
  10684. }
  10685. callback.call(null, err, args);
  10686. });
  10687. }
  10688. }, callback);
  10689. }
  10690. else {
  10691. var results = {};
  10692. async.eachSeries(_keys(tasks), function (k, callback) {
  10693. tasks[k](function (err) {
  10694. var args = Array.prototype.slice.call(arguments, 1);
  10695. if (args.length <= 1) {
  10696. args = args[0];
  10697. }
  10698. results[k] = args;
  10699. callback(err);
  10700. });
  10701. }, function (err) {
  10702. callback(err, results);
  10703. });
  10704. }
  10705. };
  10706. async.iterator = function (tasks) {
  10707. var makeCallback = function (index) {
  10708. var fn = function () {
  10709. if (tasks.length) {
  10710. tasks[index].apply(null, arguments);
  10711. }
  10712. return fn.next();
  10713. };
  10714. fn.next = function () {
  10715. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  10716. };
  10717. return fn;
  10718. };
  10719. return makeCallback(0);
  10720. };
  10721. async.apply = function (fn) {
  10722. var args = Array.prototype.slice.call(arguments, 1);
  10723. return function () {
  10724. return fn.apply(
  10725. null, args.concat(Array.prototype.slice.call(arguments))
  10726. );
  10727. };
  10728. };
  10729. var _concat = function (eachfn, arr, fn, callback) {
  10730. var r = [];
  10731. eachfn(arr, function (x, cb) {
  10732. fn(x, function (err, y) {
  10733. r = r.concat(y || []);
  10734. cb(err);
  10735. });
  10736. }, function (err) {
  10737. callback(err, r);
  10738. });
  10739. };
  10740. async.concat = doParallel(_concat);
  10741. async.concatSeries = doSeries(_concat);
  10742. async.whilst = function (test, iterator, callback) {
  10743. if (test()) {
  10744. iterator(function (err) {
  10745. if (err) {
  10746. return callback(err);
  10747. }
  10748. async.whilst(test, iterator, callback);
  10749. });
  10750. }
  10751. else {
  10752. callback();
  10753. }
  10754. };
  10755. async.doWhilst = function (iterator, test, callback) {
  10756. iterator(function (err) {
  10757. if (err) {
  10758. return callback(err);
  10759. }
  10760. var args = Array.prototype.slice.call(arguments, 1);
  10761. if (test.apply(null, args)) {
  10762. async.doWhilst(iterator, test, callback);
  10763. }
  10764. else {
  10765. callback();
  10766. }
  10767. });
  10768. };
  10769. async.until = function (test, iterator, callback) {
  10770. if (!test()) {
  10771. iterator(function (err) {
  10772. if (err) {
  10773. return callback(err);
  10774. }
  10775. async.until(test, iterator, callback);
  10776. });
  10777. }
  10778. else {
  10779. callback();
  10780. }
  10781. };
  10782. async.doUntil = function (iterator, test, callback) {
  10783. iterator(function (err) {
  10784. if (err) {
  10785. return callback(err);
  10786. }
  10787. var args = Array.prototype.slice.call(arguments, 1);
  10788. if (!test.apply(null, args)) {
  10789. async.doUntil(iterator, test, callback);
  10790. }
  10791. else {
  10792. callback();
  10793. }
  10794. });
  10795. };
  10796. async.queue = function (worker, concurrency) {
  10797. if (concurrency === undefined) {
  10798. concurrency = 1;
  10799. }
  10800. function _insert(q, data, pos, callback) {
  10801. if (!q.started){
  10802. q.started = true;
  10803. }
  10804. if (!_isArray(data)) {
  10805. data = [data];
  10806. }
  10807. if(data.length == 0) {
  10808. // call drain immediately if there are no tasks
  10809. return async.setImmediate(function() {
  10810. if (q.drain) {
  10811. q.drain();
  10812. }
  10813. });
  10814. }
  10815. _each(data, function(task) {
  10816. var item = {
  10817. data: task,
  10818. callback: typeof callback === 'function' ? callback : null
  10819. };
  10820. if (pos) {
  10821. q.tasks.unshift(item);
  10822. } else {
  10823. q.tasks.push(item);
  10824. }
  10825. if (q.saturated && q.tasks.length === q.concurrency) {
  10826. q.saturated();
  10827. }
  10828. async.setImmediate(q.process);
  10829. });
  10830. }
  10831. var workers = 0;
  10832. var q = {
  10833. tasks: [],
  10834. concurrency: concurrency,
  10835. saturated: null,
  10836. empty: null,
  10837. drain: null,
  10838. started: false,
  10839. paused: false,
  10840. push: function (data, callback) {
  10841. _insert(q, data, false, callback);
  10842. },
  10843. kill: function () {
  10844. q.drain = null;
  10845. q.tasks = [];
  10846. },
  10847. unshift: function (data, callback) {
  10848. _insert(q, data, true, callback);
  10849. },
  10850. process: function () {
  10851. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  10852. var task = q.tasks.shift();
  10853. if (q.empty && q.tasks.length === 0) {
  10854. q.empty();
  10855. }
  10856. workers += 1;
  10857. var next = function () {
  10858. workers -= 1;
  10859. if (task.callback) {
  10860. task.callback.apply(task, arguments);
  10861. }
  10862. if (q.drain && q.tasks.length + workers === 0) {
  10863. q.drain();
  10864. }
  10865. q.process();
  10866. };
  10867. var cb = only_once(next);
  10868. worker(task.data, cb);
  10869. }
  10870. },
  10871. length: function () {
  10872. return q.tasks.length;
  10873. },
  10874. running: function () {
  10875. return workers;
  10876. },
  10877. idle: function() {
  10878. return q.tasks.length + workers === 0;
  10879. },
  10880. pause: function () {
  10881. if (q.paused === true) { return; }
  10882. q.paused = true;
  10883. q.process();
  10884. },
  10885. resume: function () {
  10886. if (q.paused === false) { return; }
  10887. q.paused = false;
  10888. q.process();
  10889. }
  10890. };
  10891. return q;
  10892. };
  10893. async.priorityQueue = function (worker, concurrency) {
  10894. function _compareTasks(a, b){
  10895. return a.priority - b.priority;
  10896. };
  10897. function _binarySearch(sequence, item, compare) {
  10898. var beg = -1,
  10899. end = sequence.length - 1;
  10900. while (beg < end) {
  10901. var mid = beg + ((end - beg + 1) >>> 1);
  10902. if (compare(item, sequence[mid]) >= 0) {
  10903. beg = mid;
  10904. } else {
  10905. end = mid - 1;
  10906. }
  10907. }
  10908. return beg;
  10909. }
  10910. function _insert(q, data, priority, callback) {
  10911. if (!q.started){
  10912. q.started = true;
  10913. }
  10914. if (!_isArray(data)) {
  10915. data = [data];
  10916. }
  10917. if(data.length == 0) {
  10918. // call drain immediately if there are no tasks
  10919. return async.setImmediate(function() {
  10920. if (q.drain) {
  10921. q.drain();
  10922. }
  10923. });
  10924. }
  10925. _each(data, function(task) {
  10926. var item = {
  10927. data: task,
  10928. priority: priority,
  10929. callback: typeof callback === 'function' ? callback : null
  10930. };
  10931. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  10932. if (q.saturated && q.tasks.length === q.concurrency) {
  10933. q.saturated();
  10934. }
  10935. async.setImmediate(q.process);
  10936. });
  10937. }
  10938. // Start with a normal queue
  10939. var q = async.queue(worker, concurrency);
  10940. // Override push to accept second parameter representing priority
  10941. q.push = function (data, priority, callback) {
  10942. _insert(q, data, priority, callback);
  10943. };
  10944. // Remove unshift function
  10945. delete q.unshift;
  10946. return q;
  10947. };
  10948. async.cargo = function (worker, payload) {
  10949. var working = false,
  10950. tasks = [];
  10951. var cargo = {
  10952. tasks: tasks,
  10953. payload: payload,
  10954. saturated: null,
  10955. empty: null,
  10956. drain: null,
  10957. drained: true,
  10958. push: function (data, callback) {
  10959. if (!_isArray(data)) {
  10960. data = [data];
  10961. }
  10962. _each(data, function(task) {
  10963. tasks.push({
  10964. data: task,
  10965. callback: typeof callback === 'function' ? callback : null
  10966. });
  10967. cargo.drained = false;
  10968. if (cargo.saturated && tasks.length === payload) {
  10969. cargo.saturated();
  10970. }
  10971. });
  10972. async.setImmediate(cargo.process);
  10973. },
  10974. process: function process() {
  10975. if (working) return;
  10976. if (tasks.length === 0) {
  10977. if(cargo.drain && !cargo.drained) cargo.drain();
  10978. cargo.drained = true;
  10979. return;
  10980. }
  10981. var ts = typeof payload === 'number'
  10982. ? tasks.splice(0, payload)
  10983. : tasks.splice(0, tasks.length);
  10984. var ds = _map(ts, function (task) {
  10985. return task.data;
  10986. });
  10987. if(cargo.empty) cargo.empty();
  10988. working = true;
  10989. worker(ds, function () {
  10990. working = false;
  10991. var args = arguments;
  10992. _each(ts, function (data) {
  10993. if (data.callback) {
  10994. data.callback.apply(null, args);
  10995. }
  10996. });
  10997. process();
  10998. });
  10999. },
  11000. length: function () {
  11001. return tasks.length;
  11002. },
  11003. running: function () {
  11004. return working;
  11005. }
  11006. };
  11007. return cargo;
  11008. };
  11009. var _console_fn = function (name) {
  11010. return function (fn) {
  11011. var args = Array.prototype.slice.call(arguments, 1);
  11012. fn.apply(null, args.concat([function (err) {
  11013. var args = Array.prototype.slice.call(arguments, 1);
  11014. if (typeof console !== 'undefined') {
  11015. if (err) {
  11016. if (console.error) {
  11017. console.error(err);
  11018. }
  11019. }
  11020. else if (console[name]) {
  11021. _each(args, function (x) {
  11022. console[name](x);
  11023. });
  11024. }
  11025. }
  11026. }]));
  11027. };
  11028. };
  11029. async.log = _console_fn('log');
  11030. async.dir = _console_fn('dir');
  11031. /*async.info = _console_fn('info');
  11032. async.warn = _console_fn('warn');
  11033. async.error = _console_fn('error');*/
  11034. async.memoize = function (fn, hasher) {
  11035. var memo = {};
  11036. var queues = {};
  11037. hasher = hasher || function (x) {
  11038. return x;
  11039. };
  11040. var memoized = function () {
  11041. var args = Array.prototype.slice.call(arguments);
  11042. var callback = args.pop();
  11043. var key = hasher.apply(null, args);
  11044. if (key in memo) {
  11045. async.nextTick(function () {
  11046. callback.apply(null, memo[key]);
  11047. });
  11048. }
  11049. else if (key in queues) {
  11050. queues[key].push(callback);
  11051. }
  11052. else {
  11053. queues[key] = [callback];
  11054. fn.apply(null, args.concat([function () {
  11055. memo[key] = arguments;
  11056. var q = queues[key];
  11057. delete queues[key];
  11058. for (var i = 0, l = q.length; i < l; i++) {
  11059. q[i].apply(null, arguments);
  11060. }
  11061. }]));
  11062. }
  11063. };
  11064. memoized.memo = memo;
  11065. memoized.unmemoized = fn;
  11066. return memoized;
  11067. };
  11068. async.unmemoize = function (fn) {
  11069. return function () {
  11070. return (fn.unmemoized || fn).apply(null, arguments);
  11071. };
  11072. };
  11073. async.times = function (count, iterator, callback) {
  11074. var counter = [];
  11075. for (var i = 0; i < count; i++) {
  11076. counter.push(i);
  11077. }
  11078. return async.map(counter, iterator, callback);
  11079. };
  11080. async.timesSeries = function (count, iterator, callback) {
  11081. var counter = [];
  11082. for (var i = 0; i < count; i++) {
  11083. counter.push(i);
  11084. }
  11085. return async.mapSeries(counter, iterator, callback);
  11086. };
  11087. async.seq = function (/* functions... */) {
  11088. var fns = arguments;
  11089. return function () {
  11090. var that = this;
  11091. var args = Array.prototype.slice.call(arguments);
  11092. var callback = args.pop();
  11093. async.reduce(fns, args, function (newargs, fn, cb) {
  11094. fn.apply(that, newargs.concat([function () {
  11095. var err = arguments[0];
  11096. var nextargs = Array.prototype.slice.call(arguments, 1);
  11097. cb(err, nextargs);
  11098. }]))
  11099. },
  11100. function (err, results) {
  11101. callback.apply(that, [err].concat(results));
  11102. });
  11103. };
  11104. };
  11105. async.compose = function (/* functions... */) {
  11106. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  11107. };
  11108. var _applyEach = function (eachfn, fns /*args...*/) {
  11109. var go = function () {
  11110. var that = this;
  11111. var args = Array.prototype.slice.call(arguments);
  11112. var callback = args.pop();
  11113. return eachfn(fns, function (fn, cb) {
  11114. fn.apply(that, args.concat([cb]));
  11115. },
  11116. callback);
  11117. };
  11118. if (arguments.length > 2) {
  11119. var args = Array.prototype.slice.call(arguments, 2);
  11120. return go.apply(this, args);
  11121. }
  11122. else {
  11123. return go;
  11124. }
  11125. };
  11126. async.applyEach = doParallel(_applyEach);
  11127. async.applyEachSeries = doSeries(_applyEach);
  11128. async.forever = function (fn, callback) {
  11129. function next(err) {
  11130. if (err) {
  11131. if (callback) {
  11132. return callback(err);
  11133. }
  11134. throw err;
  11135. }
  11136. fn(next);
  11137. }
  11138. next();
  11139. };
  11140. // Node.js
  11141. if (typeof module !== 'undefined' && module.exports) {
  11142. module.exports = async;
  11143. }
  11144. // AMD / RequireJS
  11145. else if (typeof define !== 'undefined' && define.amd) {
  11146. define([], function () {
  11147. return async;
  11148. });
  11149. }
  11150. // included directly via <script> tag
  11151. else {
  11152. root.async = async;
  11153. }
  11154. }());
  11155. }).call(this,require('_process'))
  11156. },{"_process":44}],43:[function(require,module,exports){
  11157. // Copyright Joyent, Inc. and other Node contributors.
  11158. //
  11159. // Permission is hereby granted, free of charge, to any person obtaining a
  11160. // copy of this software and associated documentation files (the
  11161. // "Software"), to deal in the Software without restriction, including
  11162. // without limitation the rights to use, copy, modify, merge, publish,
  11163. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11164. // persons to whom the Software is furnished to do so, subject to the
  11165. // following conditions:
  11166. //
  11167. // The above copyright notice and this permission notice shall be included
  11168. // in all copies or substantial portions of the Software.
  11169. //
  11170. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11171. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11172. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11173. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11174. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11175. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11176. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11177. function EventEmitter() {
  11178. this._events = this._events || {};
  11179. this._maxListeners = this._maxListeners || undefined;
  11180. }
  11181. module.exports = EventEmitter;
  11182. // Backwards-compat with node 0.10.x
  11183. EventEmitter.EventEmitter = EventEmitter;
  11184. EventEmitter.prototype._events = undefined;
  11185. EventEmitter.prototype._maxListeners = undefined;
  11186. // By default EventEmitters will print a warning if more than 10 listeners are
  11187. // added to it. This is a useful default which helps finding memory leaks.
  11188. EventEmitter.defaultMaxListeners = 10;
  11189. // Obviously not all Emitters should be limited to 10. This function allows
  11190. // that to be increased. Set to zero for unlimited.
  11191. EventEmitter.prototype.setMaxListeners = function(n) {
  11192. if (!isNumber(n) || n < 0 || isNaN(n))
  11193. throw TypeError('n must be a positive number');
  11194. this._maxListeners = n;
  11195. return this;
  11196. };
  11197. EventEmitter.prototype.emit = function(type) {
  11198. var er, handler, len, args, i, listeners;
  11199. if (!this._events)
  11200. this._events = {};
  11201. // If there is no 'error' event listener then throw.
  11202. if (type === 'error') {
  11203. if (!this._events.error ||
  11204. (isObject(this._events.error) && !this._events.error.length)) {
  11205. er = arguments[1];
  11206. if (er instanceof Error) {
  11207. throw er; // Unhandled 'error' event
  11208. }
  11209. throw TypeError('Uncaught, unspecified "error" event.');
  11210. }
  11211. }
  11212. handler = this._events[type];
  11213. if (isUndefined(handler))
  11214. return false;
  11215. if (isFunction(handler)) {
  11216. switch (arguments.length) {
  11217. // fast cases
  11218. case 1:
  11219. handler.call(this);
  11220. break;
  11221. case 2:
  11222. handler.call(this, arguments[1]);
  11223. break;
  11224. case 3:
  11225. handler.call(this, arguments[1], arguments[2]);
  11226. break;
  11227. // slower
  11228. default:
  11229. len = arguments.length;
  11230. args = new Array(len - 1);
  11231. for (i = 1; i < len; i++)
  11232. args[i - 1] = arguments[i];
  11233. handler.apply(this, args);
  11234. }
  11235. } else if (isObject(handler)) {
  11236. len = arguments.length;
  11237. args = new Array(len - 1);
  11238. for (i = 1; i < len; i++)
  11239. args[i - 1] = arguments[i];
  11240. listeners = handler.slice();
  11241. len = listeners.length;
  11242. for (i = 0; i < len; i++)
  11243. listeners[i].apply(this, args);
  11244. }
  11245. return true;
  11246. };
  11247. EventEmitter.prototype.addListener = function(type, listener) {
  11248. var m;
  11249. if (!isFunction(listener))
  11250. throw TypeError('listener must be a function');
  11251. if (!this._events)
  11252. this._events = {};
  11253. // To avoid recursion in the case that type === "newListener"! Before
  11254. // adding it to the listeners, first emit "newListener".
  11255. if (this._events.newListener)
  11256. this.emit('newListener', type,
  11257. isFunction(listener.listener) ?
  11258. listener.listener : listener);
  11259. if (!this._events[type])
  11260. // Optimize the case of one listener. Don't need the extra array object.
  11261. this._events[type] = listener;
  11262. else if (isObject(this._events[type]))
  11263. // If we've already got an array, just append.
  11264. this._events[type].push(listener);
  11265. else
  11266. // Adding the second element, need to change to array.
  11267. this._events[type] = [this._events[type], listener];
  11268. // Check for listener leak
  11269. if (isObject(this._events[type]) && !this._events[type].warned) {
  11270. var m;
  11271. if (!isUndefined(this._maxListeners)) {
  11272. m = this._maxListeners;
  11273. } else {
  11274. m = EventEmitter.defaultMaxListeners;
  11275. }
  11276. if (m && m > 0 && this._events[type].length > m) {
  11277. this._events[type].warned = true;
  11278. console.error('(node) warning: possible EventEmitter memory ' +
  11279. 'leak detected. %d listeners added. ' +
  11280. 'Use emitter.setMaxListeners() to increase limit.',
  11281. this._events[type].length);
  11282. if (typeof console.trace === 'function') {
  11283. // not supported in IE 10
  11284. console.trace();
  11285. }
  11286. }
  11287. }
  11288. return this;
  11289. };
  11290. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  11291. EventEmitter.prototype.once = function(type, listener) {
  11292. if (!isFunction(listener))
  11293. throw TypeError('listener must be a function');
  11294. var fired = false;
  11295. function g() {
  11296. this.removeListener(type, g);
  11297. if (!fired) {
  11298. fired = true;
  11299. listener.apply(this, arguments);
  11300. }
  11301. }
  11302. g.listener = listener;
  11303. this.on(type, g);
  11304. return this;
  11305. };
  11306. // emits a 'removeListener' event iff the listener was removed
  11307. EventEmitter.prototype.removeListener = function(type, listener) {
  11308. var list, position, length, i;
  11309. if (!isFunction(listener))
  11310. throw TypeError('listener must be a function');
  11311. if (!this._events || !this._events[type])
  11312. return this;
  11313. list = this._events[type];
  11314. length = list.length;
  11315. position = -1;
  11316. if (list === listener ||
  11317. (isFunction(list.listener) && list.listener === listener)) {
  11318. delete this._events[type];
  11319. if (this._events.removeListener)
  11320. this.emit('removeListener', type, listener);
  11321. } else if (isObject(list)) {
  11322. for (i = length; i-- > 0;) {
  11323. if (list[i] === listener ||
  11324. (list[i].listener && list[i].listener === listener)) {
  11325. position = i;
  11326. break;
  11327. }
  11328. }
  11329. if (position < 0)
  11330. return this;
  11331. if (list.length === 1) {
  11332. list.length = 0;
  11333. delete this._events[type];
  11334. } else {
  11335. list.splice(position, 1);
  11336. }
  11337. if (this._events.removeListener)
  11338. this.emit('removeListener', type, listener);
  11339. }
  11340. return this;
  11341. };
  11342. EventEmitter.prototype.removeAllListeners = function(type) {
  11343. var key, listeners;
  11344. if (!this._events)
  11345. return this;
  11346. // not listening for removeListener, no need to emit
  11347. if (!this._events.removeListener) {
  11348. if (arguments.length === 0)
  11349. this._events = {};
  11350. else if (this._events[type])
  11351. delete this._events[type];
  11352. return this;
  11353. }
  11354. // emit removeListener for all listeners on all events
  11355. if (arguments.length === 0) {
  11356. for (key in this._events) {
  11357. if (key === 'removeListener') continue;
  11358. this.removeAllListeners(key);
  11359. }
  11360. this.removeAllListeners('removeListener');
  11361. this._events = {};
  11362. return this;
  11363. }
  11364. listeners = this._events[type];
  11365. if (isFunction(listeners)) {
  11366. this.removeListener(type, listeners);
  11367. } else {
  11368. // LIFO order
  11369. while (listeners.length)
  11370. this.removeListener(type, listeners[listeners.length - 1]);
  11371. }
  11372. delete this._events[type];
  11373. return this;
  11374. };
  11375. EventEmitter.prototype.listeners = function(type) {
  11376. var ret;
  11377. if (!this._events || !this._events[type])
  11378. ret = [];
  11379. else if (isFunction(this._events[type]))
  11380. ret = [this._events[type]];
  11381. else
  11382. ret = this._events[type].slice();
  11383. return ret;
  11384. };
  11385. EventEmitter.listenerCount = function(emitter, type) {
  11386. var ret;
  11387. if (!emitter._events || !emitter._events[type])
  11388. ret = 0;
  11389. else if (isFunction(emitter._events[type]))
  11390. ret = 1;
  11391. else
  11392. ret = emitter._events[type].length;
  11393. return ret;
  11394. };
  11395. function isFunction(arg) {
  11396. return typeof arg === 'function';
  11397. }
  11398. function isNumber(arg) {
  11399. return typeof arg === 'number';
  11400. }
  11401. function isObject(arg) {
  11402. return typeof arg === 'object' && arg !== null;
  11403. }
  11404. function isUndefined(arg) {
  11405. return arg === void 0;
  11406. }
  11407. },{}],44:[function(require,module,exports){
  11408. // shim for using process in browser
  11409. var process = module.exports = {};
  11410. var queue = [];
  11411. var draining = false;
  11412. var currentQueue;
  11413. var queueIndex = -1;
  11414. function cleanUpNextTick() {
  11415. draining = false;
  11416. if (currentQueue.length) {
  11417. queue = currentQueue.concat(queue);
  11418. } else {
  11419. queueIndex = -1;
  11420. }
  11421. if (queue.length) {
  11422. drainQueue();
  11423. }
  11424. }
  11425. function drainQueue() {
  11426. if (draining) {
  11427. return;
  11428. }
  11429. var timeout = setTimeout(cleanUpNextTick);
  11430. draining = true;
  11431. var len = queue.length;
  11432. while(len) {
  11433. currentQueue = queue;
  11434. queue = [];
  11435. while (++queueIndex < len) {
  11436. if (currentQueue) {
  11437. currentQueue[queueIndex].run();
  11438. }
  11439. }
  11440. queueIndex = -1;
  11441. len = queue.length;
  11442. }
  11443. currentQueue = null;
  11444. draining = false;
  11445. clearTimeout(timeout);
  11446. }
  11447. process.nextTick = function (fun) {
  11448. var args = new Array(arguments.length - 1);
  11449. if (arguments.length > 1) {
  11450. for (var i = 1; i < arguments.length; i++) {
  11451. args[i - 1] = arguments[i];
  11452. }
  11453. }
  11454. queue.push(new Item(fun, args));
  11455. if (queue.length === 1 && !draining) {
  11456. setTimeout(drainQueue, 0);
  11457. }
  11458. };
  11459. // v8 likes predictible objects
  11460. function Item(fun, array) {
  11461. this.fun = fun;
  11462. this.array = array;
  11463. }
  11464. Item.prototype.run = function () {
  11465. this.fun.apply(null, this.array);
  11466. };
  11467. process.title = 'browser';
  11468. process.browser = true;
  11469. process.env = {};
  11470. process.argv = [];
  11471. process.version = ''; // empty string to avoid regexp issues
  11472. process.versions = {};
  11473. function noop() {}
  11474. process.on = noop;
  11475. process.addListener = noop;
  11476. process.once = noop;
  11477. process.off = noop;
  11478. process.removeListener = noop;
  11479. process.removeAllListeners = noop;
  11480. process.emit = noop;
  11481. process.binding = function (name) {
  11482. throw new Error('process.binding is not supported');
  11483. };
  11484. process.cwd = function () { return '/' };
  11485. process.chdir = function (dir) {
  11486. throw new Error('process.chdir is not supported');
  11487. };
  11488. process.umask = function() { return 0; };
  11489. },{}],45:[function(require,module,exports){
  11490. (function (process,global){
  11491. /*!
  11492. * @overview es6-promise - a tiny implementation of Promises/A+.
  11493. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  11494. * @license Licensed under MIT license
  11495. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  11496. * @version 3.0.2
  11497. */
  11498. (function() {
  11499. "use strict";
  11500. function lib$es6$promise$utils$$objectOrFunction(x) {
  11501. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  11502. }
  11503. function lib$es6$promise$utils$$isFunction(x) {
  11504. return typeof x === 'function';
  11505. }
  11506. function lib$es6$promise$utils$$isMaybeThenable(x) {
  11507. return typeof x === 'object' && x !== null;
  11508. }
  11509. var lib$es6$promise$utils$$_isArray;
  11510. if (!Array.isArray) {
  11511. lib$es6$promise$utils$$_isArray = function (x) {
  11512. return Object.prototype.toString.call(x) === '[object Array]';
  11513. };
  11514. } else {
  11515. lib$es6$promise$utils$$_isArray = Array.isArray;
  11516. }
  11517. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  11518. var lib$es6$promise$asap$$len = 0;
  11519. var lib$es6$promise$asap$$toString = {}.toString;
  11520. var lib$es6$promise$asap$$vertxNext;
  11521. var lib$es6$promise$asap$$customSchedulerFn;
  11522. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  11523. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  11524. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  11525. lib$es6$promise$asap$$len += 2;
  11526. if (lib$es6$promise$asap$$len === 2) {
  11527. // If len is 2, that means that we need to schedule an async flush.
  11528. // If additional callbacks are queued before the queue is flushed, they
  11529. // will be processed by this flush that we are scheduling.
  11530. if (lib$es6$promise$asap$$customSchedulerFn) {
  11531. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  11532. } else {
  11533. lib$es6$promise$asap$$scheduleFlush();
  11534. }
  11535. }
  11536. }
  11537. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  11538. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  11539. }
  11540. function lib$es6$promise$asap$$setAsap(asapFn) {
  11541. lib$es6$promise$asap$$asap = asapFn;
  11542. }
  11543. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  11544. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  11545. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  11546. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  11547. // test for web worker but not in IE10
  11548. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  11549. typeof importScripts !== 'undefined' &&
  11550. typeof MessageChannel !== 'undefined';
  11551. // node
  11552. function lib$es6$promise$asap$$useNextTick() {
  11553. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  11554. // see https://github.com/cujojs/when/issues/410 for details
  11555. return function() {
  11556. process.nextTick(lib$es6$promise$asap$$flush);
  11557. };
  11558. }
  11559. // vertx
  11560. function lib$es6$promise$asap$$useVertxTimer() {
  11561. return function() {
  11562. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  11563. };
  11564. }
  11565. function lib$es6$promise$asap$$useMutationObserver() {
  11566. var iterations = 0;
  11567. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  11568. var node = document.createTextNode('');
  11569. observer.observe(node, { characterData: true });
  11570. return function() {
  11571. node.data = (iterations = ++iterations % 2);
  11572. };
  11573. }
  11574. // web worker
  11575. function lib$es6$promise$asap$$useMessageChannel() {
  11576. var channel = new MessageChannel();
  11577. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  11578. return function () {
  11579. channel.port2.postMessage(0);
  11580. };
  11581. }
  11582. function lib$es6$promise$asap$$useSetTimeout() {
  11583. return function() {
  11584. setTimeout(lib$es6$promise$asap$$flush, 1);
  11585. };
  11586. }
  11587. var lib$es6$promise$asap$$queue = new Array(1000);
  11588. function lib$es6$promise$asap$$flush() {
  11589. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  11590. var callback = lib$es6$promise$asap$$queue[i];
  11591. var arg = lib$es6$promise$asap$$queue[i+1];
  11592. callback(arg);
  11593. lib$es6$promise$asap$$queue[i] = undefined;
  11594. lib$es6$promise$asap$$queue[i+1] = undefined;
  11595. }
  11596. lib$es6$promise$asap$$len = 0;
  11597. }
  11598. function lib$es6$promise$asap$$attemptVertx() {
  11599. try {
  11600. var r = require;
  11601. var vertx = r('vertx');
  11602. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  11603. return lib$es6$promise$asap$$useVertxTimer();
  11604. } catch(e) {
  11605. return lib$es6$promise$asap$$useSetTimeout();
  11606. }
  11607. }
  11608. var lib$es6$promise$asap$$scheduleFlush;
  11609. // Decide what async method to use to triggering processing of queued callbacks:
  11610. if (lib$es6$promise$asap$$isNode) {
  11611. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  11612. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  11613. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  11614. } else if (lib$es6$promise$asap$$isWorker) {
  11615. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  11616. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  11617. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  11618. } else {
  11619. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  11620. }
  11621. function lib$es6$promise$$internal$$noop() {}
  11622. var lib$es6$promise$$internal$$PENDING = void 0;
  11623. var lib$es6$promise$$internal$$FULFILLED = 1;
  11624. var lib$es6$promise$$internal$$REJECTED = 2;
  11625. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11626. function lib$es6$promise$$internal$$selfFulfillment() {
  11627. return new TypeError("You cannot resolve a promise with itself");
  11628. }
  11629. function lib$es6$promise$$internal$$cannotReturnOwn() {
  11630. return new TypeError('A promises callback cannot return that same promise.');
  11631. }
  11632. function lib$es6$promise$$internal$$getThen(promise) {
  11633. try {
  11634. return promise.then;
  11635. } catch(error) {
  11636. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  11637. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  11638. }
  11639. }
  11640. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  11641. try {
  11642. then.call(value, fulfillmentHandler, rejectionHandler);
  11643. } catch(e) {
  11644. return e;
  11645. }
  11646. }
  11647. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  11648. lib$es6$promise$asap$$asap(function(promise) {
  11649. var sealed = false;
  11650. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  11651. if (sealed) { return; }
  11652. sealed = true;
  11653. if (thenable !== value) {
  11654. lib$es6$promise$$internal$$resolve(promise, value);
  11655. } else {
  11656. lib$es6$promise$$internal$$fulfill(promise, value);
  11657. }
  11658. }, function(reason) {
  11659. if (sealed) { return; }
  11660. sealed = true;
  11661. lib$es6$promise$$internal$$reject(promise, reason);
  11662. }, 'Settle: ' + (promise._label || ' unknown promise'));
  11663. if (!sealed && error) {
  11664. sealed = true;
  11665. lib$es6$promise$$internal$$reject(promise, error);
  11666. }
  11667. }, promise);
  11668. }
  11669. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  11670. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  11671. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  11672. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  11673. lib$es6$promise$$internal$$reject(promise, thenable._result);
  11674. } else {
  11675. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  11676. lib$es6$promise$$internal$$resolve(promise, value);
  11677. }, function(reason) {
  11678. lib$es6$promise$$internal$$reject(promise, reason);
  11679. });
  11680. }
  11681. }
  11682. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  11683. if (maybeThenable.constructor === promise.constructor) {
  11684. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  11685. } else {
  11686. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  11687. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  11688. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  11689. } else if (then === undefined) {
  11690. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11691. } else if (lib$es6$promise$utils$$isFunction(then)) {
  11692. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  11693. } else {
  11694. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11695. }
  11696. }
  11697. }
  11698. function lib$es6$promise$$internal$$resolve(promise, value) {
  11699. if (promise === value) {
  11700. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  11701. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  11702. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  11703. } else {
  11704. lib$es6$promise$$internal$$fulfill(promise, value);
  11705. }
  11706. }
  11707. function lib$es6$promise$$internal$$publishRejection(promise) {
  11708. if (promise._onerror) {
  11709. promise._onerror(promise._result);
  11710. }
  11711. lib$es6$promise$$internal$$publish(promise);
  11712. }
  11713. function lib$es6$promise$$internal$$fulfill(promise, value) {
  11714. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11715. promise._result = value;
  11716. promise._state = lib$es6$promise$$internal$$FULFILLED;
  11717. if (promise._subscribers.length !== 0) {
  11718. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  11719. }
  11720. }
  11721. function lib$es6$promise$$internal$$reject(promise, reason) {
  11722. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11723. promise._state = lib$es6$promise$$internal$$REJECTED;
  11724. promise._result = reason;
  11725. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  11726. }
  11727. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  11728. var subscribers = parent._subscribers;
  11729. var length = subscribers.length;
  11730. parent._onerror = null;
  11731. subscribers[length] = child;
  11732. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  11733. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  11734. if (length === 0 && parent._state) {
  11735. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  11736. }
  11737. }
  11738. function lib$es6$promise$$internal$$publish(promise) {
  11739. var subscribers = promise._subscribers;
  11740. var settled = promise._state;
  11741. if (subscribers.length === 0) { return; }
  11742. var child, callback, detail = promise._result;
  11743. for (var i = 0; i < subscribers.length; i += 3) {
  11744. child = subscribers[i];
  11745. callback = subscribers[i + settled];
  11746. if (child) {
  11747. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  11748. } else {
  11749. callback(detail);
  11750. }
  11751. }
  11752. promise._subscribers.length = 0;
  11753. }
  11754. function lib$es6$promise$$internal$$ErrorObject() {
  11755. this.error = null;
  11756. }
  11757. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11758. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  11759. try {
  11760. return callback(detail);
  11761. } catch(e) {
  11762. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  11763. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  11764. }
  11765. }
  11766. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  11767. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  11768. value, error, succeeded, failed;
  11769. if (hasCallback) {
  11770. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  11771. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  11772. failed = true;
  11773. error = value.error;
  11774. value = null;
  11775. } else {
  11776. succeeded = true;
  11777. }
  11778. if (promise === value) {
  11779. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  11780. return;
  11781. }
  11782. } else {
  11783. value = detail;
  11784. succeeded = true;
  11785. }
  11786. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  11787. // noop
  11788. } else if (hasCallback && succeeded) {
  11789. lib$es6$promise$$internal$$resolve(promise, value);
  11790. } else if (failed) {
  11791. lib$es6$promise$$internal$$reject(promise, error);
  11792. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  11793. lib$es6$promise$$internal$$fulfill(promise, value);
  11794. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  11795. lib$es6$promise$$internal$$reject(promise, value);
  11796. }
  11797. }
  11798. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  11799. try {
  11800. resolver(function resolvePromise(value){
  11801. lib$es6$promise$$internal$$resolve(promise, value);
  11802. }, function rejectPromise(reason) {
  11803. lib$es6$promise$$internal$$reject(promise, reason);
  11804. });
  11805. } catch(e) {
  11806. lib$es6$promise$$internal$$reject(promise, e);
  11807. }
  11808. }
  11809. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  11810. var enumerator = this;
  11811. enumerator._instanceConstructor = Constructor;
  11812. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  11813. if (enumerator._validateInput(input)) {
  11814. enumerator._input = input;
  11815. enumerator.length = input.length;
  11816. enumerator._remaining = input.length;
  11817. enumerator._init();
  11818. if (enumerator.length === 0) {
  11819. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11820. } else {
  11821. enumerator.length = enumerator.length || 0;
  11822. enumerator._enumerate();
  11823. if (enumerator._remaining === 0) {
  11824. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11825. }
  11826. }
  11827. } else {
  11828. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  11829. }
  11830. }
  11831. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  11832. return lib$es6$promise$utils$$isArray(input);
  11833. };
  11834. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  11835. return new Error('Array Methods must be provided an Array');
  11836. };
  11837. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  11838. this._result = new Array(this.length);
  11839. };
  11840. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  11841. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  11842. var enumerator = this;
  11843. var length = enumerator.length;
  11844. var promise = enumerator.promise;
  11845. var input = enumerator._input;
  11846. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11847. enumerator._eachEntry(input[i], i);
  11848. }
  11849. };
  11850. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  11851. var enumerator = this;
  11852. var c = enumerator._instanceConstructor;
  11853. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  11854. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  11855. entry._onerror = null;
  11856. enumerator._settledAt(entry._state, i, entry._result);
  11857. } else {
  11858. enumerator._willSettleAt(c.resolve(entry), i);
  11859. }
  11860. } else {
  11861. enumerator._remaining--;
  11862. enumerator._result[i] = entry;
  11863. }
  11864. };
  11865. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  11866. var enumerator = this;
  11867. var promise = enumerator.promise;
  11868. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  11869. enumerator._remaining--;
  11870. if (state === lib$es6$promise$$internal$$REJECTED) {
  11871. lib$es6$promise$$internal$$reject(promise, value);
  11872. } else {
  11873. enumerator._result[i] = value;
  11874. }
  11875. }
  11876. if (enumerator._remaining === 0) {
  11877. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  11878. }
  11879. };
  11880. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  11881. var enumerator = this;
  11882. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  11883. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  11884. }, function(reason) {
  11885. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  11886. });
  11887. };
  11888. function lib$es6$promise$promise$all$$all(entries) {
  11889. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  11890. }
  11891. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  11892. function lib$es6$promise$promise$race$$race(entries) {
  11893. /*jshint validthis:true */
  11894. var Constructor = this;
  11895. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11896. if (!lib$es6$promise$utils$$isArray(entries)) {
  11897. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  11898. return promise;
  11899. }
  11900. var length = entries.length;
  11901. function onFulfillment(value) {
  11902. lib$es6$promise$$internal$$resolve(promise, value);
  11903. }
  11904. function onRejection(reason) {
  11905. lib$es6$promise$$internal$$reject(promise, reason);
  11906. }
  11907. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11908. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  11909. }
  11910. return promise;
  11911. }
  11912. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  11913. function lib$es6$promise$promise$resolve$$resolve(object) {
  11914. /*jshint validthis:true */
  11915. var Constructor = this;
  11916. if (object && typeof object === 'object' && object.constructor === Constructor) {
  11917. return object;
  11918. }
  11919. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11920. lib$es6$promise$$internal$$resolve(promise, object);
  11921. return promise;
  11922. }
  11923. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  11924. function lib$es6$promise$promise$reject$$reject(reason) {
  11925. /*jshint validthis:true */
  11926. var Constructor = this;
  11927. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11928. lib$es6$promise$$internal$$reject(promise, reason);
  11929. return promise;
  11930. }
  11931. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  11932. var lib$es6$promise$promise$$counter = 0;
  11933. function lib$es6$promise$promise$$needsResolver() {
  11934. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  11935. }
  11936. function lib$es6$promise$promise$$needsNew() {
  11937. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  11938. }
  11939. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  11940. /**
  11941. Promise objects represent the eventual result of an asynchronous operation. The
  11942. primary way of interacting with a promise is through its `then` method, which
  11943. registers callbacks to receive either a promise's eventual value or the reason
  11944. why the promise cannot be fulfilled.
  11945. Terminology
  11946. -----------
  11947. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  11948. - `thenable` is an object or function that defines a `then` method.
  11949. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  11950. - `exception` is a value that is thrown using the throw statement.
  11951. - `reason` is a value that indicates why a promise was rejected.
  11952. - `settled` the final resting state of a promise, fulfilled or rejected.
  11953. A promise can be in one of three states: pending, fulfilled, or rejected.
  11954. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  11955. state. Promises that are rejected have a rejection reason and are in the
  11956. rejected state. A fulfillment value is never a thenable.
  11957. Promises can also be said to *resolve* a value. If this value is also a
  11958. promise, then the original promise's settled state will match the value's
  11959. settled state. So a promise that *resolves* a promise that rejects will
  11960. itself reject, and a promise that *resolves* a promise that fulfills will
  11961. itself fulfill.
  11962. Basic Usage:
  11963. ------------
  11964. ```js
  11965. var promise = new Promise(function(resolve, reject) {
  11966. // on success
  11967. resolve(value);
  11968. // on failure
  11969. reject(reason);
  11970. });
  11971. promise.then(function(value) {
  11972. // on fulfillment
  11973. }, function(reason) {
  11974. // on rejection
  11975. });
  11976. ```
  11977. Advanced Usage:
  11978. ---------------
  11979. Promises shine when abstracting away asynchronous interactions such as
  11980. `XMLHttpRequest`s.
  11981. ```js
  11982. function getJSON(url) {
  11983. return new Promise(function(resolve, reject){
  11984. var xhr = new XMLHttpRequest();
  11985. xhr.open('GET', url);
  11986. xhr.onreadystatechange = handler;
  11987. xhr.responseType = 'json';
  11988. xhr.setRequestHeader('Accept', 'application/json');
  11989. xhr.send();
  11990. function handler() {
  11991. if (this.readyState === this.DONE) {
  11992. if (this.status === 200) {
  11993. resolve(this.response);
  11994. } else {
  11995. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  11996. }
  11997. }
  11998. };
  11999. });
  12000. }
  12001. getJSON('/posts.json').then(function(json) {
  12002. // on fulfillment
  12003. }, function(reason) {
  12004. // on rejection
  12005. });
  12006. ```
  12007. Unlike callbacks, promises are great composable primitives.
  12008. ```js
  12009. Promise.all([
  12010. getJSON('/posts'),
  12011. getJSON('/comments')
  12012. ]).then(function(values){
  12013. values[0] // => postsJSON
  12014. values[1] // => commentsJSON
  12015. return values;
  12016. });
  12017. ```
  12018. @class Promise
  12019. @param {function} resolver
  12020. Useful for tooling.
  12021. @constructor
  12022. */
  12023. function lib$es6$promise$promise$$Promise(resolver) {
  12024. this._id = lib$es6$promise$promise$$counter++;
  12025. this._state = undefined;
  12026. this._result = undefined;
  12027. this._subscribers = [];
  12028. if (lib$es6$promise$$internal$$noop !== resolver) {
  12029. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12030. lib$es6$promise$promise$$needsResolver();
  12031. }
  12032. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12033. lib$es6$promise$promise$$needsNew();
  12034. }
  12035. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12036. }
  12037. }
  12038. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12039. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12040. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12041. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12042. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12043. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12044. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12045. lib$es6$promise$promise$$Promise.prototype = {
  12046. constructor: lib$es6$promise$promise$$Promise,
  12047. /**
  12048. The primary way of interacting with a promise is through its `then` method,
  12049. which registers callbacks to receive either a promise's eventual value or the
  12050. reason why the promise cannot be fulfilled.
  12051. ```js
  12052. findUser().then(function(user){
  12053. // user is available
  12054. }, function(reason){
  12055. // user is unavailable, and you are given the reason why
  12056. });
  12057. ```
  12058. Chaining
  12059. --------
  12060. The return value of `then` is itself a promise. This second, 'downstream'
  12061. promise is resolved with the return value of the first promise's fulfillment
  12062. or rejection handler, or rejected if the handler throws an exception.
  12063. ```js
  12064. findUser().then(function (user) {
  12065. return user.name;
  12066. }, function (reason) {
  12067. return 'default name';
  12068. }).then(function (userName) {
  12069. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  12070. // will be `'default name'`
  12071. });
  12072. findUser().then(function (user) {
  12073. throw new Error('Found user, but still unhappy');
  12074. }, function (reason) {
  12075. throw new Error('`findUser` rejected and we're unhappy');
  12076. }).then(function (value) {
  12077. // never reached
  12078. }, function (reason) {
  12079. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  12080. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  12081. });
  12082. ```
  12083. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  12084. ```js
  12085. findUser().then(function (user) {
  12086. throw new PedagogicalException('Upstream error');
  12087. }).then(function (value) {
  12088. // never reached
  12089. }).then(function (value) {
  12090. // never reached
  12091. }, function (reason) {
  12092. // The `PedgagocialException` is propagated all the way down to here
  12093. });
  12094. ```
  12095. Assimilation
  12096. ------------
  12097. Sometimes the value you want to propagate to a downstream promise can only be
  12098. retrieved asynchronously. This can be achieved by returning a promise in the
  12099. fulfillment or rejection handler. The downstream promise will then be pending
  12100. until the returned promise is settled. This is called *assimilation*.
  12101. ```js
  12102. findUser().then(function (user) {
  12103. return findCommentsByAuthor(user);
  12104. }).then(function (comments) {
  12105. // The user's comments are now available
  12106. });
  12107. ```
  12108. If the assimliated promise rejects, then the downstream promise will also reject.
  12109. ```js
  12110. findUser().then(function (user) {
  12111. return findCommentsByAuthor(user);
  12112. }).then(function (comments) {
  12113. // If `findCommentsByAuthor` fulfills, we'll have the value here
  12114. }, function (reason) {
  12115. // If `findCommentsByAuthor` rejects, we'll have the reason here
  12116. });
  12117. ```
  12118. Simple Example
  12119. --------------
  12120. Synchronous Example
  12121. ```javascript
  12122. var result;
  12123. try {
  12124. result = findResult();
  12125. // success
  12126. } catch(reason) {
  12127. // failure
  12128. }
  12129. ```
  12130. Errback Example
  12131. ```js
  12132. findResult(function(result, err){
  12133. if (err) {
  12134. // failure
  12135. } else {
  12136. // success
  12137. }
  12138. });
  12139. ```
  12140. Promise Example;
  12141. ```javascript
  12142. findResult().then(function(result){
  12143. // success
  12144. }, function(reason){
  12145. // failure
  12146. });
  12147. ```
  12148. Advanced Example
  12149. --------------
  12150. Synchronous Example
  12151. ```javascript
  12152. var author, books;
  12153. try {
  12154. author = findAuthor();
  12155. books = findBooksByAuthor(author);
  12156. // success
  12157. } catch(reason) {
  12158. // failure
  12159. }
  12160. ```
  12161. Errback Example
  12162. ```js
  12163. function foundBooks(books) {
  12164. }
  12165. function failure(reason) {
  12166. }
  12167. findAuthor(function(author, err){
  12168. if (err) {
  12169. failure(err);
  12170. // failure
  12171. } else {
  12172. try {
  12173. findBoooksByAuthor(author, function(books, err) {
  12174. if (err) {
  12175. failure(err);
  12176. } else {
  12177. try {
  12178. foundBooks(books);
  12179. } catch(reason) {
  12180. failure(reason);
  12181. }
  12182. }
  12183. });
  12184. } catch(error) {
  12185. failure(err);
  12186. }
  12187. // success
  12188. }
  12189. });
  12190. ```
  12191. Promise Example;
  12192. ```javascript
  12193. findAuthor().
  12194. then(findBooksByAuthor).
  12195. then(function(books){
  12196. // found books
  12197. }).catch(function(reason){
  12198. // something went wrong
  12199. });
  12200. ```
  12201. @method then
  12202. @param {Function} onFulfilled
  12203. @param {Function} onRejected
  12204. Useful for tooling.
  12205. @return {Promise}
  12206. */
  12207. then: function(onFulfillment, onRejection) {
  12208. var parent = this;
  12209. var state = parent._state;
  12210. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  12211. return this;
  12212. }
  12213. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  12214. var result = parent._result;
  12215. if (state) {
  12216. var callback = arguments[state - 1];
  12217. lib$es6$promise$asap$$asap(function(){
  12218. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  12219. });
  12220. } else {
  12221. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  12222. }
  12223. return child;
  12224. },
  12225. /**
  12226. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  12227. as the catch block of a try/catch statement.
  12228. ```js
  12229. function findAuthor(){
  12230. throw new Error('couldn't find that author');
  12231. }
  12232. // synchronous
  12233. try {
  12234. findAuthor();
  12235. } catch(reason) {
  12236. // something went wrong
  12237. }
  12238. // async with promises
  12239. findAuthor().catch(function(reason){
  12240. // something went wrong
  12241. });
  12242. ```
  12243. @method catch
  12244. @param {Function} onRejection
  12245. Useful for tooling.
  12246. @return {Promise}
  12247. */
  12248. 'catch': function(onRejection) {
  12249. return this.then(null, onRejection);
  12250. }
  12251. };
  12252. function lib$es6$promise$polyfill$$polyfill() {
  12253. var local;
  12254. if (typeof global !== 'undefined') {
  12255. local = global;
  12256. } else if (typeof self !== 'undefined') {
  12257. local = self;
  12258. } else {
  12259. try {
  12260. local = Function('return this')();
  12261. } catch (e) {
  12262. throw new Error('polyfill failed because global object is unavailable in this environment');
  12263. }
  12264. }
  12265. var P = local.Promise;
  12266. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  12267. return;
  12268. }
  12269. local.Promise = lib$es6$promise$promise$$default;
  12270. }
  12271. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  12272. var lib$es6$promise$umd$$ES6Promise = {
  12273. 'Promise': lib$es6$promise$promise$$default,
  12274. 'polyfill': lib$es6$promise$polyfill$$default
  12275. };
  12276. /* global define:true module:true window: true */
  12277. if (typeof define === 'function' && define['amd']) {
  12278. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  12279. } else if (typeof module !== 'undefined' && module['exports']) {
  12280. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  12281. } else if (typeof this !== 'undefined') {
  12282. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  12283. }
  12284. lib$es6$promise$polyfill$$default();
  12285. }).call(this);
  12286. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12287. },{"_process":44}],46:[function(require,module,exports){
  12288. /* Copyright @ 2015 Atlassian Pty Ltd
  12289. *
  12290. * Licensed under the Apache License, Version 2.0 (the "License");
  12291. * you may not use this file except in compliance with the License.
  12292. * You may obtain a copy of the License at
  12293. *
  12294. * http://www.apache.org/licenses/LICENSE-2.0
  12295. *
  12296. * Unless required by applicable law or agreed to in writing, software
  12297. * distributed under the License is distributed on an "AS IS" BASIS,
  12298. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12299. * See the License for the specific language governing permissions and
  12300. * limitations under the License.
  12301. */
  12302. /**
  12303. * Ordered log levels.
  12304. */
  12305. var levels = {
  12306. "trace": 0,
  12307. "debug": 1,
  12308. "info": 2,
  12309. "log": 3,
  12310. "warn": 4,
  12311. "error": 5
  12312. };
  12313. /**
  12314. * Parses Error's object stack trace and extracts information about the last
  12315. * caller before the log method was called.
  12316. * @returns JS object with info about the caller - method name, file location,
  12317. * line and column.
  12318. */
  12319. function getCallerInfo() {
  12320. var callerInfo = {
  12321. methodName: "",
  12322. fileLocation: "",
  12323. line: null,
  12324. column: null
  12325. };
  12326. //gets the part of the stack without the logger wrappers
  12327. var error = new Error();
  12328. var stack = error.stack? error.stack.split("\n") : [];
  12329. if(!stack || stack.length < 1) {
  12330. return callerInfo;
  12331. }
  12332. var m = null;
  12333. if(stack[3]) {
  12334. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  12335. }
  12336. if(!m || m.length <= 4) {
  12337. //Firefox && Safari
  12338. if(stack[2].indexOf("log@") === 0){
  12339. //Safari
  12340. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  12341. } else {
  12342. //Firefox
  12343. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  12344. }
  12345. return callerInfo;
  12346. }
  12347. callerInfo.methodName = m[1];
  12348. callerInfo.fileLocation = m[2];
  12349. callerInfo.line = m[3];
  12350. callerInfo.column = m[4];
  12351. return callerInfo;
  12352. }
  12353. /**
  12354. * Logs messages using the transports and level from the logger.
  12355. * @param logger a logger instance.
  12356. * @param level the log level of the message. See the levels variable.
  12357. * @param arguments array with arguments that will be logged.
  12358. */
  12359. function log() {
  12360. var logger = arguments[0], level = arguments[1],
  12361. args = Array.prototype.slice.call(arguments, 2);
  12362. if(levels[level] <= logger.level) {
  12363. return;
  12364. }
  12365. var callerInfo = getCallerInfo();
  12366. for(var i = 0; i < logger.transports.length; i++) {
  12367. var t = logger.transports[i];
  12368. var l = t[level];
  12369. if(l && typeof(l) === "function") {
  12370. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  12371. .apply(t, args);
  12372. }
  12373. }
  12374. }
  12375. /**
  12376. *
  12377. * Constructs new logger object.
  12378. * @param level the logging level for the new logger
  12379. * @param id optional identifier for the logger instance.
  12380. * @param transports optional list of handlers(objects) for the logs.
  12381. * The handlers must support - log, warn, error, debug, info, trace.
  12382. * @param format optional (NOT implemented) string.
  12383. */
  12384. function Logger(level, id, transports, format) {
  12385. this.id = id;
  12386. this.format = format;
  12387. if(!this.transports) {
  12388. this.transports = [];
  12389. this.transports.push(Logger.consoleTransport);
  12390. }
  12391. this.level = levels[level];
  12392. var methods = Object.keys(levels);
  12393. for(var i = 0; i < methods.length; i++){
  12394. this[methods[i]] =
  12395. log.bind(null, this, methods[i]);
  12396. }
  12397. }
  12398. /**
  12399. * Sets the log level for the logger.
  12400. * @param level the new log level.
  12401. */
  12402. Logger.prototype.setLevel = function (level) {
  12403. this.level = levels[level];
  12404. };
  12405. module.exports = Logger;
  12406. /**
  12407. * The default transport - console
  12408. */
  12409. Logger.consoleTransport = console;
  12410. /**
  12411. * Enum for the supported log levels.
  12412. */
  12413. Logger.levels = {
  12414. TRACE: "trace",
  12415. DEBUG: "debug",
  12416. INFO: "info",
  12417. LOG: "log",
  12418. WARN: "warn",
  12419. ERROR: "error"
  12420. };
  12421. },{}],47:[function(require,module,exports){
  12422. /* Copyright @ 2015 Atlassian Pty Ltd
  12423. *
  12424. * Licensed under the Apache License, Version 2.0 (the "License");
  12425. * you may not use this file except in compliance with the License.
  12426. * You may obtain a copy of the License at
  12427. *
  12428. * http://www.apache.org/licenses/LICENSE-2.0
  12429. *
  12430. * Unless required by applicable law or agreed to in writing, software
  12431. * distributed under the License is distributed on an "AS IS" BASIS,
  12432. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12433. * See the License for the specific language governing permissions and
  12434. * limitations under the License.
  12435. */
  12436. var Logger = require("./Logger");
  12437. /**
  12438. * Map with the created loggers with ID.
  12439. */
  12440. var idLoggers = {};
  12441. /**
  12442. * Array with the loggers without id.
  12443. */
  12444. var loggers = [];
  12445. /**
  12446. * Log level for the lbrary.
  12447. */
  12448. var curLevel = Logger.levels.TRACE;
  12449. module.exports = {
  12450. /**
  12451. * Creates new logger.
  12452. * @arguments the same as Logger constructor
  12453. */
  12454. getLogger: function(id, transports, format) {
  12455. var logger = new Logger(curLevel, id, transports, format);
  12456. if(id) {
  12457. idLoggers[id] = idLoggers[id] || [];
  12458. idLoggers[id].push(logger);
  12459. } else {
  12460. loggers.push(logger);
  12461. }
  12462. return logger;
  12463. },
  12464. /**
  12465. * Changes the log level for the existing loggers by id.
  12466. * @param level the new log level.
  12467. * @param id if specified the level will be changed only for loggers with the
  12468. * same id. Otherwise the operation will affect all loggers that don't
  12469. * have id.
  12470. */
  12471. setLogLevelById: function(level, id) {
  12472. var l = id? (idLoggers[id] || []) : loggers;
  12473. for(var i = 0; i < l.length; i++) {
  12474. l[i].setLevel(level);
  12475. }
  12476. },
  12477. /**
  12478. * Changes the log level for all existing loggers.
  12479. * @param level the new log level.
  12480. */
  12481. setLogLevel: function (level) {
  12482. curLevel = level;
  12483. var i = 0;
  12484. for(; i < loggers.length; i++) {
  12485. loggers[i].setLevel(level);
  12486. }
  12487. for(var id in idLoggers) {
  12488. var l = idLoggers[id] || [];
  12489. for(i = 0; i < l.length; i++) {
  12490. l[i].setLevel(level);
  12491. }
  12492. }
  12493. },
  12494. /**
  12495. * The supported log levels.
  12496. */
  12497. levels: Logger.levels
  12498. };
  12499. },{"./Logger":46}],48:[function(require,module,exports){
  12500. // Top level file is just a mixin of submodules & constants
  12501. 'use strict';
  12502. var assign = require('./lib/utils/common').assign;
  12503. var deflate = require('./lib/deflate');
  12504. var inflate = require('./lib/inflate');
  12505. var constants = require('./lib/zlib/constants');
  12506. var pako = {};
  12507. assign(pako, deflate, inflate, constants);
  12508. module.exports = pako;
  12509. },{"./lib/deflate":49,"./lib/inflate":50,"./lib/utils/common":51,"./lib/zlib/constants":54}],49:[function(require,module,exports){
  12510. 'use strict';
  12511. var zlib_deflate = require('./zlib/deflate.js');
  12512. var utils = require('./utils/common');
  12513. var strings = require('./utils/strings');
  12514. var msg = require('./zlib/messages');
  12515. var zstream = require('./zlib/zstream');
  12516. var toString = Object.prototype.toString;
  12517. /* Public constants ==========================================================*/
  12518. /* ===========================================================================*/
  12519. var Z_NO_FLUSH = 0;
  12520. var Z_FINISH = 4;
  12521. var Z_OK = 0;
  12522. var Z_STREAM_END = 1;
  12523. var Z_SYNC_FLUSH = 2;
  12524. var Z_DEFAULT_COMPRESSION = -1;
  12525. var Z_DEFAULT_STRATEGY = 0;
  12526. var Z_DEFLATED = 8;
  12527. /* ===========================================================================*/
  12528. /**
  12529. * class Deflate
  12530. *
  12531. * Generic JS-style wrapper for zlib calls. If you don't need
  12532. * streaming behaviour - use more simple functions: [[deflate]],
  12533. * [[deflateRaw]] and [[gzip]].
  12534. **/
  12535. /* internal
  12536. * Deflate.chunks -> Array
  12537. *
  12538. * Chunks of output data, if [[Deflate#onData]] not overriden.
  12539. **/
  12540. /**
  12541. * Deflate.result -> Uint8Array|Array
  12542. *
  12543. * Compressed result, generated by default [[Deflate#onData]]
  12544. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  12545. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  12546. * push a chunk with explicit flush (call [[Deflate#push]] with
  12547. * `Z_SYNC_FLUSH` param).
  12548. **/
  12549. /**
  12550. * Deflate.err -> Number
  12551. *
  12552. * Error code after deflate finished. 0 (Z_OK) on success.
  12553. * You will not need it in real life, because deflate errors
  12554. * are possible only on wrong options or bad `onData` / `onEnd`
  12555. * custom handlers.
  12556. **/
  12557. /**
  12558. * Deflate.msg -> String
  12559. *
  12560. * Error message, if [[Deflate.err]] != 0
  12561. **/
  12562. /**
  12563. * new Deflate(options)
  12564. * - options (Object): zlib deflate options.
  12565. *
  12566. * Creates new deflator instance with specified params. Throws exception
  12567. * on bad params. Supported options:
  12568. *
  12569. * - `level`
  12570. * - `windowBits`
  12571. * - `memLevel`
  12572. * - `strategy`
  12573. *
  12574. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12575. * for more information on these.
  12576. *
  12577. * Additional options, for internal needs:
  12578. *
  12579. * - `chunkSize` - size of generated data chunks (16K by default)
  12580. * - `raw` (Boolean) - do raw deflate
  12581. * - `gzip` (Boolean) - create gzip wrapper
  12582. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12583. * (each char code [0..255])
  12584. * - `header` (Object) - custom header for gzip
  12585. * - `text` (Boolean) - true if compressed data believed to be text
  12586. * - `time` (Number) - modification time, unix timestamp
  12587. * - `os` (Number) - operation system code
  12588. * - `extra` (Array) - array of bytes with extra data (max 65536)
  12589. * - `name` (String) - file name (binary string)
  12590. * - `comment` (String) - comment (binary string)
  12591. * - `hcrc` (Boolean) - true if header crc should be added
  12592. *
  12593. * ##### Example:
  12594. *
  12595. * ```javascript
  12596. * var pako = require('pako')
  12597. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12598. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12599. *
  12600. * var deflate = new pako.Deflate({ level: 3});
  12601. *
  12602. * deflate.push(chunk1, false);
  12603. * deflate.push(chunk2, true); // true -> last chunk
  12604. *
  12605. * if (deflate.err) { throw new Error(deflate.err); }
  12606. *
  12607. * console.log(deflate.result);
  12608. * ```
  12609. **/
  12610. var Deflate = function(options) {
  12611. this.options = utils.assign({
  12612. level: Z_DEFAULT_COMPRESSION,
  12613. method: Z_DEFLATED,
  12614. chunkSize: 16384,
  12615. windowBits: 15,
  12616. memLevel: 8,
  12617. strategy: Z_DEFAULT_STRATEGY,
  12618. to: ''
  12619. }, options || {});
  12620. var opt = this.options;
  12621. if (opt.raw && (opt.windowBits > 0)) {
  12622. opt.windowBits = -opt.windowBits;
  12623. }
  12624. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  12625. opt.windowBits += 16;
  12626. }
  12627. this.err = 0; // error code, if happens (0 = Z_OK)
  12628. this.msg = ''; // error message
  12629. this.ended = false; // used to avoid multiple onEnd() calls
  12630. this.chunks = []; // chunks of compressed data
  12631. this.strm = new zstream();
  12632. this.strm.avail_out = 0;
  12633. var status = zlib_deflate.deflateInit2(
  12634. this.strm,
  12635. opt.level,
  12636. opt.method,
  12637. opt.windowBits,
  12638. opt.memLevel,
  12639. opt.strategy
  12640. );
  12641. if (status !== Z_OK) {
  12642. throw new Error(msg[status]);
  12643. }
  12644. if (opt.header) {
  12645. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  12646. }
  12647. };
  12648. /**
  12649. * Deflate#push(data[, mode]) -> Boolean
  12650. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  12651. * converted to utf8 byte sequence.
  12652. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12653. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12654. *
  12655. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  12656. * new compressed chunks. Returns `true` on success. The last data block must have
  12657. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12658. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12659. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  12660. *
  12661. * On fail call [[Deflate#onEnd]] with error code and return false.
  12662. *
  12663. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12664. * array format is detected automatically). Also, don't skip last param and always
  12665. * use the same type in your code (boolean or number). That will improve JS speed.
  12666. *
  12667. * For regular `Array`-s make sure all elements are [0..255].
  12668. *
  12669. * ##### Example
  12670. *
  12671. * ```javascript
  12672. * push(chunk, false); // push one of data chunks
  12673. * ...
  12674. * push(chunk, true); // push last chunk
  12675. * ```
  12676. **/
  12677. Deflate.prototype.push = function(data, mode) {
  12678. var strm = this.strm;
  12679. var chunkSize = this.options.chunkSize;
  12680. var status, _mode;
  12681. if (this.ended) { return false; }
  12682. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  12683. // Convert data if needed
  12684. if (typeof data === 'string') {
  12685. // If we need to compress text, change encoding to utf8.
  12686. strm.input = strings.string2buf(data);
  12687. } else if (toString.call(data) === '[object ArrayBuffer]') {
  12688. strm.input = new Uint8Array(data);
  12689. } else {
  12690. strm.input = data;
  12691. }
  12692. strm.next_in = 0;
  12693. strm.avail_in = strm.input.length;
  12694. do {
  12695. if (strm.avail_out === 0) {
  12696. strm.output = new utils.Buf8(chunkSize);
  12697. strm.next_out = 0;
  12698. strm.avail_out = chunkSize;
  12699. }
  12700. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  12701. if (status !== Z_STREAM_END && status !== Z_OK) {
  12702. this.onEnd(status);
  12703. this.ended = true;
  12704. return false;
  12705. }
  12706. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  12707. if (this.options.to === 'string') {
  12708. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  12709. } else {
  12710. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  12711. }
  12712. }
  12713. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  12714. // Finalize on the last chunk.
  12715. if (_mode === Z_FINISH) {
  12716. status = zlib_deflate.deflateEnd(this.strm);
  12717. this.onEnd(status);
  12718. this.ended = true;
  12719. return status === Z_OK;
  12720. }
  12721. // callback interim results if Z_SYNC_FLUSH.
  12722. if (_mode === Z_SYNC_FLUSH) {
  12723. this.onEnd(Z_OK);
  12724. strm.avail_out = 0;
  12725. return true;
  12726. }
  12727. return true;
  12728. };
  12729. /**
  12730. * Deflate#onData(chunk) -> Void
  12731. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  12732. * on js engine support. When string output requested, each chunk
  12733. * will be string.
  12734. *
  12735. * By default, stores data blocks in `chunks[]` property and glue
  12736. * those in `onEnd`. Override this handler, if you need another behaviour.
  12737. **/
  12738. Deflate.prototype.onData = function(chunk) {
  12739. this.chunks.push(chunk);
  12740. };
  12741. /**
  12742. * Deflate#onEnd(status) -> Void
  12743. * - status (Number): deflate status. 0 (Z_OK) on success,
  12744. * other if not.
  12745. *
  12746. * Called once after you tell deflate that the input stream is
  12747. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  12748. * or if an error happened. By default - join collected chunks,
  12749. * free memory and fill `results` / `err` properties.
  12750. **/
  12751. Deflate.prototype.onEnd = function(status) {
  12752. // On success - join
  12753. if (status === Z_OK) {
  12754. if (this.options.to === 'string') {
  12755. this.result = this.chunks.join('');
  12756. } else {
  12757. this.result = utils.flattenChunks(this.chunks);
  12758. }
  12759. }
  12760. this.chunks = [];
  12761. this.err = status;
  12762. this.msg = this.strm.msg;
  12763. };
  12764. /**
  12765. * deflate(data[, options]) -> Uint8Array|Array|String
  12766. * - data (Uint8Array|Array|String): input data to compress.
  12767. * - options (Object): zlib deflate options.
  12768. *
  12769. * Compress `data` with deflate alrorythm and `options`.
  12770. *
  12771. * Supported options are:
  12772. *
  12773. * - level
  12774. * - windowBits
  12775. * - memLevel
  12776. * - strategy
  12777. *
  12778. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12779. * for more information on these.
  12780. *
  12781. * Sugar (options):
  12782. *
  12783. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  12784. * negative windowBits implicitly.
  12785. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12786. * (each char code [0..255])
  12787. *
  12788. * ##### Example:
  12789. *
  12790. * ```javascript
  12791. * var pako = require('pako')
  12792. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  12793. *
  12794. * console.log(pako.deflate(data));
  12795. * ```
  12796. **/
  12797. function deflate(input, options) {
  12798. var deflator = new Deflate(options);
  12799. deflator.push(input, true);
  12800. // That will never happens, if you don't cheat with options :)
  12801. if (deflator.err) { throw deflator.msg; }
  12802. return deflator.result;
  12803. }
  12804. /**
  12805. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  12806. * - data (Uint8Array|Array|String): input data to compress.
  12807. * - options (Object): zlib deflate options.
  12808. *
  12809. * The same as [[deflate]], but creates raw data, without wrapper
  12810. * (header and adler32 crc).
  12811. **/
  12812. function deflateRaw(input, options) {
  12813. options = options || {};
  12814. options.raw = true;
  12815. return deflate(input, options);
  12816. }
  12817. /**
  12818. * gzip(data[, options]) -> Uint8Array|Array|String
  12819. * - data (Uint8Array|Array|String): input data to compress.
  12820. * - options (Object): zlib deflate options.
  12821. *
  12822. * The same as [[deflate]], but create gzip wrapper instead of
  12823. * deflate one.
  12824. **/
  12825. function gzip(input, options) {
  12826. options = options || {};
  12827. options.gzip = true;
  12828. return deflate(input, options);
  12829. }
  12830. exports.Deflate = Deflate;
  12831. exports.deflate = deflate;
  12832. exports.deflateRaw = deflateRaw;
  12833. exports.gzip = gzip;
  12834. },{"./utils/common":51,"./utils/strings":52,"./zlib/deflate.js":56,"./zlib/messages":61,"./zlib/zstream":63}],50:[function(require,module,exports){
  12835. 'use strict';
  12836. var zlib_inflate = require('./zlib/inflate.js');
  12837. var utils = require('./utils/common');
  12838. var strings = require('./utils/strings');
  12839. var c = require('./zlib/constants');
  12840. var msg = require('./zlib/messages');
  12841. var zstream = require('./zlib/zstream');
  12842. var gzheader = require('./zlib/gzheader');
  12843. var toString = Object.prototype.toString;
  12844. /**
  12845. * class Inflate
  12846. *
  12847. * Generic JS-style wrapper for zlib calls. If you don't need
  12848. * streaming behaviour - use more simple functions: [[inflate]]
  12849. * and [[inflateRaw]].
  12850. **/
  12851. /* internal
  12852. * inflate.chunks -> Array
  12853. *
  12854. * Chunks of output data, if [[Inflate#onData]] not overriden.
  12855. **/
  12856. /**
  12857. * Inflate.result -> Uint8Array|Array|String
  12858. *
  12859. * Uncompressed result, generated by default [[Inflate#onData]]
  12860. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  12861. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  12862. * push a chunk with explicit flush (call [[Inflate#push]] with
  12863. * `Z_SYNC_FLUSH` param).
  12864. **/
  12865. /**
  12866. * Inflate.err -> Number
  12867. *
  12868. * Error code after inflate finished. 0 (Z_OK) on success.
  12869. * Should be checked if broken data possible.
  12870. **/
  12871. /**
  12872. * Inflate.msg -> String
  12873. *
  12874. * Error message, if [[Inflate.err]] != 0
  12875. **/
  12876. /**
  12877. * new Inflate(options)
  12878. * - options (Object): zlib inflate options.
  12879. *
  12880. * Creates new inflator instance with specified params. Throws exception
  12881. * on bad params. Supported options:
  12882. *
  12883. * - `windowBits`
  12884. *
  12885. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12886. * for more information on these.
  12887. *
  12888. * Additional options, for internal needs:
  12889. *
  12890. * - `chunkSize` - size of generated data chunks (16K by default)
  12891. * - `raw` (Boolean) - do raw inflate
  12892. * - `to` (String) - if equal to 'string', then result will be converted
  12893. * from utf8 to utf16 (javascript) string. When string output requested,
  12894. * chunk length can differ from `chunkSize`, depending on content.
  12895. *
  12896. * By default, when no options set, autodetect deflate/gzip data format via
  12897. * wrapper header.
  12898. *
  12899. * ##### Example:
  12900. *
  12901. * ```javascript
  12902. * var pako = require('pako')
  12903. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12904. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12905. *
  12906. * var inflate = new pako.Inflate({ level: 3});
  12907. *
  12908. * inflate.push(chunk1, false);
  12909. * inflate.push(chunk2, true); // true -> last chunk
  12910. *
  12911. * if (inflate.err) { throw new Error(inflate.err); }
  12912. *
  12913. * console.log(inflate.result);
  12914. * ```
  12915. **/
  12916. var Inflate = function(options) {
  12917. this.options = utils.assign({
  12918. chunkSize: 16384,
  12919. windowBits: 0,
  12920. to: ''
  12921. }, options || {});
  12922. var opt = this.options;
  12923. // Force window size for `raw` data, if not set directly,
  12924. // because we have no header for autodetect.
  12925. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  12926. opt.windowBits = -opt.windowBits;
  12927. if (opt.windowBits === 0) { opt.windowBits = -15; }
  12928. }
  12929. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  12930. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  12931. !(options && options.windowBits)) {
  12932. opt.windowBits += 32;
  12933. }
  12934. // Gzip header has no info about windows size, we can do autodetect only
  12935. // for deflate. So, if window size not set, force it to max when gzip possible
  12936. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  12937. // bit 3 (16) -> gzipped data
  12938. // bit 4 (32) -> autodetect gzip/deflate
  12939. if ((opt.windowBits & 15) === 0) {
  12940. opt.windowBits |= 15;
  12941. }
  12942. }
  12943. this.err = 0; // error code, if happens (0 = Z_OK)
  12944. this.msg = ''; // error message
  12945. this.ended = false; // used to avoid multiple onEnd() calls
  12946. this.chunks = []; // chunks of compressed data
  12947. this.strm = new zstream();
  12948. this.strm.avail_out = 0;
  12949. var status = zlib_inflate.inflateInit2(
  12950. this.strm,
  12951. opt.windowBits
  12952. );
  12953. if (status !== c.Z_OK) {
  12954. throw new Error(msg[status]);
  12955. }
  12956. this.header = new gzheader();
  12957. zlib_inflate.inflateGetHeader(this.strm, this.header);
  12958. };
  12959. /**
  12960. * Inflate#push(data[, mode]) -> Boolean
  12961. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  12962. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12963. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12964. *
  12965. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  12966. * new output chunks. Returns `true` on success. The last data block must have
  12967. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12968. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12969. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  12970. *
  12971. * On fail call [[Inflate#onEnd]] with error code and return false.
  12972. *
  12973. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12974. * format is detected automatically). Also, don't skip last param and always
  12975. * use the same type in your code (boolean or number). That will improve JS speed.
  12976. *
  12977. * For regular `Array`-s make sure all elements are [0..255].
  12978. *
  12979. * ##### Example
  12980. *
  12981. * ```javascript
  12982. * push(chunk, false); // push one of data chunks
  12983. * ...
  12984. * push(chunk, true); // push last chunk
  12985. * ```
  12986. **/
  12987. Inflate.prototype.push = function(data, mode) {
  12988. var strm = this.strm;
  12989. var chunkSize = this.options.chunkSize;
  12990. var status, _mode;
  12991. var next_out_utf8, tail, utf8str;
  12992. // Flag to properly process Z_BUF_ERROR on testing inflate call
  12993. // when we check that all output data was flushed.
  12994. var allowBufError = false;
  12995. if (this.ended) { return false; }
  12996. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  12997. // Convert data if needed
  12998. if (typeof data === 'string') {
  12999. // Only binary strings can be decompressed on practice
  13000. strm.input = strings.binstring2buf(data);
  13001. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13002. strm.input = new Uint8Array(data);
  13003. } else {
  13004. strm.input = data;
  13005. }
  13006. strm.next_in = 0;
  13007. strm.avail_in = strm.input.length;
  13008. do {
  13009. if (strm.avail_out === 0) {
  13010. strm.output = new utils.Buf8(chunkSize);
  13011. strm.next_out = 0;
  13012. strm.avail_out = chunkSize;
  13013. }
  13014. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13015. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13016. status = c.Z_OK;
  13017. allowBufError = false;
  13018. }
  13019. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13020. this.onEnd(status);
  13021. this.ended = true;
  13022. return false;
  13023. }
  13024. if (strm.next_out) {
  13025. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13026. if (this.options.to === 'string') {
  13027. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13028. tail = strm.next_out - next_out_utf8;
  13029. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13030. // move tail
  13031. strm.next_out = tail;
  13032. strm.avail_out = chunkSize - tail;
  13033. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13034. this.onData(utf8str);
  13035. } else {
  13036. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13037. }
  13038. }
  13039. }
  13040. // When no more input data, we should check that internal inflate buffers
  13041. // are flushed. The only way to do it when avail_out = 0 - run one more
  13042. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13043. // Here we set flag to process this error properly.
  13044. //
  13045. // NOTE. Deflate does not return error in this case and does not needs such
  13046. // logic.
  13047. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13048. allowBufError = true;
  13049. }
  13050. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13051. if (status === c.Z_STREAM_END) {
  13052. _mode = c.Z_FINISH;
  13053. }
  13054. // Finalize on the last chunk.
  13055. if (_mode === c.Z_FINISH) {
  13056. status = zlib_inflate.inflateEnd(this.strm);
  13057. this.onEnd(status);
  13058. this.ended = true;
  13059. return status === c.Z_OK;
  13060. }
  13061. // callback interim results if Z_SYNC_FLUSH.
  13062. if (_mode === c.Z_SYNC_FLUSH) {
  13063. this.onEnd(c.Z_OK);
  13064. strm.avail_out = 0;
  13065. return true;
  13066. }
  13067. return true;
  13068. };
  13069. /**
  13070. * Inflate#onData(chunk) -> Void
  13071. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13072. * on js engine support. When string output requested, each chunk
  13073. * will be string.
  13074. *
  13075. * By default, stores data blocks in `chunks[]` property and glue
  13076. * those in `onEnd`. Override this handler, if you need another behaviour.
  13077. **/
  13078. Inflate.prototype.onData = function(chunk) {
  13079. this.chunks.push(chunk);
  13080. };
  13081. /**
  13082. * Inflate#onEnd(status) -> Void
  13083. * - status (Number): inflate status. 0 (Z_OK) on success,
  13084. * other if not.
  13085. *
  13086. * Called either after you tell inflate that the input stream is
  13087. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13088. * or if an error happened. By default - join collected chunks,
  13089. * free memory and fill `results` / `err` properties.
  13090. **/
  13091. Inflate.prototype.onEnd = function(status) {
  13092. // On success - join
  13093. if (status === c.Z_OK) {
  13094. if (this.options.to === 'string') {
  13095. // Glue & convert here, until we teach pako to send
  13096. // utf8 alligned strings to onData
  13097. this.result = this.chunks.join('');
  13098. } else {
  13099. this.result = utils.flattenChunks(this.chunks);
  13100. }
  13101. }
  13102. this.chunks = [];
  13103. this.err = status;
  13104. this.msg = this.strm.msg;
  13105. };
  13106. /**
  13107. * inflate(data[, options]) -> Uint8Array|Array|String
  13108. * - data (Uint8Array|Array|String): input data to decompress.
  13109. * - options (Object): zlib inflate options.
  13110. *
  13111. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  13112. * format via wrapper header by default. That's why we don't provide
  13113. * separate `ungzip` method.
  13114. *
  13115. * Supported options are:
  13116. *
  13117. * - windowBits
  13118. *
  13119. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13120. * for more information.
  13121. *
  13122. * Sugar (options):
  13123. *
  13124. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13125. * negative windowBits implicitly.
  13126. * - `to` (String) - if equal to 'string', then result will be converted
  13127. * from utf8 to utf16 (javascript) string. When string output requested,
  13128. * chunk length can differ from `chunkSize`, depending on content.
  13129. *
  13130. *
  13131. * ##### Example:
  13132. *
  13133. * ```javascript
  13134. * var pako = require('pako')
  13135. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  13136. * , output;
  13137. *
  13138. * try {
  13139. * output = pako.inflate(input);
  13140. * } catch (err)
  13141. * console.log(err);
  13142. * }
  13143. * ```
  13144. **/
  13145. function inflate(input, options) {
  13146. var inflator = new Inflate(options);
  13147. inflator.push(input, true);
  13148. // That will never happens, if you don't cheat with options :)
  13149. if (inflator.err) { throw inflator.msg; }
  13150. return inflator.result;
  13151. }
  13152. /**
  13153. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  13154. * - data (Uint8Array|Array|String): input data to decompress.
  13155. * - options (Object): zlib inflate options.
  13156. *
  13157. * The same as [[inflate]], but creates raw data, without wrapper
  13158. * (header and adler32 crc).
  13159. **/
  13160. function inflateRaw(input, options) {
  13161. options = options || {};
  13162. options.raw = true;
  13163. return inflate(input, options);
  13164. }
  13165. /**
  13166. * ungzip(data[, options]) -> Uint8Array|Array|String
  13167. * - data (Uint8Array|Array|String): input data to decompress.
  13168. * - options (Object): zlib inflate options.
  13169. *
  13170. * Just shortcut to [[inflate]], because it autodetects format
  13171. * by header.content. Done for convenience.
  13172. **/
  13173. exports.Inflate = Inflate;
  13174. exports.inflate = inflate;
  13175. exports.inflateRaw = inflateRaw;
  13176. exports.ungzip = inflate;
  13177. },{"./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){
  13178. 'use strict';
  13179. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  13180. (typeof Uint16Array !== 'undefined') &&
  13181. (typeof Int32Array !== 'undefined');
  13182. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  13183. var sources = Array.prototype.slice.call(arguments, 1);
  13184. while (sources.length) {
  13185. var source = sources.shift();
  13186. if (!source) { continue; }
  13187. if (typeof source !== 'object') {
  13188. throw new TypeError(source + 'must be non-object');
  13189. }
  13190. for (var p in source) {
  13191. if (source.hasOwnProperty(p)) {
  13192. obj[p] = source[p];
  13193. }
  13194. }
  13195. }
  13196. return obj;
  13197. };
  13198. // reduce buffer size, avoiding mem copy
  13199. exports.shrinkBuf = function (buf, size) {
  13200. if (buf.length === size) { return buf; }
  13201. if (buf.subarray) { return buf.subarray(0, size); }
  13202. buf.length = size;
  13203. return buf;
  13204. };
  13205. var fnTyped = {
  13206. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13207. if (src.subarray && dest.subarray) {
  13208. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  13209. return;
  13210. }
  13211. // Fallback to ordinary array
  13212. for (var i=0; i<len; i++) {
  13213. dest[dest_offs + i] = src[src_offs + i];
  13214. }
  13215. },
  13216. // Join array of chunks to single array.
  13217. flattenChunks: function(chunks) {
  13218. var i, l, len, pos, chunk, result;
  13219. // calculate data length
  13220. len = 0;
  13221. for (i=0, l=chunks.length; i<l; i++) {
  13222. len += chunks[i].length;
  13223. }
  13224. // join chunks
  13225. result = new Uint8Array(len);
  13226. pos = 0;
  13227. for (i=0, l=chunks.length; i<l; i++) {
  13228. chunk = chunks[i];
  13229. result.set(chunk, pos);
  13230. pos += chunk.length;
  13231. }
  13232. return result;
  13233. }
  13234. };
  13235. var fnUntyped = {
  13236. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13237. for (var i=0; i<len; i++) {
  13238. dest[dest_offs + i] = src[src_offs + i];
  13239. }
  13240. },
  13241. // Join array of chunks to single array.
  13242. flattenChunks: function(chunks) {
  13243. return [].concat.apply([], chunks);
  13244. }
  13245. };
  13246. // Enable/Disable typed arrays use, for testing
  13247. //
  13248. exports.setTyped = function (on) {
  13249. if (on) {
  13250. exports.Buf8 = Uint8Array;
  13251. exports.Buf16 = Uint16Array;
  13252. exports.Buf32 = Int32Array;
  13253. exports.assign(exports, fnTyped);
  13254. } else {
  13255. exports.Buf8 = Array;
  13256. exports.Buf16 = Array;
  13257. exports.Buf32 = Array;
  13258. exports.assign(exports, fnUntyped);
  13259. }
  13260. };
  13261. exports.setTyped(TYPED_OK);
  13262. },{}],52:[function(require,module,exports){
  13263. // String encode/decode helpers
  13264. 'use strict';
  13265. var utils = require('./common');
  13266. // Quick check if we can use fast array to bin string conversion
  13267. //
  13268. // - apply(Array) can fail on Android 2.2
  13269. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  13270. //
  13271. var STR_APPLY_OK = true;
  13272. var STR_APPLY_UIA_OK = true;
  13273. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  13274. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  13275. // Table with utf8 lengths (calculated by first byte of sequence)
  13276. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13277. // because max possible codepoint is 0x10ffff
  13278. var _utf8len = new utils.Buf8(256);
  13279. for (var q=0; q<256; q++) {
  13280. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  13281. }
  13282. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  13283. // convert string to array (typed, when possible)
  13284. exports.string2buf = function (str) {
  13285. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13286. // count binary size
  13287. for (m_pos = 0; m_pos < str_len; m_pos++) {
  13288. c = str.charCodeAt(m_pos);
  13289. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13290. c2 = str.charCodeAt(m_pos+1);
  13291. if ((c2 & 0xfc00) === 0xdc00) {
  13292. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13293. m_pos++;
  13294. }
  13295. }
  13296. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  13297. }
  13298. // allocate buffer
  13299. buf = new utils.Buf8(buf_len);
  13300. // convert
  13301. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  13302. c = str.charCodeAt(m_pos);
  13303. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13304. c2 = str.charCodeAt(m_pos+1);
  13305. if ((c2 & 0xfc00) === 0xdc00) {
  13306. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13307. m_pos++;
  13308. }
  13309. }
  13310. if (c < 0x80) {
  13311. /* one byte */
  13312. buf[i++] = c;
  13313. } else if (c < 0x800) {
  13314. /* two bytes */
  13315. buf[i++] = 0xC0 | (c >>> 6);
  13316. buf[i++] = 0x80 | (c & 0x3f);
  13317. } else if (c < 0x10000) {
  13318. /* three bytes */
  13319. buf[i++] = 0xE0 | (c >>> 12);
  13320. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13321. buf[i++] = 0x80 | (c & 0x3f);
  13322. } else {
  13323. /* four bytes */
  13324. buf[i++] = 0xf0 | (c >>> 18);
  13325. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  13326. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13327. buf[i++] = 0x80 | (c & 0x3f);
  13328. }
  13329. }
  13330. return buf;
  13331. };
  13332. // Helper (used in 2 places)
  13333. function buf2binstring(buf, len) {
  13334. // use fallback for big arrays to avoid stack overflow
  13335. if (len < 65537) {
  13336. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  13337. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  13338. }
  13339. }
  13340. var result = '';
  13341. for (var i=0; i < len; i++) {
  13342. result += String.fromCharCode(buf[i]);
  13343. }
  13344. return result;
  13345. }
  13346. // Convert byte array to binary string
  13347. exports.buf2binstring = function(buf) {
  13348. return buf2binstring(buf, buf.length);
  13349. };
  13350. // Convert binary string (typed, when possible)
  13351. exports.binstring2buf = function(str) {
  13352. var buf = new utils.Buf8(str.length);
  13353. for (var i=0, len=buf.length; i < len; i++) {
  13354. buf[i] = str.charCodeAt(i);
  13355. }
  13356. return buf;
  13357. };
  13358. // convert array to string
  13359. exports.buf2string = function (buf, max) {
  13360. var i, out, c, c_len;
  13361. var len = max || buf.length;
  13362. // Reserve max possible length (2 words per char)
  13363. // NB: by unknown reasons, Array is significantly faster for
  13364. // String.fromCharCode.apply than Uint16Array.
  13365. var utf16buf = new Array(len*2);
  13366. for (out=0, i=0; i<len;) {
  13367. c = buf[i++];
  13368. // quick process ascii
  13369. if (c < 0x80) { utf16buf[out++] = c; continue; }
  13370. c_len = _utf8len[c];
  13371. // skip 5 & 6 byte codes
  13372. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  13373. // apply mask on first byte
  13374. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  13375. // join the rest
  13376. while (c_len > 1 && i < len) {
  13377. c = (c << 6) | (buf[i++] & 0x3f);
  13378. c_len--;
  13379. }
  13380. // terminated by end of string?
  13381. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  13382. if (c < 0x10000) {
  13383. utf16buf[out++] = c;
  13384. } else {
  13385. c -= 0x10000;
  13386. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  13387. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  13388. }
  13389. }
  13390. return buf2binstring(utf16buf, out);
  13391. };
  13392. // Calculate max possible position in utf8 buffer,
  13393. // that will not break sequence. If that's not possible
  13394. // - (very small limits) return max size as is.
  13395. //
  13396. // buf[] - utf8 bytes array
  13397. // max - length limit (mandatory);
  13398. exports.utf8border = function(buf, max) {
  13399. var pos;
  13400. max = max || buf.length;
  13401. if (max > buf.length) { max = buf.length; }
  13402. // go back from last position, until start of sequence found
  13403. pos = max-1;
  13404. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  13405. // Fuckup - very small and broken sequence,
  13406. // return max, because we should return something anyway.
  13407. if (pos < 0) { return max; }
  13408. // If we came to start of buffer - that means vuffer is too small,
  13409. // return max too.
  13410. if (pos === 0) { return max; }
  13411. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  13412. };
  13413. },{"./common":51}],53:[function(require,module,exports){
  13414. 'use strict';
  13415. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  13416. // It doesn't worth to make additional optimizationa as in original.
  13417. // Small size is preferable.
  13418. function adler32(adler, buf, len, pos) {
  13419. var s1 = (adler & 0xffff) |0,
  13420. s2 = ((adler >>> 16) & 0xffff) |0,
  13421. n = 0;
  13422. while (len !== 0) {
  13423. // Set limit ~ twice less than 5552, to keep
  13424. // s2 in 31-bits, because we force signed ints.
  13425. // in other case %= will fail.
  13426. n = len > 2000 ? 2000 : len;
  13427. len -= n;
  13428. do {
  13429. s1 = (s1 + buf[pos++]) |0;
  13430. s2 = (s2 + s1) |0;
  13431. } while (--n);
  13432. s1 %= 65521;
  13433. s2 %= 65521;
  13434. }
  13435. return (s1 | (s2 << 16)) |0;
  13436. }
  13437. module.exports = adler32;
  13438. },{}],54:[function(require,module,exports){
  13439. module.exports = {
  13440. /* Allowed flush values; see deflate() and inflate() below for details */
  13441. Z_NO_FLUSH: 0,
  13442. Z_PARTIAL_FLUSH: 1,
  13443. Z_SYNC_FLUSH: 2,
  13444. Z_FULL_FLUSH: 3,
  13445. Z_FINISH: 4,
  13446. Z_BLOCK: 5,
  13447. Z_TREES: 6,
  13448. /* Return codes for the compression/decompression functions. Negative values
  13449. * are errors, positive values are used for special but normal events.
  13450. */
  13451. Z_OK: 0,
  13452. Z_STREAM_END: 1,
  13453. Z_NEED_DICT: 2,
  13454. Z_ERRNO: -1,
  13455. Z_STREAM_ERROR: -2,
  13456. Z_DATA_ERROR: -3,
  13457. //Z_MEM_ERROR: -4,
  13458. Z_BUF_ERROR: -5,
  13459. //Z_VERSION_ERROR: -6,
  13460. /* compression levels */
  13461. Z_NO_COMPRESSION: 0,
  13462. Z_BEST_SPEED: 1,
  13463. Z_BEST_COMPRESSION: 9,
  13464. Z_DEFAULT_COMPRESSION: -1,
  13465. Z_FILTERED: 1,
  13466. Z_HUFFMAN_ONLY: 2,
  13467. Z_RLE: 3,
  13468. Z_FIXED: 4,
  13469. Z_DEFAULT_STRATEGY: 0,
  13470. /* Possible values of the data_type field (though see inflate()) */
  13471. Z_BINARY: 0,
  13472. Z_TEXT: 1,
  13473. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  13474. Z_UNKNOWN: 2,
  13475. /* The deflate compression method */
  13476. Z_DEFLATED: 8
  13477. //Z_NULL: null // Use -1 or null inline, depending on var type
  13478. };
  13479. },{}],55:[function(require,module,exports){
  13480. 'use strict';
  13481. // Note: we can't get significant speed boost here.
  13482. // So write code to minimize size - no pregenerated tables
  13483. // and array tools dependencies.
  13484. // Use ordinary array, since untyped makes no boost here
  13485. function makeTable() {
  13486. var c, table = [];
  13487. for (var n =0; n < 256; n++) {
  13488. c = n;
  13489. for (var k =0; k < 8; k++) {
  13490. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  13491. }
  13492. table[n] = c;
  13493. }
  13494. return table;
  13495. }
  13496. // Create table on load. Just 255 signed longs. Not a problem.
  13497. var crcTable = makeTable();
  13498. function crc32(crc, buf, len, pos) {
  13499. var t = crcTable,
  13500. end = pos + len;
  13501. crc = crc ^ (-1);
  13502. for (var i = pos; i < end; i++) {
  13503. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  13504. }
  13505. return (crc ^ (-1)); // >>> 0;
  13506. }
  13507. module.exports = crc32;
  13508. },{}],56:[function(require,module,exports){
  13509. 'use strict';
  13510. var utils = require('../utils/common');
  13511. var trees = require('./trees');
  13512. var adler32 = require('./adler32');
  13513. var crc32 = require('./crc32');
  13514. var msg = require('./messages');
  13515. /* Public constants ==========================================================*/
  13516. /* ===========================================================================*/
  13517. /* Allowed flush values; see deflate() and inflate() below for details */
  13518. var Z_NO_FLUSH = 0;
  13519. var Z_PARTIAL_FLUSH = 1;
  13520. //var Z_SYNC_FLUSH = 2;
  13521. var Z_FULL_FLUSH = 3;
  13522. var Z_FINISH = 4;
  13523. var Z_BLOCK = 5;
  13524. //var Z_TREES = 6;
  13525. /* Return codes for the compression/decompression functions. Negative values
  13526. * are errors, positive values are used for special but normal events.
  13527. */
  13528. var Z_OK = 0;
  13529. var Z_STREAM_END = 1;
  13530. //var Z_NEED_DICT = 2;
  13531. //var Z_ERRNO = -1;
  13532. var Z_STREAM_ERROR = -2;
  13533. var Z_DATA_ERROR = -3;
  13534. //var Z_MEM_ERROR = -4;
  13535. var Z_BUF_ERROR = -5;
  13536. //var Z_VERSION_ERROR = -6;
  13537. /* compression levels */
  13538. //var Z_NO_COMPRESSION = 0;
  13539. //var Z_BEST_SPEED = 1;
  13540. //var Z_BEST_COMPRESSION = 9;
  13541. var Z_DEFAULT_COMPRESSION = -1;
  13542. var Z_FILTERED = 1;
  13543. var Z_HUFFMAN_ONLY = 2;
  13544. var Z_RLE = 3;
  13545. var Z_FIXED = 4;
  13546. var Z_DEFAULT_STRATEGY = 0;
  13547. /* Possible values of the data_type field (though see inflate()) */
  13548. //var Z_BINARY = 0;
  13549. //var Z_TEXT = 1;
  13550. //var Z_ASCII = 1; // = Z_TEXT
  13551. var Z_UNKNOWN = 2;
  13552. /* The deflate compression method */
  13553. var Z_DEFLATED = 8;
  13554. /*============================================================================*/
  13555. var MAX_MEM_LEVEL = 9;
  13556. /* Maximum value for memLevel in deflateInit2 */
  13557. var MAX_WBITS = 15;
  13558. /* 32K LZ77 window */
  13559. var DEF_MEM_LEVEL = 8;
  13560. var LENGTH_CODES = 29;
  13561. /* number of length codes, not counting the special END_BLOCK code */
  13562. var LITERALS = 256;
  13563. /* number of literal bytes 0..255 */
  13564. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  13565. /* number of Literal or Length codes, including the END_BLOCK code */
  13566. var D_CODES = 30;
  13567. /* number of distance codes */
  13568. var BL_CODES = 19;
  13569. /* number of codes used to transfer the bit lengths */
  13570. var HEAP_SIZE = 2*L_CODES + 1;
  13571. /* maximum heap size */
  13572. var MAX_BITS = 15;
  13573. /* All codes must not exceed MAX_BITS bits */
  13574. var MIN_MATCH = 3;
  13575. var MAX_MATCH = 258;
  13576. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  13577. var PRESET_DICT = 0x20;
  13578. var INIT_STATE = 42;
  13579. var EXTRA_STATE = 69;
  13580. var NAME_STATE = 73;
  13581. var COMMENT_STATE = 91;
  13582. var HCRC_STATE = 103;
  13583. var BUSY_STATE = 113;
  13584. var FINISH_STATE = 666;
  13585. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  13586. var BS_BLOCK_DONE = 2; /* block flush performed */
  13587. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  13588. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  13589. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  13590. function err(strm, errorCode) {
  13591. strm.msg = msg[errorCode];
  13592. return errorCode;
  13593. }
  13594. function rank(f) {
  13595. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  13596. }
  13597. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  13598. /* =========================================================================
  13599. * Flush as much pending output as possible. All deflate() output goes
  13600. * through this function so some applications may wish to modify it
  13601. * to avoid allocating a large strm->output buffer and copying into it.
  13602. * (See also read_buf()).
  13603. */
  13604. function flush_pending(strm) {
  13605. var s = strm.state;
  13606. //_tr_flush_bits(s);
  13607. var len = s.pending;
  13608. if (len > strm.avail_out) {
  13609. len = strm.avail_out;
  13610. }
  13611. if (len === 0) { return; }
  13612. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  13613. strm.next_out += len;
  13614. s.pending_out += len;
  13615. strm.total_out += len;
  13616. strm.avail_out -= len;
  13617. s.pending -= len;
  13618. if (s.pending === 0) {
  13619. s.pending_out = 0;
  13620. }
  13621. }
  13622. function flush_block_only (s, last) {
  13623. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  13624. s.block_start = s.strstart;
  13625. flush_pending(s.strm);
  13626. }
  13627. function put_byte(s, b) {
  13628. s.pending_buf[s.pending++] = b;
  13629. }
  13630. /* =========================================================================
  13631. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  13632. * IN assertion: the stream state is correct and there is enough room in
  13633. * pending_buf.
  13634. */
  13635. function putShortMSB(s, b) {
  13636. // put_byte(s, (Byte)(b >> 8));
  13637. // put_byte(s, (Byte)(b & 0xff));
  13638. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  13639. s.pending_buf[s.pending++] = b & 0xff;
  13640. }
  13641. /* ===========================================================================
  13642. * Read a new buffer from the current input stream, update the adler32
  13643. * and total number of bytes read. All deflate() input goes through
  13644. * this function so some applications may wish to modify it to avoid
  13645. * allocating a large strm->input buffer and copying from it.
  13646. * (See also flush_pending()).
  13647. */
  13648. function read_buf(strm, buf, start, size) {
  13649. var len = strm.avail_in;
  13650. if (len > size) { len = size; }
  13651. if (len === 0) { return 0; }
  13652. strm.avail_in -= len;
  13653. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  13654. if (strm.state.wrap === 1) {
  13655. strm.adler = adler32(strm.adler, buf, len, start);
  13656. }
  13657. else if (strm.state.wrap === 2) {
  13658. strm.adler = crc32(strm.adler, buf, len, start);
  13659. }
  13660. strm.next_in += len;
  13661. strm.total_in += len;
  13662. return len;
  13663. }
  13664. /* ===========================================================================
  13665. * Set match_start to the longest match starting at the given string and
  13666. * return its length. Matches shorter or equal to prev_length are discarded,
  13667. * in which case the result is equal to prev_length and match_start is
  13668. * garbage.
  13669. * IN assertions: cur_match is the head of the hash chain for the current
  13670. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  13671. * OUT assertion: the match length is not greater than s->lookahead.
  13672. */
  13673. function longest_match(s, cur_match) {
  13674. var chain_length = s.max_chain_length; /* max hash chain length */
  13675. var scan = s.strstart; /* current string */
  13676. var match; /* matched string */
  13677. var len; /* length of current match */
  13678. var best_len = s.prev_length; /* best match length so far */
  13679. var nice_match = s.nice_match; /* stop if match long enough */
  13680. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  13681. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  13682. var _win = s.window; // shortcut
  13683. var wmask = s.w_mask;
  13684. var prev = s.prev;
  13685. /* Stop when cur_match becomes <= limit. To simplify the code,
  13686. * we prevent matches with the string of window index 0.
  13687. */
  13688. var strend = s.strstart + MAX_MATCH;
  13689. var scan_end1 = _win[scan + best_len - 1];
  13690. var scan_end = _win[scan + best_len];
  13691. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  13692. * It is easy to get rid of this optimization if necessary.
  13693. */
  13694. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  13695. /* Do not waste too much time if we already have a good match: */
  13696. if (s.prev_length >= s.good_match) {
  13697. chain_length >>= 2;
  13698. }
  13699. /* Do not look for matches beyond the end of the input. This is necessary
  13700. * to make deflate deterministic.
  13701. */
  13702. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  13703. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  13704. do {
  13705. // Assert(cur_match < s->strstart, "no future");
  13706. match = cur_match;
  13707. /* Skip to next match if the match length cannot increase
  13708. * or if the match length is less than 2. Note that the checks below
  13709. * for insufficient lookahead only occur occasionally for performance
  13710. * reasons. Therefore uninitialized memory will be accessed, and
  13711. * conditional jumps will be made that depend on those values.
  13712. * However the length of the match is limited to the lookahead, so
  13713. * the output of deflate is not affected by the uninitialized values.
  13714. */
  13715. if (_win[match + best_len] !== scan_end ||
  13716. _win[match + best_len - 1] !== scan_end1 ||
  13717. _win[match] !== _win[scan] ||
  13718. _win[++match] !== _win[scan + 1]) {
  13719. continue;
  13720. }
  13721. /* The check at best_len-1 can be removed because it will be made
  13722. * again later. (This heuristic is not always a win.)
  13723. * It is not necessary to compare scan[2] and match[2] since they
  13724. * are always equal when the other bytes match, given that
  13725. * the hash keys are equal and that HASH_BITS >= 8.
  13726. */
  13727. scan += 2;
  13728. match++;
  13729. // Assert(*scan == *match, "match[2]?");
  13730. /* We check for insufficient lookahead only every 8th comparison;
  13731. * the 256th check will be made at strstart+258.
  13732. */
  13733. do {
  13734. /*jshint noempty:false*/
  13735. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13736. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13737. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13738. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13739. scan < strend);
  13740. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  13741. len = MAX_MATCH - (strend - scan);
  13742. scan = strend - MAX_MATCH;
  13743. if (len > best_len) {
  13744. s.match_start = cur_match;
  13745. best_len = len;
  13746. if (len >= nice_match) {
  13747. break;
  13748. }
  13749. scan_end1 = _win[scan + best_len - 1];
  13750. scan_end = _win[scan + best_len];
  13751. }
  13752. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  13753. if (best_len <= s.lookahead) {
  13754. return best_len;
  13755. }
  13756. return s.lookahead;
  13757. }
  13758. /* ===========================================================================
  13759. * Fill the window when the lookahead becomes insufficient.
  13760. * Updates strstart and lookahead.
  13761. *
  13762. * IN assertion: lookahead < MIN_LOOKAHEAD
  13763. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  13764. * At least one byte has been read, or avail_in == 0; reads are
  13765. * performed for at least two bytes (required for the zip translate_eol
  13766. * option -- not supported here).
  13767. */
  13768. function fill_window(s) {
  13769. var _w_size = s.w_size;
  13770. var p, n, m, more, str;
  13771. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  13772. do {
  13773. more = s.window_size - s.lookahead - s.strstart;
  13774. // JS ints have 32 bit, block below not needed
  13775. /* Deal with !@#$% 64K limit: */
  13776. //if (sizeof(int) <= 2) {
  13777. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  13778. // more = wsize;
  13779. //
  13780. // } else if (more == (unsigned)(-1)) {
  13781. // /* Very unlikely, but possible on 16 bit machine if
  13782. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  13783. // */
  13784. // more--;
  13785. // }
  13786. //}
  13787. /* If the window is almost full and there is insufficient lookahead,
  13788. * move the upper half to the lower one to make room in the upper half.
  13789. */
  13790. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  13791. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  13792. s.match_start -= _w_size;
  13793. s.strstart -= _w_size;
  13794. /* we now have strstart >= MAX_DIST */
  13795. s.block_start -= _w_size;
  13796. /* Slide the hash table (could be avoided with 32 bit values
  13797. at the expense of memory usage). We slide even when level == 0
  13798. to keep the hash table consistent if we switch back to level > 0
  13799. later. (Using level 0 permanently is not an optimal usage of
  13800. zlib, so we don't care about this pathological case.)
  13801. */
  13802. n = s.hash_size;
  13803. p = n;
  13804. do {
  13805. m = s.head[--p];
  13806. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  13807. } while (--n);
  13808. n = _w_size;
  13809. p = n;
  13810. do {
  13811. m = s.prev[--p];
  13812. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  13813. /* If n is not on any hash chain, prev[n] is garbage but
  13814. * its value will never be used.
  13815. */
  13816. } while (--n);
  13817. more += _w_size;
  13818. }
  13819. if (s.strm.avail_in === 0) {
  13820. break;
  13821. }
  13822. /* If there was no sliding:
  13823. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  13824. * more == window_size - lookahead - strstart
  13825. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  13826. * => more >= window_size - 2*WSIZE + 2
  13827. * In the BIG_MEM or MMAP case (not yet supported),
  13828. * window_size == input_size + MIN_LOOKAHEAD &&
  13829. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  13830. * Otherwise, window_size == 2*WSIZE so more >= 2.
  13831. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  13832. */
  13833. //Assert(more >= 2, "more < 2");
  13834. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  13835. s.lookahead += n;
  13836. /* Initialize the hash value now that we have some input: */
  13837. if (s.lookahead + s.insert >= MIN_MATCH) {
  13838. str = s.strstart - s.insert;
  13839. s.ins_h = s.window[str];
  13840. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  13841. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  13842. //#if MIN_MATCH != 3
  13843. // Call update_hash() MIN_MATCH-3 more times
  13844. //#endif
  13845. while (s.insert) {
  13846. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  13847. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  13848. s.prev[str & s.w_mask] = s.head[s.ins_h];
  13849. s.head[s.ins_h] = str;
  13850. str++;
  13851. s.insert--;
  13852. if (s.lookahead + s.insert < MIN_MATCH) {
  13853. break;
  13854. }
  13855. }
  13856. }
  13857. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  13858. * but this is not important since only literal bytes will be emitted.
  13859. */
  13860. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  13861. /* If the WIN_INIT bytes after the end of the current data have never been
  13862. * written, then zero those bytes in order to avoid memory check reports of
  13863. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  13864. * the longest match routines. Update the high water mark for the next
  13865. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  13866. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  13867. */
  13868. // if (s.high_water < s.window_size) {
  13869. // var curr = s.strstart + s.lookahead;
  13870. // var init = 0;
  13871. //
  13872. // if (s.high_water < curr) {
  13873. // /* Previous high water mark below current data -- zero WIN_INIT
  13874. // * bytes or up to end of window, whichever is less.
  13875. // */
  13876. // init = s.window_size - curr;
  13877. // if (init > WIN_INIT)
  13878. // init = WIN_INIT;
  13879. // zmemzero(s->window + curr, (unsigned)init);
  13880. // s->high_water = curr + init;
  13881. // }
  13882. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  13883. // /* High water mark at or above current data, but below current data
  13884. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  13885. // * to end of window, whichever is less.
  13886. // */
  13887. // init = (ulg)curr + WIN_INIT - s->high_water;
  13888. // if (init > s->window_size - s->high_water)
  13889. // init = s->window_size - s->high_water;
  13890. // zmemzero(s->window + s->high_water, (unsigned)init);
  13891. // s->high_water += init;
  13892. // }
  13893. // }
  13894. //
  13895. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  13896. // "not enough room for search");
  13897. }
  13898. /* ===========================================================================
  13899. * Copy without compression as much as possible from the input stream, return
  13900. * the current block state.
  13901. * This function does not insert new strings in the dictionary since
  13902. * uncompressible data is probably not useful. This function is used
  13903. * only for the level=0 compression option.
  13904. * NOTE: this function should be optimized to avoid extra copying from
  13905. * window to pending_buf.
  13906. */
  13907. function deflate_stored(s, flush) {
  13908. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  13909. * to pending_buf_size, and each stored block has a 5 byte header:
  13910. */
  13911. var max_block_size = 0xffff;
  13912. if (max_block_size > s.pending_buf_size - 5) {
  13913. max_block_size = s.pending_buf_size - 5;
  13914. }
  13915. /* Copy as much as possible from input to output: */
  13916. for (;;) {
  13917. /* Fill the window as much as possible: */
  13918. if (s.lookahead <= 1) {
  13919. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  13920. // s->block_start >= (long)s->w_size, "slide too late");
  13921. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  13922. // s.block_start >= s.w_size)) {
  13923. // throw new Error("slide too late");
  13924. // }
  13925. fill_window(s);
  13926. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  13927. return BS_NEED_MORE;
  13928. }
  13929. if (s.lookahead === 0) {
  13930. break;
  13931. }
  13932. /* flush the current block */
  13933. }
  13934. //Assert(s->block_start >= 0L, "block gone");
  13935. // if (s.block_start < 0) throw new Error("block gone");
  13936. s.strstart += s.lookahead;
  13937. s.lookahead = 0;
  13938. /* Emit a stored block if pending_buf will be full: */
  13939. var max_start = s.block_start + max_block_size;
  13940. if (s.strstart === 0 || s.strstart >= max_start) {
  13941. /* strstart == 0 is possible when wraparound on 16-bit machine */
  13942. s.lookahead = s.strstart - max_start;
  13943. s.strstart = max_start;
  13944. /*** FLUSH_BLOCK(s, 0); ***/
  13945. flush_block_only(s, false);
  13946. if (s.strm.avail_out === 0) {
  13947. return BS_NEED_MORE;
  13948. }
  13949. /***/
  13950. }
  13951. /* Flush if we may have to slide, otherwise block_start may become
  13952. * negative and the data will be gone:
  13953. */
  13954. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  13955. /*** FLUSH_BLOCK(s, 0); ***/
  13956. flush_block_only(s, false);
  13957. if (s.strm.avail_out === 0) {
  13958. return BS_NEED_MORE;
  13959. }
  13960. /***/
  13961. }
  13962. }
  13963. s.insert = 0;
  13964. if (flush === Z_FINISH) {
  13965. /*** FLUSH_BLOCK(s, 1); ***/
  13966. flush_block_only(s, true);
  13967. if (s.strm.avail_out === 0) {
  13968. return BS_FINISH_STARTED;
  13969. }
  13970. /***/
  13971. return BS_FINISH_DONE;
  13972. }
  13973. if (s.strstart > s.block_start) {
  13974. /*** FLUSH_BLOCK(s, 0); ***/
  13975. flush_block_only(s, false);
  13976. if (s.strm.avail_out === 0) {
  13977. return BS_NEED_MORE;
  13978. }
  13979. /***/
  13980. }
  13981. return BS_NEED_MORE;
  13982. }
  13983. /* ===========================================================================
  13984. * Compress as much as possible from the input stream, return the current
  13985. * block state.
  13986. * This function does not perform lazy evaluation of matches and inserts
  13987. * new strings in the dictionary only for unmatched strings or for short
  13988. * matches. It is used only for the fast compression options.
  13989. */
  13990. function deflate_fast(s, flush) {
  13991. var hash_head; /* head of the hash chain */
  13992. var bflush; /* set if current block must be flushed */
  13993. for (;;) {
  13994. /* Make sure that we always have enough lookahead, except
  13995. * at the end of the input file. We need MAX_MATCH bytes
  13996. * for the next match, plus MIN_MATCH bytes to insert the
  13997. * string following the next match.
  13998. */
  13999. if (s.lookahead < MIN_LOOKAHEAD) {
  14000. fill_window(s);
  14001. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14002. return BS_NEED_MORE;
  14003. }
  14004. if (s.lookahead === 0) {
  14005. break; /* flush the current block */
  14006. }
  14007. }
  14008. /* Insert the string window[strstart .. strstart+2] in the
  14009. * dictionary, and set hash_head to the head of the hash chain:
  14010. */
  14011. hash_head = 0/*NIL*/;
  14012. if (s.lookahead >= MIN_MATCH) {
  14013. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14014. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14015. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14016. s.head[s.ins_h] = s.strstart;
  14017. /***/
  14018. }
  14019. /* Find the longest match, discarding those <= prev_length.
  14020. * At this point we have always match_length < MIN_MATCH
  14021. */
  14022. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14023. /* To simplify the code, we prevent matches with the string
  14024. * of window index 0 (in particular we have to avoid a match
  14025. * of the string with itself at the start of the input file).
  14026. */
  14027. s.match_length = longest_match(s, hash_head);
  14028. /* longest_match() sets match_start */
  14029. }
  14030. if (s.match_length >= MIN_MATCH) {
  14031. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14032. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14033. s.match_length - MIN_MATCH, bflush); ***/
  14034. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14035. s.lookahead -= s.match_length;
  14036. /* Insert new strings in the hash table only if the match length
  14037. * is not too large. This saves time but degrades compression.
  14038. */
  14039. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14040. s.match_length--; /* string at strstart already in table */
  14041. do {
  14042. s.strstart++;
  14043. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14044. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14045. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14046. s.head[s.ins_h] = s.strstart;
  14047. /***/
  14048. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14049. * always MIN_MATCH bytes ahead.
  14050. */
  14051. } while (--s.match_length !== 0);
  14052. s.strstart++;
  14053. } else
  14054. {
  14055. s.strstart += s.match_length;
  14056. s.match_length = 0;
  14057. s.ins_h = s.window[s.strstart];
  14058. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14059. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14060. //#if MIN_MATCH != 3
  14061. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14062. //#endif
  14063. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14064. * matter since it will be recomputed at next deflate call.
  14065. */
  14066. }
  14067. } else {
  14068. /* No match, output a literal byte */
  14069. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14070. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14071. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14072. s.lookahead--;
  14073. s.strstart++;
  14074. }
  14075. if (bflush) {
  14076. /*** FLUSH_BLOCK(s, 0); ***/
  14077. flush_block_only(s, false);
  14078. if (s.strm.avail_out === 0) {
  14079. return BS_NEED_MORE;
  14080. }
  14081. /***/
  14082. }
  14083. }
  14084. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  14085. if (flush === Z_FINISH) {
  14086. /*** FLUSH_BLOCK(s, 1); ***/
  14087. flush_block_only(s, true);
  14088. if (s.strm.avail_out === 0) {
  14089. return BS_FINISH_STARTED;
  14090. }
  14091. /***/
  14092. return BS_FINISH_DONE;
  14093. }
  14094. if (s.last_lit) {
  14095. /*** FLUSH_BLOCK(s, 0); ***/
  14096. flush_block_only(s, false);
  14097. if (s.strm.avail_out === 0) {
  14098. return BS_NEED_MORE;
  14099. }
  14100. /***/
  14101. }
  14102. return BS_BLOCK_DONE;
  14103. }
  14104. /* ===========================================================================
  14105. * Same as above, but achieves better compression. We use a lazy
  14106. * evaluation for matches: a match is finally adopted only if there is
  14107. * no better match at the next window position.
  14108. */
  14109. function deflate_slow(s, flush) {
  14110. var hash_head; /* head of hash chain */
  14111. var bflush; /* set if current block must be flushed */
  14112. var max_insert;
  14113. /* Process the input block. */
  14114. for (;;) {
  14115. /* Make sure that we always have enough lookahead, except
  14116. * at the end of the input file. We need MAX_MATCH bytes
  14117. * for the next match, plus MIN_MATCH bytes to insert the
  14118. * string following the next match.
  14119. */
  14120. if (s.lookahead < MIN_LOOKAHEAD) {
  14121. fill_window(s);
  14122. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14123. return BS_NEED_MORE;
  14124. }
  14125. if (s.lookahead === 0) { break; } /* flush the current block */
  14126. }
  14127. /* Insert the string window[strstart .. strstart+2] in the
  14128. * dictionary, and set hash_head to the head of the hash chain:
  14129. */
  14130. hash_head = 0/*NIL*/;
  14131. if (s.lookahead >= MIN_MATCH) {
  14132. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14133. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14134. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14135. s.head[s.ins_h] = s.strstart;
  14136. /***/
  14137. }
  14138. /* Find the longest match, discarding those <= prev_length.
  14139. */
  14140. s.prev_length = s.match_length;
  14141. s.prev_match = s.match_start;
  14142. s.match_length = MIN_MATCH-1;
  14143. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  14144. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  14145. /* To simplify the code, we prevent matches with the string
  14146. * of window index 0 (in particular we have to avoid a match
  14147. * of the string with itself at the start of the input file).
  14148. */
  14149. s.match_length = longest_match(s, hash_head);
  14150. /* longest_match() sets match_start */
  14151. if (s.match_length <= 5 &&
  14152. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  14153. /* If prev_match is also MIN_MATCH, match_start is garbage
  14154. * but we will ignore the current match anyway.
  14155. */
  14156. s.match_length = MIN_MATCH-1;
  14157. }
  14158. }
  14159. /* If there was a match at the previous step and the current
  14160. * match is not better, output the previous match:
  14161. */
  14162. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  14163. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  14164. /* Do not insert strings in hash table beyond this. */
  14165. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  14166. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  14167. s.prev_length - MIN_MATCH, bflush);***/
  14168. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  14169. /* Insert in hash table all strings up to the end of the match.
  14170. * strstart-1 and strstart are already inserted. If there is not
  14171. * enough lookahead, the last two strings are not inserted in
  14172. * the hash table.
  14173. */
  14174. s.lookahead -= s.prev_length-1;
  14175. s.prev_length -= 2;
  14176. do {
  14177. if (++s.strstart <= max_insert) {
  14178. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14179. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14180. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14181. s.head[s.ins_h] = s.strstart;
  14182. /***/
  14183. }
  14184. } while (--s.prev_length !== 0);
  14185. s.match_available = 0;
  14186. s.match_length = MIN_MATCH-1;
  14187. s.strstart++;
  14188. if (bflush) {
  14189. /*** FLUSH_BLOCK(s, 0); ***/
  14190. flush_block_only(s, false);
  14191. if (s.strm.avail_out === 0) {
  14192. return BS_NEED_MORE;
  14193. }
  14194. /***/
  14195. }
  14196. } else if (s.match_available) {
  14197. /* If there was no match at the previous position, output a
  14198. * single literal. If there was a match but the current match
  14199. * is longer, truncate the previous match to a single literal.
  14200. */
  14201. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14202. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14203. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14204. if (bflush) {
  14205. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  14206. flush_block_only(s, false);
  14207. /***/
  14208. }
  14209. s.strstart++;
  14210. s.lookahead--;
  14211. if (s.strm.avail_out === 0) {
  14212. return BS_NEED_MORE;
  14213. }
  14214. } else {
  14215. /* There is no previous match to compare with, wait for
  14216. * the next step to decide.
  14217. */
  14218. s.match_available = 1;
  14219. s.strstart++;
  14220. s.lookahead--;
  14221. }
  14222. }
  14223. //Assert (flush != Z_NO_FLUSH, "no flush?");
  14224. if (s.match_available) {
  14225. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14226. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14227. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14228. s.match_available = 0;
  14229. }
  14230. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  14231. if (flush === Z_FINISH) {
  14232. /*** FLUSH_BLOCK(s, 1); ***/
  14233. flush_block_only(s, true);
  14234. if (s.strm.avail_out === 0) {
  14235. return BS_FINISH_STARTED;
  14236. }
  14237. /***/
  14238. return BS_FINISH_DONE;
  14239. }
  14240. if (s.last_lit) {
  14241. /*** FLUSH_BLOCK(s, 0); ***/
  14242. flush_block_only(s, false);
  14243. if (s.strm.avail_out === 0) {
  14244. return BS_NEED_MORE;
  14245. }
  14246. /***/
  14247. }
  14248. return BS_BLOCK_DONE;
  14249. }
  14250. /* ===========================================================================
  14251. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  14252. * one. Do not maintain a hash table. (It will be regenerated if this run of
  14253. * deflate switches away from Z_RLE.)
  14254. */
  14255. function deflate_rle(s, flush) {
  14256. var bflush; /* set if current block must be flushed */
  14257. var prev; /* byte at distance one to match */
  14258. var scan, strend; /* scan goes up to strend for length of run */
  14259. var _win = s.window;
  14260. for (;;) {
  14261. /* Make sure that we always have enough lookahead, except
  14262. * at the end of the input file. We need MAX_MATCH bytes
  14263. * for the longest run, plus one for the unrolled loop.
  14264. */
  14265. if (s.lookahead <= MAX_MATCH) {
  14266. fill_window(s);
  14267. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  14268. return BS_NEED_MORE;
  14269. }
  14270. if (s.lookahead === 0) { break; } /* flush the current block */
  14271. }
  14272. /* See how many times the previous byte repeats */
  14273. s.match_length = 0;
  14274. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  14275. scan = s.strstart - 1;
  14276. prev = _win[scan];
  14277. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  14278. strend = s.strstart + MAX_MATCH;
  14279. do {
  14280. /*jshint noempty:false*/
  14281. } while (prev === _win[++scan] && prev === _win[++scan] &&
  14282. prev === _win[++scan] && prev === _win[++scan] &&
  14283. prev === _win[++scan] && prev === _win[++scan] &&
  14284. prev === _win[++scan] && prev === _win[++scan] &&
  14285. scan < strend);
  14286. s.match_length = MAX_MATCH - (strend - scan);
  14287. if (s.match_length > s.lookahead) {
  14288. s.match_length = s.lookahead;
  14289. }
  14290. }
  14291. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  14292. }
  14293. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  14294. if (s.match_length >= MIN_MATCH) {
  14295. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  14296. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  14297. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  14298. s.lookahead -= s.match_length;
  14299. s.strstart += s.match_length;
  14300. s.match_length = 0;
  14301. } else {
  14302. /* No match, output a literal byte */
  14303. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14304. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14305. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14306. s.lookahead--;
  14307. s.strstart++;
  14308. }
  14309. if (bflush) {
  14310. /*** FLUSH_BLOCK(s, 0); ***/
  14311. flush_block_only(s, false);
  14312. if (s.strm.avail_out === 0) {
  14313. return BS_NEED_MORE;
  14314. }
  14315. /***/
  14316. }
  14317. }
  14318. s.insert = 0;
  14319. if (flush === Z_FINISH) {
  14320. /*** FLUSH_BLOCK(s, 1); ***/
  14321. flush_block_only(s, true);
  14322. if (s.strm.avail_out === 0) {
  14323. return BS_FINISH_STARTED;
  14324. }
  14325. /***/
  14326. return BS_FINISH_DONE;
  14327. }
  14328. if (s.last_lit) {
  14329. /*** FLUSH_BLOCK(s, 0); ***/
  14330. flush_block_only(s, false);
  14331. if (s.strm.avail_out === 0) {
  14332. return BS_NEED_MORE;
  14333. }
  14334. /***/
  14335. }
  14336. return BS_BLOCK_DONE;
  14337. }
  14338. /* ===========================================================================
  14339. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  14340. * (It will be regenerated if this run of deflate switches away from Huffman.)
  14341. */
  14342. function deflate_huff(s, flush) {
  14343. var bflush; /* set if current block must be flushed */
  14344. for (;;) {
  14345. /* Make sure that we have a literal to write. */
  14346. if (s.lookahead === 0) {
  14347. fill_window(s);
  14348. if (s.lookahead === 0) {
  14349. if (flush === Z_NO_FLUSH) {
  14350. return BS_NEED_MORE;
  14351. }
  14352. break; /* flush the current block */
  14353. }
  14354. }
  14355. /* Output a literal byte */
  14356. s.match_length = 0;
  14357. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14358. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14359. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14360. s.lookahead--;
  14361. s.strstart++;
  14362. if (bflush) {
  14363. /*** FLUSH_BLOCK(s, 0); ***/
  14364. flush_block_only(s, false);
  14365. if (s.strm.avail_out === 0) {
  14366. return BS_NEED_MORE;
  14367. }
  14368. /***/
  14369. }
  14370. }
  14371. s.insert = 0;
  14372. if (flush === Z_FINISH) {
  14373. /*** FLUSH_BLOCK(s, 1); ***/
  14374. flush_block_only(s, true);
  14375. if (s.strm.avail_out === 0) {
  14376. return BS_FINISH_STARTED;
  14377. }
  14378. /***/
  14379. return BS_FINISH_DONE;
  14380. }
  14381. if (s.last_lit) {
  14382. /*** FLUSH_BLOCK(s, 0); ***/
  14383. flush_block_only(s, false);
  14384. if (s.strm.avail_out === 0) {
  14385. return BS_NEED_MORE;
  14386. }
  14387. /***/
  14388. }
  14389. return BS_BLOCK_DONE;
  14390. }
  14391. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  14392. * the desired pack level (0..9). The values given below have been tuned to
  14393. * exclude worst case performance for pathological files. Better values may be
  14394. * found for specific files.
  14395. */
  14396. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  14397. this.good_length = good_length;
  14398. this.max_lazy = max_lazy;
  14399. this.nice_length = nice_length;
  14400. this.max_chain = max_chain;
  14401. this.func = func;
  14402. };
  14403. var configuration_table;
  14404. configuration_table = [
  14405. /* good lazy nice chain */
  14406. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  14407. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  14408. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  14409. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  14410. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  14411. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  14412. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  14413. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  14414. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  14415. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  14416. ];
  14417. /* ===========================================================================
  14418. * Initialize the "longest match" routines for a new zlib stream
  14419. */
  14420. function lm_init(s) {
  14421. s.window_size = 2 * s.w_size;
  14422. /*** CLEAR_HASH(s); ***/
  14423. zero(s.head); // Fill with NIL (= 0);
  14424. /* Set the default configuration parameters:
  14425. */
  14426. s.max_lazy_match = configuration_table[s.level].max_lazy;
  14427. s.good_match = configuration_table[s.level].good_length;
  14428. s.nice_match = configuration_table[s.level].nice_length;
  14429. s.max_chain_length = configuration_table[s.level].max_chain;
  14430. s.strstart = 0;
  14431. s.block_start = 0;
  14432. s.lookahead = 0;
  14433. s.insert = 0;
  14434. s.match_length = s.prev_length = MIN_MATCH - 1;
  14435. s.match_available = 0;
  14436. s.ins_h = 0;
  14437. }
  14438. function DeflateState() {
  14439. this.strm = null; /* pointer back to this zlib stream */
  14440. this.status = 0; /* as the name implies */
  14441. this.pending_buf = null; /* output still pending */
  14442. this.pending_buf_size = 0; /* size of pending_buf */
  14443. this.pending_out = 0; /* next pending byte to output to the stream */
  14444. this.pending = 0; /* nb of bytes in the pending buffer */
  14445. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14446. this.gzhead = null; /* gzip header information to write */
  14447. this.gzindex = 0; /* where in extra, name, or comment */
  14448. this.method = Z_DEFLATED; /* can only be DEFLATED */
  14449. this.last_flush = -1; /* value of flush param for previous deflate call */
  14450. this.w_size = 0; /* LZ77 window size (32K by default) */
  14451. this.w_bits = 0; /* log2(w_size) (8..16) */
  14452. this.w_mask = 0; /* w_size - 1 */
  14453. this.window = null;
  14454. /* Sliding window. Input bytes are read into the second half of the window,
  14455. * and move to the first half later to keep a dictionary of at least wSize
  14456. * bytes. With this organization, matches are limited to a distance of
  14457. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  14458. * performed with a length multiple of the block size.
  14459. */
  14460. this.window_size = 0;
  14461. /* Actual size of window: 2*wSize, except when the user input buffer
  14462. * is directly used as sliding window.
  14463. */
  14464. this.prev = null;
  14465. /* Link to older string with same hash index. To limit the size of this
  14466. * array to 64K, this link is maintained only for the last 32K strings.
  14467. * An index in this array is thus a window index modulo 32K.
  14468. */
  14469. this.head = null; /* Heads of the hash chains or NIL. */
  14470. this.ins_h = 0; /* hash index of string to be inserted */
  14471. this.hash_size = 0; /* number of elements in hash table */
  14472. this.hash_bits = 0; /* log2(hash_size) */
  14473. this.hash_mask = 0; /* hash_size-1 */
  14474. this.hash_shift = 0;
  14475. /* Number of bits by which ins_h must be shifted at each input
  14476. * step. It must be such that after MIN_MATCH steps, the oldest
  14477. * byte no longer takes part in the hash key, that is:
  14478. * hash_shift * MIN_MATCH >= hash_bits
  14479. */
  14480. this.block_start = 0;
  14481. /* Window position at the beginning of the current output block. Gets
  14482. * negative when the window is moved backwards.
  14483. */
  14484. this.match_length = 0; /* length of best match */
  14485. this.prev_match = 0; /* previous match */
  14486. this.match_available = 0; /* set if previous match exists */
  14487. this.strstart = 0; /* start of string to insert */
  14488. this.match_start = 0; /* start of matching string */
  14489. this.lookahead = 0; /* number of valid bytes ahead in window */
  14490. this.prev_length = 0;
  14491. /* Length of the best match at previous step. Matches not greater than this
  14492. * are discarded. This is used in the lazy match evaluation.
  14493. */
  14494. this.max_chain_length = 0;
  14495. /* To speed up deflation, hash chains are never searched beyond this
  14496. * length. A higher limit improves compression ratio but degrades the
  14497. * speed.
  14498. */
  14499. this.max_lazy_match = 0;
  14500. /* Attempt to find a better match only when the current match is strictly
  14501. * smaller than this value. This mechanism is used only for compression
  14502. * levels >= 4.
  14503. */
  14504. // That's alias to max_lazy_match, don't use directly
  14505. //this.max_insert_length = 0;
  14506. /* Insert new strings in the hash table only if the match length is not
  14507. * greater than this length. This saves time but degrades compression.
  14508. * max_insert_length is used only for compression levels <= 3.
  14509. */
  14510. this.level = 0; /* compression level (1..9) */
  14511. this.strategy = 0; /* favor or force Huffman coding*/
  14512. this.good_match = 0;
  14513. /* Use a faster search when the previous match is longer than this */
  14514. this.nice_match = 0; /* Stop searching when current match exceeds this */
  14515. /* used by trees.c: */
  14516. /* Didn't use ct_data typedef below to suppress compiler warning */
  14517. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  14518. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  14519. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  14520. // Use flat array of DOUBLE size, with interleaved fata,
  14521. // because JS does not support effective
  14522. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  14523. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  14524. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  14525. zero(this.dyn_ltree);
  14526. zero(this.dyn_dtree);
  14527. zero(this.bl_tree);
  14528. this.l_desc = null; /* desc. for literal tree */
  14529. this.d_desc = null; /* desc. for distance tree */
  14530. this.bl_desc = null; /* desc. for bit length tree */
  14531. //ush bl_count[MAX_BITS+1];
  14532. this.bl_count = new utils.Buf16(MAX_BITS+1);
  14533. /* number of codes at each bit length for an optimal tree */
  14534. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  14535. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  14536. zero(this.heap);
  14537. this.heap_len = 0; /* number of elements in the heap */
  14538. this.heap_max = 0; /* element of largest frequency */
  14539. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  14540. * The same heap array is used to build all trees.
  14541. */
  14542. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  14543. zero(this.depth);
  14544. /* Depth of each subtree used as tie breaker for trees of equal frequency
  14545. */
  14546. this.l_buf = 0; /* buffer index for literals or lengths */
  14547. this.lit_bufsize = 0;
  14548. /* Size of match buffer for literals/lengths. There are 4 reasons for
  14549. * limiting lit_bufsize to 64K:
  14550. * - frequencies can be kept in 16 bit counters
  14551. * - if compression is not successful for the first block, all input
  14552. * data is still in the window so we can still emit a stored block even
  14553. * when input comes from standard input. (This can also be done for
  14554. * all blocks if lit_bufsize is not greater than 32K.)
  14555. * - if compression is not successful for a file smaller than 64K, we can
  14556. * even emit a stored file instead of a stored block (saving 5 bytes).
  14557. * This is applicable only for zip (not gzip or zlib).
  14558. * - creating new Huffman trees less frequently may not provide fast
  14559. * adaptation to changes in the input data statistics. (Take for
  14560. * example a binary file with poorly compressible code followed by
  14561. * a highly compressible string table.) Smaller buffer sizes give
  14562. * fast adaptation but have of course the overhead of transmitting
  14563. * trees more frequently.
  14564. * - I can't count above 4
  14565. */
  14566. this.last_lit = 0; /* running index in l_buf */
  14567. this.d_buf = 0;
  14568. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  14569. * the same number of elements. To use different lengths, an extra flag
  14570. * array would be necessary.
  14571. */
  14572. this.opt_len = 0; /* bit length of current block with optimal trees */
  14573. this.static_len = 0; /* bit length of current block with static trees */
  14574. this.matches = 0; /* number of string matches in current block */
  14575. this.insert = 0; /* bytes at end of window left to insert */
  14576. this.bi_buf = 0;
  14577. /* Output buffer. bits are inserted starting at the bottom (least
  14578. * significant bits).
  14579. */
  14580. this.bi_valid = 0;
  14581. /* Number of valid bits in bi_buf. All bits above the last valid bit
  14582. * are always zero.
  14583. */
  14584. // Used for window memory init. We safely ignore it for JS. That makes
  14585. // sense only for pointers and memory check tools.
  14586. //this.high_water = 0;
  14587. /* High water mark offset in window for initialized bytes -- bytes above
  14588. * this are set to zero in order to avoid memory check warnings when
  14589. * longest match routines access bytes past the input. This is then
  14590. * updated to the new high water mark.
  14591. */
  14592. }
  14593. function deflateResetKeep(strm) {
  14594. var s;
  14595. if (!strm || !strm.state) {
  14596. return err(strm, Z_STREAM_ERROR);
  14597. }
  14598. strm.total_in = strm.total_out = 0;
  14599. strm.data_type = Z_UNKNOWN;
  14600. s = strm.state;
  14601. s.pending = 0;
  14602. s.pending_out = 0;
  14603. if (s.wrap < 0) {
  14604. s.wrap = -s.wrap;
  14605. /* was made negative by deflate(..., Z_FINISH); */
  14606. }
  14607. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  14608. strm.adler = (s.wrap === 2) ?
  14609. 0 // crc32(0, Z_NULL, 0)
  14610. :
  14611. 1; // adler32(0, Z_NULL, 0)
  14612. s.last_flush = Z_NO_FLUSH;
  14613. trees._tr_init(s);
  14614. return Z_OK;
  14615. }
  14616. function deflateReset(strm) {
  14617. var ret = deflateResetKeep(strm);
  14618. if (ret === Z_OK) {
  14619. lm_init(strm.state);
  14620. }
  14621. return ret;
  14622. }
  14623. function deflateSetHeader(strm, head) {
  14624. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14625. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  14626. strm.state.gzhead = head;
  14627. return Z_OK;
  14628. }
  14629. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  14630. if (!strm) { // === Z_NULL
  14631. return Z_STREAM_ERROR;
  14632. }
  14633. var wrap = 1;
  14634. if (level === Z_DEFAULT_COMPRESSION) {
  14635. level = 6;
  14636. }
  14637. if (windowBits < 0) { /* suppress zlib wrapper */
  14638. wrap = 0;
  14639. windowBits = -windowBits;
  14640. }
  14641. else if (windowBits > 15) {
  14642. wrap = 2; /* write gzip wrapper instead */
  14643. windowBits -= 16;
  14644. }
  14645. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  14646. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  14647. strategy < 0 || strategy > Z_FIXED) {
  14648. return err(strm, Z_STREAM_ERROR);
  14649. }
  14650. if (windowBits === 8) {
  14651. windowBits = 9;
  14652. }
  14653. /* until 256-byte window bug fixed */
  14654. var s = new DeflateState();
  14655. strm.state = s;
  14656. s.strm = strm;
  14657. s.wrap = wrap;
  14658. s.gzhead = null;
  14659. s.w_bits = windowBits;
  14660. s.w_size = 1 << s.w_bits;
  14661. s.w_mask = s.w_size - 1;
  14662. s.hash_bits = memLevel + 7;
  14663. s.hash_size = 1 << s.hash_bits;
  14664. s.hash_mask = s.hash_size - 1;
  14665. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  14666. s.window = new utils.Buf8(s.w_size * 2);
  14667. s.head = new utils.Buf16(s.hash_size);
  14668. s.prev = new utils.Buf16(s.w_size);
  14669. // Don't need mem init magic for JS.
  14670. //s.high_water = 0; /* nothing written to s->window yet */
  14671. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  14672. s.pending_buf_size = s.lit_bufsize * 4;
  14673. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  14674. s.d_buf = s.lit_bufsize >> 1;
  14675. s.l_buf = (1 + 2) * s.lit_bufsize;
  14676. s.level = level;
  14677. s.strategy = strategy;
  14678. s.method = method;
  14679. return deflateReset(strm);
  14680. }
  14681. function deflateInit(strm, level) {
  14682. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  14683. }
  14684. function deflate(strm, flush) {
  14685. var old_flush, s;
  14686. var beg, val; // for gzip header write only
  14687. if (!strm || !strm.state ||
  14688. flush > Z_BLOCK || flush < 0) {
  14689. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  14690. }
  14691. s = strm.state;
  14692. if (!strm.output ||
  14693. (!strm.input && strm.avail_in !== 0) ||
  14694. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  14695. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  14696. }
  14697. s.strm = strm; /* just in case */
  14698. old_flush = s.last_flush;
  14699. s.last_flush = flush;
  14700. /* Write the header */
  14701. if (s.status === INIT_STATE) {
  14702. if (s.wrap === 2) { // GZIP header
  14703. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14704. put_byte(s, 31);
  14705. put_byte(s, 139);
  14706. put_byte(s, 8);
  14707. if (!s.gzhead) { // s->gzhead == Z_NULL
  14708. put_byte(s, 0);
  14709. put_byte(s, 0);
  14710. put_byte(s, 0);
  14711. put_byte(s, 0);
  14712. put_byte(s, 0);
  14713. put_byte(s, s.level === 9 ? 2 :
  14714. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14715. 4 : 0));
  14716. put_byte(s, OS_CODE);
  14717. s.status = BUSY_STATE;
  14718. }
  14719. else {
  14720. put_byte(s, (s.gzhead.text ? 1 : 0) +
  14721. (s.gzhead.hcrc ? 2 : 0) +
  14722. (!s.gzhead.extra ? 0 : 4) +
  14723. (!s.gzhead.name ? 0 : 8) +
  14724. (!s.gzhead.comment ? 0 : 16)
  14725. );
  14726. put_byte(s, s.gzhead.time & 0xff);
  14727. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  14728. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  14729. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  14730. put_byte(s, s.level === 9 ? 2 :
  14731. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14732. 4 : 0));
  14733. put_byte(s, s.gzhead.os & 0xff);
  14734. if (s.gzhead.extra && s.gzhead.extra.length) {
  14735. put_byte(s, s.gzhead.extra.length & 0xff);
  14736. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  14737. }
  14738. if (s.gzhead.hcrc) {
  14739. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  14740. }
  14741. s.gzindex = 0;
  14742. s.status = EXTRA_STATE;
  14743. }
  14744. }
  14745. else // DEFLATE header
  14746. {
  14747. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  14748. var level_flags = -1;
  14749. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  14750. level_flags = 0;
  14751. } else if (s.level < 6) {
  14752. level_flags = 1;
  14753. } else if (s.level === 6) {
  14754. level_flags = 2;
  14755. } else {
  14756. level_flags = 3;
  14757. }
  14758. header |= (level_flags << 6);
  14759. if (s.strstart !== 0) { header |= PRESET_DICT; }
  14760. header += 31 - (header % 31);
  14761. s.status = BUSY_STATE;
  14762. putShortMSB(s, header);
  14763. /* Save the adler32 of the preset dictionary: */
  14764. if (s.strstart !== 0) {
  14765. putShortMSB(s, strm.adler >>> 16);
  14766. putShortMSB(s, strm.adler & 0xffff);
  14767. }
  14768. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  14769. }
  14770. }
  14771. //#ifdef GZIP
  14772. if (s.status === EXTRA_STATE) {
  14773. if (s.gzhead.extra/* != Z_NULL*/) {
  14774. beg = s.pending; /* start of bytes to update crc */
  14775. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  14776. if (s.pending === s.pending_buf_size) {
  14777. if (s.gzhead.hcrc && s.pending > beg) {
  14778. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14779. }
  14780. flush_pending(strm);
  14781. beg = s.pending;
  14782. if (s.pending === s.pending_buf_size) {
  14783. break;
  14784. }
  14785. }
  14786. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  14787. s.gzindex++;
  14788. }
  14789. if (s.gzhead.hcrc && s.pending > beg) {
  14790. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14791. }
  14792. if (s.gzindex === s.gzhead.extra.length) {
  14793. s.gzindex = 0;
  14794. s.status = NAME_STATE;
  14795. }
  14796. }
  14797. else {
  14798. s.status = NAME_STATE;
  14799. }
  14800. }
  14801. if (s.status === NAME_STATE) {
  14802. if (s.gzhead.name/* != Z_NULL*/) {
  14803. beg = s.pending; /* start of bytes to update crc */
  14804. //int val;
  14805. do {
  14806. if (s.pending === s.pending_buf_size) {
  14807. if (s.gzhead.hcrc && s.pending > beg) {
  14808. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14809. }
  14810. flush_pending(strm);
  14811. beg = s.pending;
  14812. if (s.pending === s.pending_buf_size) {
  14813. val = 1;
  14814. break;
  14815. }
  14816. }
  14817. // JS specific: little magic to add zero terminator to end of string
  14818. if (s.gzindex < s.gzhead.name.length) {
  14819. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  14820. } else {
  14821. val = 0;
  14822. }
  14823. put_byte(s, val);
  14824. } while (val !== 0);
  14825. if (s.gzhead.hcrc && s.pending > beg) {
  14826. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14827. }
  14828. if (val === 0) {
  14829. s.gzindex = 0;
  14830. s.status = COMMENT_STATE;
  14831. }
  14832. }
  14833. else {
  14834. s.status = COMMENT_STATE;
  14835. }
  14836. }
  14837. if (s.status === COMMENT_STATE) {
  14838. if (s.gzhead.comment/* != Z_NULL*/) {
  14839. beg = s.pending; /* start of bytes to update crc */
  14840. //int val;
  14841. do {
  14842. if (s.pending === s.pending_buf_size) {
  14843. if (s.gzhead.hcrc && s.pending > beg) {
  14844. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14845. }
  14846. flush_pending(strm);
  14847. beg = s.pending;
  14848. if (s.pending === s.pending_buf_size) {
  14849. val = 1;
  14850. break;
  14851. }
  14852. }
  14853. // JS specific: little magic to add zero terminator to end of string
  14854. if (s.gzindex < s.gzhead.comment.length) {
  14855. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  14856. } else {
  14857. val = 0;
  14858. }
  14859. put_byte(s, val);
  14860. } while (val !== 0);
  14861. if (s.gzhead.hcrc && s.pending > beg) {
  14862. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14863. }
  14864. if (val === 0) {
  14865. s.status = HCRC_STATE;
  14866. }
  14867. }
  14868. else {
  14869. s.status = HCRC_STATE;
  14870. }
  14871. }
  14872. if (s.status === HCRC_STATE) {
  14873. if (s.gzhead.hcrc) {
  14874. if (s.pending + 2 > s.pending_buf_size) {
  14875. flush_pending(strm);
  14876. }
  14877. if (s.pending + 2 <= s.pending_buf_size) {
  14878. put_byte(s, strm.adler & 0xff);
  14879. put_byte(s, (strm.adler >> 8) & 0xff);
  14880. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14881. s.status = BUSY_STATE;
  14882. }
  14883. }
  14884. else {
  14885. s.status = BUSY_STATE;
  14886. }
  14887. }
  14888. //#endif
  14889. /* Flush as much pending output as possible */
  14890. if (s.pending !== 0) {
  14891. flush_pending(strm);
  14892. if (strm.avail_out === 0) {
  14893. /* Since avail_out is 0, deflate will be called again with
  14894. * more output space, but possibly with both pending and
  14895. * avail_in equal to zero. There won't be anything to do,
  14896. * but this is not an error situation so make sure we
  14897. * return OK instead of BUF_ERROR at next call of deflate:
  14898. */
  14899. s.last_flush = -1;
  14900. return Z_OK;
  14901. }
  14902. /* Make sure there is something to do and avoid duplicate consecutive
  14903. * flushes. For repeated and useless calls with Z_FINISH, we keep
  14904. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  14905. */
  14906. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  14907. flush !== Z_FINISH) {
  14908. return err(strm, Z_BUF_ERROR);
  14909. }
  14910. /* User must not provide more input after the first FINISH: */
  14911. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  14912. return err(strm, Z_BUF_ERROR);
  14913. }
  14914. /* Start a new block or continue the current one.
  14915. */
  14916. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  14917. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  14918. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  14919. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  14920. configuration_table[s.level].func(s, flush));
  14921. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  14922. s.status = FINISH_STATE;
  14923. }
  14924. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  14925. if (strm.avail_out === 0) {
  14926. s.last_flush = -1;
  14927. /* avoid BUF_ERROR next call, see above */
  14928. }
  14929. return Z_OK;
  14930. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  14931. * of deflate should use the same flush parameter to make sure
  14932. * that the flush is complete. So we don't have to output an
  14933. * empty block here, this will be done at next call. This also
  14934. * ensures that for a very small output buffer, we emit at most
  14935. * one empty block.
  14936. */
  14937. }
  14938. if (bstate === BS_BLOCK_DONE) {
  14939. if (flush === Z_PARTIAL_FLUSH) {
  14940. trees._tr_align(s);
  14941. }
  14942. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  14943. trees._tr_stored_block(s, 0, 0, false);
  14944. /* For a full flush, this empty block will be recognized
  14945. * as a special marker by inflate_sync().
  14946. */
  14947. if (flush === Z_FULL_FLUSH) {
  14948. /*** CLEAR_HASH(s); ***/ /* forget history */
  14949. zero(s.head); // Fill with NIL (= 0);
  14950. if (s.lookahead === 0) {
  14951. s.strstart = 0;
  14952. s.block_start = 0;
  14953. s.insert = 0;
  14954. }
  14955. }
  14956. }
  14957. flush_pending(strm);
  14958. if (strm.avail_out === 0) {
  14959. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  14960. return Z_OK;
  14961. }
  14962. }
  14963. }
  14964. //Assert(strm->avail_out > 0, "bug2");
  14965. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  14966. if (flush !== Z_FINISH) { return Z_OK; }
  14967. if (s.wrap <= 0) { return Z_STREAM_END; }
  14968. /* Write the trailer */
  14969. if (s.wrap === 2) {
  14970. put_byte(s, strm.adler & 0xff);
  14971. put_byte(s, (strm.adler >> 8) & 0xff);
  14972. put_byte(s, (strm.adler >> 16) & 0xff);
  14973. put_byte(s, (strm.adler >> 24) & 0xff);
  14974. put_byte(s, strm.total_in & 0xff);
  14975. put_byte(s, (strm.total_in >> 8) & 0xff);
  14976. put_byte(s, (strm.total_in >> 16) & 0xff);
  14977. put_byte(s, (strm.total_in >> 24) & 0xff);
  14978. }
  14979. else
  14980. {
  14981. putShortMSB(s, strm.adler >>> 16);
  14982. putShortMSB(s, strm.adler & 0xffff);
  14983. }
  14984. flush_pending(strm);
  14985. /* If avail_out is zero, the application will call deflate again
  14986. * to flush the rest.
  14987. */
  14988. if (s.wrap > 0) { s.wrap = -s.wrap; }
  14989. /* write the trailer only once! */
  14990. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  14991. }
  14992. function deflateEnd(strm) {
  14993. var status;
  14994. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  14995. return Z_STREAM_ERROR;
  14996. }
  14997. status = strm.state.status;
  14998. if (status !== INIT_STATE &&
  14999. status !== EXTRA_STATE &&
  15000. status !== NAME_STATE &&
  15001. status !== COMMENT_STATE &&
  15002. status !== HCRC_STATE &&
  15003. status !== BUSY_STATE &&
  15004. status !== FINISH_STATE
  15005. ) {
  15006. return err(strm, Z_STREAM_ERROR);
  15007. }
  15008. strm.state = null;
  15009. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15010. }
  15011. /* =========================================================================
  15012. * Copy the source state to the destination state
  15013. */
  15014. //function deflateCopy(dest, source) {
  15015. //
  15016. //}
  15017. exports.deflateInit = deflateInit;
  15018. exports.deflateInit2 = deflateInit2;
  15019. exports.deflateReset = deflateReset;
  15020. exports.deflateResetKeep = deflateResetKeep;
  15021. exports.deflateSetHeader = deflateSetHeader;
  15022. exports.deflate = deflate;
  15023. exports.deflateEnd = deflateEnd;
  15024. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15025. /* Not implemented
  15026. exports.deflateBound = deflateBound;
  15027. exports.deflateCopy = deflateCopy;
  15028. exports.deflateSetDictionary = deflateSetDictionary;
  15029. exports.deflateParams = deflateParams;
  15030. exports.deflatePending = deflatePending;
  15031. exports.deflatePrime = deflatePrime;
  15032. exports.deflateTune = deflateTune;
  15033. */
  15034. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./messages":61,"./trees":62}],57:[function(require,module,exports){
  15035. 'use strict';
  15036. function GZheader() {
  15037. /* true if compressed data believed to be text */
  15038. this.text = 0;
  15039. /* modification time */
  15040. this.time = 0;
  15041. /* extra flags (not used when writing a gzip file) */
  15042. this.xflags = 0;
  15043. /* operating system */
  15044. this.os = 0;
  15045. /* pointer to extra field or Z_NULL if none */
  15046. this.extra = null;
  15047. /* extra field length (valid if extra != Z_NULL) */
  15048. this.extra_len = 0; // Actually, we don't need it in JS,
  15049. // but leave for few code modifications
  15050. //
  15051. // Setup limits is not necessary because in js we should not preallocate memory
  15052. // for inflate use constant limit in 65536 bytes
  15053. //
  15054. /* space at extra (only when reading header) */
  15055. // this.extra_max = 0;
  15056. /* pointer to zero-terminated file name or Z_NULL */
  15057. this.name = '';
  15058. /* space at name (only when reading header) */
  15059. // this.name_max = 0;
  15060. /* pointer to zero-terminated comment or Z_NULL */
  15061. this.comment = '';
  15062. /* space at comment (only when reading header) */
  15063. // this.comm_max = 0;
  15064. /* true if there was or will be a header crc */
  15065. this.hcrc = 0;
  15066. /* true when done reading gzip header (not used when writing a gzip file) */
  15067. this.done = false;
  15068. }
  15069. module.exports = GZheader;
  15070. },{}],58:[function(require,module,exports){
  15071. 'use strict';
  15072. // See state defs from inflate.js
  15073. var BAD = 30; /* got a data error -- remain here until reset */
  15074. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15075. /*
  15076. Decode literal, length, and distance codes and write out the resulting
  15077. literal and match bytes until either not enough input or output is
  15078. available, an end-of-block is encountered, or a data error is encountered.
  15079. When large enough input and output buffers are supplied to inflate(), for
  15080. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  15081. inflate execution time is spent in this routine.
  15082. Entry assumptions:
  15083. state.mode === LEN
  15084. strm.avail_in >= 6
  15085. strm.avail_out >= 258
  15086. start >= strm.avail_out
  15087. state.bits < 8
  15088. On return, state.mode is one of:
  15089. LEN -- ran out of enough output space or enough available input
  15090. TYPE -- reached end of block code, inflate() to interpret next block
  15091. BAD -- error in block data
  15092. Notes:
  15093. - The maximum input bits used by a length/distance pair is 15 bits for the
  15094. length code, 5 bits for the length extra, 15 bits for the distance code,
  15095. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  15096. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  15097. checking for available input while decoding.
  15098. - The maximum bytes that a single length/distance pair can output is 258
  15099. bytes, which is the maximum length that can be coded. inflate_fast()
  15100. requires strm.avail_out >= 258 for each loop to avoid checking for
  15101. output space.
  15102. */
  15103. module.exports = function inflate_fast(strm, start) {
  15104. var state;
  15105. var _in; /* local strm.input */
  15106. var last; /* have enough input while in < last */
  15107. var _out; /* local strm.output */
  15108. var beg; /* inflate()'s initial strm.output */
  15109. var end; /* while out < end, enough space available */
  15110. //#ifdef INFLATE_STRICT
  15111. var dmax; /* maximum distance from zlib header */
  15112. //#endif
  15113. var wsize; /* window size or zero if not using window */
  15114. var whave; /* valid bytes in the window */
  15115. var wnext; /* window write index */
  15116. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  15117. var s_window; /* allocated sliding window, if wsize != 0 */
  15118. var hold; /* local strm.hold */
  15119. var bits; /* local strm.bits */
  15120. var lcode; /* local strm.lencode */
  15121. var dcode; /* local strm.distcode */
  15122. var lmask; /* mask for first level of length codes */
  15123. var dmask; /* mask for first level of distance codes */
  15124. var here; /* retrieved table entry */
  15125. var op; /* code bits, operation, extra bits, or */
  15126. /* window position, window bytes to copy */
  15127. var len; /* match length, unused bytes */
  15128. var dist; /* match distance */
  15129. var from; /* where to copy match from */
  15130. var from_source;
  15131. var input, output; // JS specific, because we have no pointers
  15132. /* copy state to local variables */
  15133. state = strm.state;
  15134. //here = state.here;
  15135. _in = strm.next_in;
  15136. input = strm.input;
  15137. last = _in + (strm.avail_in - 5);
  15138. _out = strm.next_out;
  15139. output = strm.output;
  15140. beg = _out - (start - strm.avail_out);
  15141. end = _out + (strm.avail_out - 257);
  15142. //#ifdef INFLATE_STRICT
  15143. dmax = state.dmax;
  15144. //#endif
  15145. wsize = state.wsize;
  15146. whave = state.whave;
  15147. wnext = state.wnext;
  15148. s_window = state.window;
  15149. hold = state.hold;
  15150. bits = state.bits;
  15151. lcode = state.lencode;
  15152. dcode = state.distcode;
  15153. lmask = (1 << state.lenbits) - 1;
  15154. dmask = (1 << state.distbits) - 1;
  15155. /* decode literals and length/distances until end-of-block or not enough
  15156. input data or output space */
  15157. top:
  15158. do {
  15159. if (bits < 15) {
  15160. hold += input[_in++] << bits;
  15161. bits += 8;
  15162. hold += input[_in++] << bits;
  15163. bits += 8;
  15164. }
  15165. here = lcode[hold & lmask];
  15166. dolen:
  15167. for (;;) { // Goto emulation
  15168. op = here >>> 24/*here.bits*/;
  15169. hold >>>= op;
  15170. bits -= op;
  15171. op = (here >>> 16) & 0xff/*here.op*/;
  15172. if (op === 0) { /* literal */
  15173. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15174. // "inflate: literal '%c'\n" :
  15175. // "inflate: literal 0x%02x\n", here.val));
  15176. output[_out++] = here & 0xffff/*here.val*/;
  15177. }
  15178. else if (op & 16) { /* length base */
  15179. len = here & 0xffff/*here.val*/;
  15180. op &= 15; /* number of extra bits */
  15181. if (op) {
  15182. if (bits < op) {
  15183. hold += input[_in++] << bits;
  15184. bits += 8;
  15185. }
  15186. len += hold & ((1 << op) - 1);
  15187. hold >>>= op;
  15188. bits -= op;
  15189. }
  15190. //Tracevv((stderr, "inflate: length %u\n", len));
  15191. if (bits < 15) {
  15192. hold += input[_in++] << bits;
  15193. bits += 8;
  15194. hold += input[_in++] << bits;
  15195. bits += 8;
  15196. }
  15197. here = dcode[hold & dmask];
  15198. dodist:
  15199. for (;;) { // goto emulation
  15200. op = here >>> 24/*here.bits*/;
  15201. hold >>>= op;
  15202. bits -= op;
  15203. op = (here >>> 16) & 0xff/*here.op*/;
  15204. if (op & 16) { /* distance base */
  15205. dist = here & 0xffff/*here.val*/;
  15206. op &= 15; /* number of extra bits */
  15207. if (bits < op) {
  15208. hold += input[_in++] << bits;
  15209. bits += 8;
  15210. if (bits < op) {
  15211. hold += input[_in++] << bits;
  15212. bits += 8;
  15213. }
  15214. }
  15215. dist += hold & ((1 << op) - 1);
  15216. //#ifdef INFLATE_STRICT
  15217. if (dist > dmax) {
  15218. strm.msg = 'invalid distance too far back';
  15219. state.mode = BAD;
  15220. break top;
  15221. }
  15222. //#endif
  15223. hold >>>= op;
  15224. bits -= op;
  15225. //Tracevv((stderr, "inflate: distance %u\n", dist));
  15226. op = _out - beg; /* max distance in output */
  15227. if (dist > op) { /* see if copy from window */
  15228. op = dist - op; /* distance back in window */
  15229. if (op > whave) {
  15230. if (state.sane) {
  15231. strm.msg = 'invalid distance too far back';
  15232. state.mode = BAD;
  15233. break top;
  15234. }
  15235. // (!) This block is disabled in zlib defailts,
  15236. // don't enable it for binary compatibility
  15237. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15238. // if (len <= op - whave) {
  15239. // do {
  15240. // output[_out++] = 0;
  15241. // } while (--len);
  15242. // continue top;
  15243. // }
  15244. // len -= op - whave;
  15245. // do {
  15246. // output[_out++] = 0;
  15247. // } while (--op > whave);
  15248. // if (op === 0) {
  15249. // from = _out - dist;
  15250. // do {
  15251. // output[_out++] = output[from++];
  15252. // } while (--len);
  15253. // continue top;
  15254. // }
  15255. //#endif
  15256. }
  15257. from = 0; // window index
  15258. from_source = s_window;
  15259. if (wnext === 0) { /* very common case */
  15260. from += wsize - op;
  15261. if (op < len) { /* some from window */
  15262. len -= op;
  15263. do {
  15264. output[_out++] = s_window[from++];
  15265. } while (--op);
  15266. from = _out - dist; /* rest from output */
  15267. from_source = output;
  15268. }
  15269. }
  15270. else if (wnext < op) { /* wrap around window */
  15271. from += wsize + wnext - op;
  15272. op -= wnext;
  15273. if (op < len) { /* some from end of window */
  15274. len -= op;
  15275. do {
  15276. output[_out++] = s_window[from++];
  15277. } while (--op);
  15278. from = 0;
  15279. if (wnext < len) { /* some from start of window */
  15280. op = wnext;
  15281. len -= op;
  15282. do {
  15283. output[_out++] = s_window[from++];
  15284. } while (--op);
  15285. from = _out - dist; /* rest from output */
  15286. from_source = output;
  15287. }
  15288. }
  15289. }
  15290. else { /* contiguous in window */
  15291. from += wnext - op;
  15292. if (op < len) { /* some from window */
  15293. len -= op;
  15294. do {
  15295. output[_out++] = s_window[from++];
  15296. } while (--op);
  15297. from = _out - dist; /* rest from output */
  15298. from_source = output;
  15299. }
  15300. }
  15301. while (len > 2) {
  15302. output[_out++] = from_source[from++];
  15303. output[_out++] = from_source[from++];
  15304. output[_out++] = from_source[from++];
  15305. len -= 3;
  15306. }
  15307. if (len) {
  15308. output[_out++] = from_source[from++];
  15309. if (len > 1) {
  15310. output[_out++] = from_source[from++];
  15311. }
  15312. }
  15313. }
  15314. else {
  15315. from = _out - dist; /* copy direct from output */
  15316. do { /* minimum length is three */
  15317. output[_out++] = output[from++];
  15318. output[_out++] = output[from++];
  15319. output[_out++] = output[from++];
  15320. len -= 3;
  15321. } while (len > 2);
  15322. if (len) {
  15323. output[_out++] = output[from++];
  15324. if (len > 1) {
  15325. output[_out++] = output[from++];
  15326. }
  15327. }
  15328. }
  15329. }
  15330. else if ((op & 64) === 0) { /* 2nd level distance code */
  15331. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15332. continue dodist;
  15333. }
  15334. else {
  15335. strm.msg = 'invalid distance code';
  15336. state.mode = BAD;
  15337. break top;
  15338. }
  15339. break; // need to emulate goto via "continue"
  15340. }
  15341. }
  15342. else if ((op & 64) === 0) { /* 2nd level length code */
  15343. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15344. continue dolen;
  15345. }
  15346. else if (op & 32) { /* end-of-block */
  15347. //Tracevv((stderr, "inflate: end of block\n"));
  15348. state.mode = TYPE;
  15349. break top;
  15350. }
  15351. else {
  15352. strm.msg = 'invalid literal/length code';
  15353. state.mode = BAD;
  15354. break top;
  15355. }
  15356. break; // need to emulate goto via "continue"
  15357. }
  15358. } while (_in < last && _out < end);
  15359. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  15360. len = bits >> 3;
  15361. _in -= len;
  15362. bits -= len << 3;
  15363. hold &= (1 << bits) - 1;
  15364. /* update state and return */
  15365. strm.next_in = _in;
  15366. strm.next_out = _out;
  15367. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  15368. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  15369. state.hold = hold;
  15370. state.bits = bits;
  15371. return;
  15372. };
  15373. },{}],59:[function(require,module,exports){
  15374. 'use strict';
  15375. var utils = require('../utils/common');
  15376. var adler32 = require('./adler32');
  15377. var crc32 = require('./crc32');
  15378. var inflate_fast = require('./inffast');
  15379. var inflate_table = require('./inftrees');
  15380. var CODES = 0;
  15381. var LENS = 1;
  15382. var DISTS = 2;
  15383. /* Public constants ==========================================================*/
  15384. /* ===========================================================================*/
  15385. /* Allowed flush values; see deflate() and inflate() below for details */
  15386. //var Z_NO_FLUSH = 0;
  15387. //var Z_PARTIAL_FLUSH = 1;
  15388. //var Z_SYNC_FLUSH = 2;
  15389. //var Z_FULL_FLUSH = 3;
  15390. var Z_FINISH = 4;
  15391. var Z_BLOCK = 5;
  15392. var Z_TREES = 6;
  15393. /* Return codes for the compression/decompression functions. Negative values
  15394. * are errors, positive values are used for special but normal events.
  15395. */
  15396. var Z_OK = 0;
  15397. var Z_STREAM_END = 1;
  15398. var Z_NEED_DICT = 2;
  15399. //var Z_ERRNO = -1;
  15400. var Z_STREAM_ERROR = -2;
  15401. var Z_DATA_ERROR = -3;
  15402. var Z_MEM_ERROR = -4;
  15403. var Z_BUF_ERROR = -5;
  15404. //var Z_VERSION_ERROR = -6;
  15405. /* The deflate compression method */
  15406. var Z_DEFLATED = 8;
  15407. /* STATES ====================================================================*/
  15408. /* ===========================================================================*/
  15409. var HEAD = 1; /* i: waiting for magic header */
  15410. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  15411. var TIME = 3; /* i: waiting for modification time (gzip) */
  15412. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  15413. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  15414. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  15415. var NAME = 7; /* i: waiting for end of file name (gzip) */
  15416. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  15417. var HCRC = 9; /* i: waiting for header crc (gzip) */
  15418. var DICTID = 10; /* i: waiting for dictionary check value */
  15419. var DICT = 11; /* waiting for inflateSetDictionary() call */
  15420. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15421. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  15422. var STORED = 14; /* i: waiting for stored size (length and complement) */
  15423. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  15424. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  15425. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  15426. var LENLENS = 18; /* i: waiting for code length code lengths */
  15427. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  15428. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  15429. var LEN = 21; /* i: waiting for length/lit/eob code */
  15430. var LENEXT = 22; /* i: waiting for length extra bits */
  15431. var DIST = 23; /* i: waiting for distance code */
  15432. var DISTEXT = 24; /* i: waiting for distance extra bits */
  15433. var MATCH = 25; /* o: waiting for output space to copy string */
  15434. var LIT = 26; /* o: waiting for output space to write literal */
  15435. var CHECK = 27; /* i: waiting for 32-bit check value */
  15436. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  15437. var DONE = 29; /* finished check, done -- remain here until reset */
  15438. var BAD = 30; /* got a data error -- remain here until reset */
  15439. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  15440. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  15441. /* ===========================================================================*/
  15442. var ENOUGH_LENS = 852;
  15443. var ENOUGH_DISTS = 592;
  15444. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15445. var MAX_WBITS = 15;
  15446. /* 32K LZ77 window */
  15447. var DEF_WBITS = MAX_WBITS;
  15448. function ZSWAP32(q) {
  15449. return (((q >>> 24) & 0xff) +
  15450. ((q >>> 8) & 0xff00) +
  15451. ((q & 0xff00) << 8) +
  15452. ((q & 0xff) << 24));
  15453. }
  15454. function InflateState() {
  15455. this.mode = 0; /* current inflate mode */
  15456. this.last = false; /* true if processing last block */
  15457. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15458. this.havedict = false; /* true if dictionary provided */
  15459. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  15460. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  15461. this.check = 0; /* protected copy of check value */
  15462. this.total = 0; /* protected copy of output count */
  15463. // TODO: may be {}
  15464. this.head = null; /* where to save gzip header information */
  15465. /* sliding window */
  15466. this.wbits = 0; /* log base 2 of requested window size */
  15467. this.wsize = 0; /* window size or zero if not using window */
  15468. this.whave = 0; /* valid bytes in the window */
  15469. this.wnext = 0; /* window write index */
  15470. this.window = null; /* allocated sliding window, if needed */
  15471. /* bit accumulator */
  15472. this.hold = 0; /* input bit accumulator */
  15473. this.bits = 0; /* number of bits in "in" */
  15474. /* for string and stored block copying */
  15475. this.length = 0; /* literal or length of data to copy */
  15476. this.offset = 0; /* distance back to copy string from */
  15477. /* for table and code decoding */
  15478. this.extra = 0; /* extra bits needed */
  15479. /* fixed and dynamic code tables */
  15480. this.lencode = null; /* starting table for length/literal codes */
  15481. this.distcode = null; /* starting table for distance codes */
  15482. this.lenbits = 0; /* index bits for lencode */
  15483. this.distbits = 0; /* index bits for distcode */
  15484. /* dynamic table building */
  15485. this.ncode = 0; /* number of code length code lengths */
  15486. this.nlen = 0; /* number of length code lengths */
  15487. this.ndist = 0; /* number of distance code lengths */
  15488. this.have = 0; /* number of code lengths in lens[] */
  15489. this.next = null; /* next available space in codes[] */
  15490. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  15491. this.work = new utils.Buf16(288); /* work area for code table building */
  15492. /*
  15493. because we don't have pointers in js, we use lencode and distcode directly
  15494. as buffers so we don't need codes
  15495. */
  15496. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  15497. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  15498. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  15499. this.sane = 0; /* if false, allow invalid distance too far */
  15500. this.back = 0; /* bits back of last unprocessed length/lit */
  15501. this.was = 0; /* initial length of match */
  15502. }
  15503. function inflateResetKeep(strm) {
  15504. var state;
  15505. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15506. state = strm.state;
  15507. strm.total_in = strm.total_out = state.total = 0;
  15508. strm.msg = ''; /*Z_NULL*/
  15509. if (state.wrap) { /* to support ill-conceived Java test suite */
  15510. strm.adler = state.wrap & 1;
  15511. }
  15512. state.mode = HEAD;
  15513. state.last = 0;
  15514. state.havedict = 0;
  15515. state.dmax = 32768;
  15516. state.head = null/*Z_NULL*/;
  15517. state.hold = 0;
  15518. state.bits = 0;
  15519. //state.lencode = state.distcode = state.next = state.codes;
  15520. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  15521. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  15522. state.sane = 1;
  15523. state.back = -1;
  15524. //Tracev((stderr, "inflate: reset\n"));
  15525. return Z_OK;
  15526. }
  15527. function inflateReset(strm) {
  15528. var state;
  15529. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15530. state = strm.state;
  15531. state.wsize = 0;
  15532. state.whave = 0;
  15533. state.wnext = 0;
  15534. return inflateResetKeep(strm);
  15535. }
  15536. function inflateReset2(strm, windowBits) {
  15537. var wrap;
  15538. var state;
  15539. /* get the state */
  15540. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15541. state = strm.state;
  15542. /* extract wrap request from windowBits parameter */
  15543. if (windowBits < 0) {
  15544. wrap = 0;
  15545. windowBits = -windowBits;
  15546. }
  15547. else {
  15548. wrap = (windowBits >> 4) + 1;
  15549. if (windowBits < 48) {
  15550. windowBits &= 15;
  15551. }
  15552. }
  15553. /* set number of window bits, free window if different */
  15554. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  15555. return Z_STREAM_ERROR;
  15556. }
  15557. if (state.window !== null && state.wbits !== windowBits) {
  15558. state.window = null;
  15559. }
  15560. /* update state and reset the rest of it */
  15561. state.wrap = wrap;
  15562. state.wbits = windowBits;
  15563. return inflateReset(strm);
  15564. }
  15565. function inflateInit2(strm, windowBits) {
  15566. var ret;
  15567. var state;
  15568. if (!strm) { return Z_STREAM_ERROR; }
  15569. //strm.msg = Z_NULL; /* in case we return an error */
  15570. state = new InflateState();
  15571. //if (state === Z_NULL) return Z_MEM_ERROR;
  15572. //Tracev((stderr, "inflate: allocated\n"));
  15573. strm.state = state;
  15574. state.window = null/*Z_NULL*/;
  15575. ret = inflateReset2(strm, windowBits);
  15576. if (ret !== Z_OK) {
  15577. strm.state = null/*Z_NULL*/;
  15578. }
  15579. return ret;
  15580. }
  15581. function inflateInit(strm) {
  15582. return inflateInit2(strm, DEF_WBITS);
  15583. }
  15584. /*
  15585. Return state with length and distance decoding tables and index sizes set to
  15586. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  15587. If BUILDFIXED is defined, then instead this routine builds the tables the
  15588. first time it's called, and returns those tables the first time and
  15589. thereafter. This reduces the size of the code by about 2K bytes, in
  15590. exchange for a little execution time. However, BUILDFIXED should not be
  15591. used for threaded applications, since the rewriting of the tables and virgin
  15592. may not be thread-safe.
  15593. */
  15594. var virgin = true;
  15595. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  15596. function fixedtables(state) {
  15597. /* build fixed huffman tables if first call (may not be thread safe) */
  15598. if (virgin) {
  15599. var sym;
  15600. lenfix = new utils.Buf32(512);
  15601. distfix = new utils.Buf32(32);
  15602. /* literal/length table */
  15603. sym = 0;
  15604. while (sym < 144) { state.lens[sym++] = 8; }
  15605. while (sym < 256) { state.lens[sym++] = 9; }
  15606. while (sym < 280) { state.lens[sym++] = 7; }
  15607. while (sym < 288) { state.lens[sym++] = 8; }
  15608. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  15609. /* distance table */
  15610. sym = 0;
  15611. while (sym < 32) { state.lens[sym++] = 5; }
  15612. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  15613. /* do this just once */
  15614. virgin = false;
  15615. }
  15616. state.lencode = lenfix;
  15617. state.lenbits = 9;
  15618. state.distcode = distfix;
  15619. state.distbits = 5;
  15620. }
  15621. /*
  15622. Update the window with the last wsize (normally 32K) bytes written before
  15623. returning. If window does not exist yet, create it. This is only called
  15624. when a window is already in use, or when output has been written during this
  15625. inflate call, but the end of the deflate stream has not been reached yet.
  15626. It is also called to create a window for dictionary data when a dictionary
  15627. is loaded.
  15628. Providing output buffers larger than 32K to inflate() should provide a speed
  15629. advantage, since only the last 32K of output is copied to the sliding window
  15630. upon return from inflate(), and since all distances after the first 32K of
  15631. output will fall in the output data, making match copies simpler and faster.
  15632. The advantage may be dependent on the size of the processor's data caches.
  15633. */
  15634. function updatewindow(strm, src, end, copy) {
  15635. var dist;
  15636. var state = strm.state;
  15637. /* if it hasn't been done already, allocate space for the window */
  15638. if (state.window === null) {
  15639. state.wsize = 1 << state.wbits;
  15640. state.wnext = 0;
  15641. state.whave = 0;
  15642. state.window = new utils.Buf8(state.wsize);
  15643. }
  15644. /* copy state->wsize or less output bytes into the circular window */
  15645. if (copy >= state.wsize) {
  15646. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  15647. state.wnext = 0;
  15648. state.whave = state.wsize;
  15649. }
  15650. else {
  15651. dist = state.wsize - state.wnext;
  15652. if (dist > copy) {
  15653. dist = copy;
  15654. }
  15655. //zmemcpy(state->window + state->wnext, end - copy, dist);
  15656. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  15657. copy -= dist;
  15658. if (copy) {
  15659. //zmemcpy(state->window, end - copy, copy);
  15660. utils.arraySet(state.window,src, end - copy, copy, 0);
  15661. state.wnext = copy;
  15662. state.whave = state.wsize;
  15663. }
  15664. else {
  15665. state.wnext += dist;
  15666. if (state.wnext === state.wsize) { state.wnext = 0; }
  15667. if (state.whave < state.wsize) { state.whave += dist; }
  15668. }
  15669. }
  15670. return 0;
  15671. }
  15672. function inflate(strm, flush) {
  15673. var state;
  15674. var input, output; // input/output buffers
  15675. var next; /* next input INDEX */
  15676. var put; /* next output INDEX */
  15677. var have, left; /* available input and output */
  15678. var hold; /* bit buffer */
  15679. var bits; /* bits in bit buffer */
  15680. var _in, _out; /* save starting available input and output */
  15681. var copy; /* number of stored or match bytes to copy */
  15682. var from; /* where to copy match bytes from */
  15683. var from_source;
  15684. var here = 0; /* current decoding table entry */
  15685. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  15686. //var last; /* parent table entry */
  15687. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  15688. var len; /* length to copy for repeats, bits to drop */
  15689. var ret; /* return code */
  15690. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  15691. var opts;
  15692. var n; // temporary var for NEED_BITS
  15693. var order = /* permutation of code lengths */
  15694. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  15695. if (!strm || !strm.state || !strm.output ||
  15696. (!strm.input && strm.avail_in !== 0)) {
  15697. return Z_STREAM_ERROR;
  15698. }
  15699. state = strm.state;
  15700. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  15701. //--- LOAD() ---
  15702. put = strm.next_out;
  15703. output = strm.output;
  15704. left = strm.avail_out;
  15705. next = strm.next_in;
  15706. input = strm.input;
  15707. have = strm.avail_in;
  15708. hold = state.hold;
  15709. bits = state.bits;
  15710. //---
  15711. _in = have;
  15712. _out = left;
  15713. ret = Z_OK;
  15714. inf_leave: // goto emulation
  15715. for (;;) {
  15716. switch (state.mode) {
  15717. case HEAD:
  15718. if (state.wrap === 0) {
  15719. state.mode = TYPEDO;
  15720. break;
  15721. }
  15722. //=== NEEDBITS(16);
  15723. while (bits < 16) {
  15724. if (have === 0) { break inf_leave; }
  15725. have--;
  15726. hold += input[next++] << bits;
  15727. bits += 8;
  15728. }
  15729. //===//
  15730. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  15731. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  15732. //=== CRC2(state.check, hold);
  15733. hbuf[0] = hold & 0xff;
  15734. hbuf[1] = (hold >>> 8) & 0xff;
  15735. state.check = crc32(state.check, hbuf, 2, 0);
  15736. //===//
  15737. //=== INITBITS();
  15738. hold = 0;
  15739. bits = 0;
  15740. //===//
  15741. state.mode = FLAGS;
  15742. break;
  15743. }
  15744. state.flags = 0; /* expect zlib header */
  15745. if (state.head) {
  15746. state.head.done = false;
  15747. }
  15748. if (!(state.wrap & 1) || /* check if zlib header allowed */
  15749. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  15750. strm.msg = 'incorrect header check';
  15751. state.mode = BAD;
  15752. break;
  15753. }
  15754. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  15755. strm.msg = 'unknown compression method';
  15756. state.mode = BAD;
  15757. break;
  15758. }
  15759. //--- DROPBITS(4) ---//
  15760. hold >>>= 4;
  15761. bits -= 4;
  15762. //---//
  15763. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  15764. if (state.wbits === 0) {
  15765. state.wbits = len;
  15766. }
  15767. else if (len > state.wbits) {
  15768. strm.msg = 'invalid window size';
  15769. state.mode = BAD;
  15770. break;
  15771. }
  15772. state.dmax = 1 << len;
  15773. //Tracev((stderr, "inflate: zlib header ok\n"));
  15774. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  15775. state.mode = hold & 0x200 ? DICTID : TYPE;
  15776. //=== INITBITS();
  15777. hold = 0;
  15778. bits = 0;
  15779. //===//
  15780. break;
  15781. case FLAGS:
  15782. //=== NEEDBITS(16); */
  15783. while (bits < 16) {
  15784. if (have === 0) { break inf_leave; }
  15785. have--;
  15786. hold += input[next++] << bits;
  15787. bits += 8;
  15788. }
  15789. //===//
  15790. state.flags = hold;
  15791. if ((state.flags & 0xff) !== Z_DEFLATED) {
  15792. strm.msg = 'unknown compression method';
  15793. state.mode = BAD;
  15794. break;
  15795. }
  15796. if (state.flags & 0xe000) {
  15797. strm.msg = 'unknown header flags set';
  15798. state.mode = BAD;
  15799. break;
  15800. }
  15801. if (state.head) {
  15802. state.head.text = ((hold >> 8) & 1);
  15803. }
  15804. if (state.flags & 0x0200) {
  15805. //=== CRC2(state.check, hold);
  15806. hbuf[0] = hold & 0xff;
  15807. hbuf[1] = (hold >>> 8) & 0xff;
  15808. state.check = crc32(state.check, hbuf, 2, 0);
  15809. //===//
  15810. }
  15811. //=== INITBITS();
  15812. hold = 0;
  15813. bits = 0;
  15814. //===//
  15815. state.mode = TIME;
  15816. /* falls through */
  15817. case TIME:
  15818. //=== NEEDBITS(32); */
  15819. while (bits < 32) {
  15820. if (have === 0) { break inf_leave; }
  15821. have--;
  15822. hold += input[next++] << bits;
  15823. bits += 8;
  15824. }
  15825. //===//
  15826. if (state.head) {
  15827. state.head.time = hold;
  15828. }
  15829. if (state.flags & 0x0200) {
  15830. //=== CRC4(state.check, hold)
  15831. hbuf[0] = hold & 0xff;
  15832. hbuf[1] = (hold >>> 8) & 0xff;
  15833. hbuf[2] = (hold >>> 16) & 0xff;
  15834. hbuf[3] = (hold >>> 24) & 0xff;
  15835. state.check = crc32(state.check, hbuf, 4, 0);
  15836. //===
  15837. }
  15838. //=== INITBITS();
  15839. hold = 0;
  15840. bits = 0;
  15841. //===//
  15842. state.mode = OS;
  15843. /* falls through */
  15844. case OS:
  15845. //=== NEEDBITS(16); */
  15846. while (bits < 16) {
  15847. if (have === 0) { break inf_leave; }
  15848. have--;
  15849. hold += input[next++] << bits;
  15850. bits += 8;
  15851. }
  15852. //===//
  15853. if (state.head) {
  15854. state.head.xflags = (hold & 0xff);
  15855. state.head.os = (hold >> 8);
  15856. }
  15857. if (state.flags & 0x0200) {
  15858. //=== CRC2(state.check, hold);
  15859. hbuf[0] = hold & 0xff;
  15860. hbuf[1] = (hold >>> 8) & 0xff;
  15861. state.check = crc32(state.check, hbuf, 2, 0);
  15862. //===//
  15863. }
  15864. //=== INITBITS();
  15865. hold = 0;
  15866. bits = 0;
  15867. //===//
  15868. state.mode = EXLEN;
  15869. /* falls through */
  15870. case EXLEN:
  15871. if (state.flags & 0x0400) {
  15872. //=== NEEDBITS(16); */
  15873. while (bits < 16) {
  15874. if (have === 0) { break inf_leave; }
  15875. have--;
  15876. hold += input[next++] << bits;
  15877. bits += 8;
  15878. }
  15879. //===//
  15880. state.length = hold;
  15881. if (state.head) {
  15882. state.head.extra_len = hold;
  15883. }
  15884. if (state.flags & 0x0200) {
  15885. //=== CRC2(state.check, hold);
  15886. hbuf[0] = hold & 0xff;
  15887. hbuf[1] = (hold >>> 8) & 0xff;
  15888. state.check = crc32(state.check, hbuf, 2, 0);
  15889. //===//
  15890. }
  15891. //=== INITBITS();
  15892. hold = 0;
  15893. bits = 0;
  15894. //===//
  15895. }
  15896. else if (state.head) {
  15897. state.head.extra = null/*Z_NULL*/;
  15898. }
  15899. state.mode = EXTRA;
  15900. /* falls through */
  15901. case EXTRA:
  15902. if (state.flags & 0x0400) {
  15903. copy = state.length;
  15904. if (copy > have) { copy = have; }
  15905. if (copy) {
  15906. if (state.head) {
  15907. len = state.head.extra_len - state.length;
  15908. if (!state.head.extra) {
  15909. // Use untyped array for more conveniend processing later
  15910. state.head.extra = new Array(state.head.extra_len);
  15911. }
  15912. utils.arraySet(
  15913. state.head.extra,
  15914. input,
  15915. next,
  15916. // extra field is limited to 65536 bytes
  15917. // - no need for additional size check
  15918. copy,
  15919. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  15920. len
  15921. );
  15922. //zmemcpy(state.head.extra + len, next,
  15923. // len + copy > state.head.extra_max ?
  15924. // state.head.extra_max - len : copy);
  15925. }
  15926. if (state.flags & 0x0200) {
  15927. state.check = crc32(state.check, input, copy, next);
  15928. }
  15929. have -= copy;
  15930. next += copy;
  15931. state.length -= copy;
  15932. }
  15933. if (state.length) { break inf_leave; }
  15934. }
  15935. state.length = 0;
  15936. state.mode = NAME;
  15937. /* falls through */
  15938. case NAME:
  15939. if (state.flags & 0x0800) {
  15940. if (have === 0) { break inf_leave; }
  15941. copy = 0;
  15942. do {
  15943. // TODO: 2 or 1 bytes?
  15944. len = input[next + copy++];
  15945. /* use constant limit because in js we should not preallocate memory */
  15946. if (state.head && len &&
  15947. (state.length < 65536 /*state.head.name_max*/)) {
  15948. state.head.name += String.fromCharCode(len);
  15949. }
  15950. } while (len && copy < have);
  15951. if (state.flags & 0x0200) {
  15952. state.check = crc32(state.check, input, copy, next);
  15953. }
  15954. have -= copy;
  15955. next += copy;
  15956. if (len) { break inf_leave; }
  15957. }
  15958. else if (state.head) {
  15959. state.head.name = null;
  15960. }
  15961. state.length = 0;
  15962. state.mode = COMMENT;
  15963. /* falls through */
  15964. case COMMENT:
  15965. if (state.flags & 0x1000) {
  15966. if (have === 0) { break inf_leave; }
  15967. copy = 0;
  15968. do {
  15969. len = input[next + copy++];
  15970. /* use constant limit because in js we should not preallocate memory */
  15971. if (state.head && len &&
  15972. (state.length < 65536 /*state.head.comm_max*/)) {
  15973. state.head.comment += String.fromCharCode(len);
  15974. }
  15975. } while (len && copy < have);
  15976. if (state.flags & 0x0200) {
  15977. state.check = crc32(state.check, input, copy, next);
  15978. }
  15979. have -= copy;
  15980. next += copy;
  15981. if (len) { break inf_leave; }
  15982. }
  15983. else if (state.head) {
  15984. state.head.comment = null;
  15985. }
  15986. state.mode = HCRC;
  15987. /* falls through */
  15988. case HCRC:
  15989. if (state.flags & 0x0200) {
  15990. //=== NEEDBITS(16); */
  15991. while (bits < 16) {
  15992. if (have === 0) { break inf_leave; }
  15993. have--;
  15994. hold += input[next++] << bits;
  15995. bits += 8;
  15996. }
  15997. //===//
  15998. if (hold !== (state.check & 0xffff)) {
  15999. strm.msg = 'header crc mismatch';
  16000. state.mode = BAD;
  16001. break;
  16002. }
  16003. //=== INITBITS();
  16004. hold = 0;
  16005. bits = 0;
  16006. //===//
  16007. }
  16008. if (state.head) {
  16009. state.head.hcrc = ((state.flags >> 9) & 1);
  16010. state.head.done = true;
  16011. }
  16012. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16013. state.mode = TYPE;
  16014. break;
  16015. case DICTID:
  16016. //=== NEEDBITS(32); */
  16017. while (bits < 32) {
  16018. if (have === 0) { break inf_leave; }
  16019. have--;
  16020. hold += input[next++] << bits;
  16021. bits += 8;
  16022. }
  16023. //===//
  16024. strm.adler = state.check = ZSWAP32(hold);
  16025. //=== INITBITS();
  16026. hold = 0;
  16027. bits = 0;
  16028. //===//
  16029. state.mode = DICT;
  16030. /* falls through */
  16031. case DICT:
  16032. if (state.havedict === 0) {
  16033. //--- RESTORE() ---
  16034. strm.next_out = put;
  16035. strm.avail_out = left;
  16036. strm.next_in = next;
  16037. strm.avail_in = have;
  16038. state.hold = hold;
  16039. state.bits = bits;
  16040. //---
  16041. return Z_NEED_DICT;
  16042. }
  16043. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16044. state.mode = TYPE;
  16045. /* falls through */
  16046. case TYPE:
  16047. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16048. /* falls through */
  16049. case TYPEDO:
  16050. if (state.last) {
  16051. //--- BYTEBITS() ---//
  16052. hold >>>= bits & 7;
  16053. bits -= bits & 7;
  16054. //---//
  16055. state.mode = CHECK;
  16056. break;
  16057. }
  16058. //=== NEEDBITS(3); */
  16059. while (bits < 3) {
  16060. if (have === 0) { break inf_leave; }
  16061. have--;
  16062. hold += input[next++] << bits;
  16063. bits += 8;
  16064. }
  16065. //===//
  16066. state.last = (hold & 0x01)/*BITS(1)*/;
  16067. //--- DROPBITS(1) ---//
  16068. hold >>>= 1;
  16069. bits -= 1;
  16070. //---//
  16071. switch ((hold & 0x03)/*BITS(2)*/) {
  16072. case 0: /* stored block */
  16073. //Tracev((stderr, "inflate: stored block%s\n",
  16074. // state.last ? " (last)" : ""));
  16075. state.mode = STORED;
  16076. break;
  16077. case 1: /* fixed block */
  16078. fixedtables(state);
  16079. //Tracev((stderr, "inflate: fixed codes block%s\n",
  16080. // state.last ? " (last)" : ""));
  16081. state.mode = LEN_; /* decode codes */
  16082. if (flush === Z_TREES) {
  16083. //--- DROPBITS(2) ---//
  16084. hold >>>= 2;
  16085. bits -= 2;
  16086. //---//
  16087. break inf_leave;
  16088. }
  16089. break;
  16090. case 2: /* dynamic block */
  16091. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  16092. // state.last ? " (last)" : ""));
  16093. state.mode = TABLE;
  16094. break;
  16095. case 3:
  16096. strm.msg = 'invalid block type';
  16097. state.mode = BAD;
  16098. }
  16099. //--- DROPBITS(2) ---//
  16100. hold >>>= 2;
  16101. bits -= 2;
  16102. //---//
  16103. break;
  16104. case STORED:
  16105. //--- BYTEBITS() ---// /* go to byte boundary */
  16106. hold >>>= bits & 7;
  16107. bits -= bits & 7;
  16108. //---//
  16109. //=== NEEDBITS(32); */
  16110. while (bits < 32) {
  16111. if (have === 0) { break inf_leave; }
  16112. have--;
  16113. hold += input[next++] << bits;
  16114. bits += 8;
  16115. }
  16116. //===//
  16117. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  16118. strm.msg = 'invalid stored block lengths';
  16119. state.mode = BAD;
  16120. break;
  16121. }
  16122. state.length = hold & 0xffff;
  16123. //Tracev((stderr, "inflate: stored length %u\n",
  16124. // state.length));
  16125. //=== INITBITS();
  16126. hold = 0;
  16127. bits = 0;
  16128. //===//
  16129. state.mode = COPY_;
  16130. if (flush === Z_TREES) { break inf_leave; }
  16131. /* falls through */
  16132. case COPY_:
  16133. state.mode = COPY;
  16134. /* falls through */
  16135. case COPY:
  16136. copy = state.length;
  16137. if (copy) {
  16138. if (copy > have) { copy = have; }
  16139. if (copy > left) { copy = left; }
  16140. if (copy === 0) { break inf_leave; }
  16141. //--- zmemcpy(put, next, copy); ---
  16142. utils.arraySet(output, input, next, copy, put);
  16143. //---//
  16144. have -= copy;
  16145. next += copy;
  16146. left -= copy;
  16147. put += copy;
  16148. state.length -= copy;
  16149. break;
  16150. }
  16151. //Tracev((stderr, "inflate: stored end\n"));
  16152. state.mode = TYPE;
  16153. break;
  16154. case TABLE:
  16155. //=== NEEDBITS(14); */
  16156. while (bits < 14) {
  16157. if (have === 0) { break inf_leave; }
  16158. have--;
  16159. hold += input[next++] << bits;
  16160. bits += 8;
  16161. }
  16162. //===//
  16163. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  16164. //--- DROPBITS(5) ---//
  16165. hold >>>= 5;
  16166. bits -= 5;
  16167. //---//
  16168. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  16169. //--- DROPBITS(5) ---//
  16170. hold >>>= 5;
  16171. bits -= 5;
  16172. //---//
  16173. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  16174. //--- DROPBITS(4) ---//
  16175. hold >>>= 4;
  16176. bits -= 4;
  16177. //---//
  16178. //#ifndef PKZIP_BUG_WORKAROUND
  16179. if (state.nlen > 286 || state.ndist > 30) {
  16180. strm.msg = 'too many length or distance symbols';
  16181. state.mode = BAD;
  16182. break;
  16183. }
  16184. //#endif
  16185. //Tracev((stderr, "inflate: table sizes ok\n"));
  16186. state.have = 0;
  16187. state.mode = LENLENS;
  16188. /* falls through */
  16189. case LENLENS:
  16190. while (state.have < state.ncode) {
  16191. //=== NEEDBITS(3);
  16192. while (bits < 3) {
  16193. if (have === 0) { break inf_leave; }
  16194. have--;
  16195. hold += input[next++] << bits;
  16196. bits += 8;
  16197. }
  16198. //===//
  16199. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  16200. //--- DROPBITS(3) ---//
  16201. hold >>>= 3;
  16202. bits -= 3;
  16203. //---//
  16204. }
  16205. while (state.have < 19) {
  16206. state.lens[order[state.have++]] = 0;
  16207. }
  16208. // We have separate tables & no pointers. 2 commented lines below not needed.
  16209. //state.next = state.codes;
  16210. //state.lencode = state.next;
  16211. // Switch to use dynamic table
  16212. state.lencode = state.lendyn;
  16213. state.lenbits = 7;
  16214. opts = {bits: state.lenbits};
  16215. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  16216. state.lenbits = opts.bits;
  16217. if (ret) {
  16218. strm.msg = 'invalid code lengths set';
  16219. state.mode = BAD;
  16220. break;
  16221. }
  16222. //Tracev((stderr, "inflate: code lengths ok\n"));
  16223. state.have = 0;
  16224. state.mode = CODELENS;
  16225. /* falls through */
  16226. case CODELENS:
  16227. while (state.have < state.nlen + state.ndist) {
  16228. for (;;) {
  16229. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  16230. here_bits = here >>> 24;
  16231. here_op = (here >>> 16) & 0xff;
  16232. here_val = here & 0xffff;
  16233. if ((here_bits) <= bits) { break; }
  16234. //--- PULLBYTE() ---//
  16235. if (have === 0) { break inf_leave; }
  16236. have--;
  16237. hold += input[next++] << bits;
  16238. bits += 8;
  16239. //---//
  16240. }
  16241. if (here_val < 16) {
  16242. //--- DROPBITS(here.bits) ---//
  16243. hold >>>= here_bits;
  16244. bits -= here_bits;
  16245. //---//
  16246. state.lens[state.have++] = here_val;
  16247. }
  16248. else {
  16249. if (here_val === 16) {
  16250. //=== NEEDBITS(here.bits + 2);
  16251. n = here_bits + 2;
  16252. while (bits < n) {
  16253. if (have === 0) { break inf_leave; }
  16254. have--;
  16255. hold += input[next++] << bits;
  16256. bits += 8;
  16257. }
  16258. //===//
  16259. //--- DROPBITS(here.bits) ---//
  16260. hold >>>= here_bits;
  16261. bits -= here_bits;
  16262. //---//
  16263. if (state.have === 0) {
  16264. strm.msg = 'invalid bit length repeat';
  16265. state.mode = BAD;
  16266. break;
  16267. }
  16268. len = state.lens[state.have - 1];
  16269. copy = 3 + (hold & 0x03);//BITS(2);
  16270. //--- DROPBITS(2) ---//
  16271. hold >>>= 2;
  16272. bits -= 2;
  16273. //---//
  16274. }
  16275. else if (here_val === 17) {
  16276. //=== NEEDBITS(here.bits + 3);
  16277. n = here_bits + 3;
  16278. while (bits < n) {
  16279. if (have === 0) { break inf_leave; }
  16280. have--;
  16281. hold += input[next++] << bits;
  16282. bits += 8;
  16283. }
  16284. //===//
  16285. //--- DROPBITS(here.bits) ---//
  16286. hold >>>= here_bits;
  16287. bits -= here_bits;
  16288. //---//
  16289. len = 0;
  16290. copy = 3 + (hold & 0x07);//BITS(3);
  16291. //--- DROPBITS(3) ---//
  16292. hold >>>= 3;
  16293. bits -= 3;
  16294. //---//
  16295. }
  16296. else {
  16297. //=== NEEDBITS(here.bits + 7);
  16298. n = here_bits + 7;
  16299. while (bits < n) {
  16300. if (have === 0) { break inf_leave; }
  16301. have--;
  16302. hold += input[next++] << bits;
  16303. bits += 8;
  16304. }
  16305. //===//
  16306. //--- DROPBITS(here.bits) ---//
  16307. hold >>>= here_bits;
  16308. bits -= here_bits;
  16309. //---//
  16310. len = 0;
  16311. copy = 11 + (hold & 0x7f);//BITS(7);
  16312. //--- DROPBITS(7) ---//
  16313. hold >>>= 7;
  16314. bits -= 7;
  16315. //---//
  16316. }
  16317. if (state.have + copy > state.nlen + state.ndist) {
  16318. strm.msg = 'invalid bit length repeat';
  16319. state.mode = BAD;
  16320. break;
  16321. }
  16322. while (copy--) {
  16323. state.lens[state.have++] = len;
  16324. }
  16325. }
  16326. }
  16327. /* handle error breaks in while */
  16328. if (state.mode === BAD) { break; }
  16329. /* check for end-of-block code (better have one) */
  16330. if (state.lens[256] === 0) {
  16331. strm.msg = 'invalid code -- missing end-of-block';
  16332. state.mode = BAD;
  16333. break;
  16334. }
  16335. /* build code tables -- note: do not change the lenbits or distbits
  16336. values here (9 and 6) without reading the comments in inftrees.h
  16337. concerning the ENOUGH constants, which depend on those values */
  16338. state.lenbits = 9;
  16339. opts = {bits: state.lenbits};
  16340. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  16341. // We have separate tables & no pointers. 2 commented lines below not needed.
  16342. // state.next_index = opts.table_index;
  16343. state.lenbits = opts.bits;
  16344. // state.lencode = state.next;
  16345. if (ret) {
  16346. strm.msg = 'invalid literal/lengths set';
  16347. state.mode = BAD;
  16348. break;
  16349. }
  16350. state.distbits = 6;
  16351. //state.distcode.copy(state.codes);
  16352. // Switch to use dynamic table
  16353. state.distcode = state.distdyn;
  16354. opts = {bits: state.distbits};
  16355. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  16356. // We have separate tables & no pointers. 2 commented lines below not needed.
  16357. // state.next_index = opts.table_index;
  16358. state.distbits = opts.bits;
  16359. // state.distcode = state.next;
  16360. if (ret) {
  16361. strm.msg = 'invalid distances set';
  16362. state.mode = BAD;
  16363. break;
  16364. }
  16365. //Tracev((stderr, 'inflate: codes ok\n'));
  16366. state.mode = LEN_;
  16367. if (flush === Z_TREES) { break inf_leave; }
  16368. /* falls through */
  16369. case LEN_:
  16370. state.mode = LEN;
  16371. /* falls through */
  16372. case LEN:
  16373. if (have >= 6 && left >= 258) {
  16374. //--- RESTORE() ---
  16375. strm.next_out = put;
  16376. strm.avail_out = left;
  16377. strm.next_in = next;
  16378. strm.avail_in = have;
  16379. state.hold = hold;
  16380. state.bits = bits;
  16381. //---
  16382. inflate_fast(strm, _out);
  16383. //--- LOAD() ---
  16384. put = strm.next_out;
  16385. output = strm.output;
  16386. left = strm.avail_out;
  16387. next = strm.next_in;
  16388. input = strm.input;
  16389. have = strm.avail_in;
  16390. hold = state.hold;
  16391. bits = state.bits;
  16392. //---
  16393. if (state.mode === TYPE) {
  16394. state.back = -1;
  16395. }
  16396. break;
  16397. }
  16398. state.back = 0;
  16399. for (;;) {
  16400. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  16401. here_bits = here >>> 24;
  16402. here_op = (here >>> 16) & 0xff;
  16403. here_val = here & 0xffff;
  16404. if (here_bits <= bits) { break; }
  16405. //--- PULLBYTE() ---//
  16406. if (have === 0) { break inf_leave; }
  16407. have--;
  16408. hold += input[next++] << bits;
  16409. bits += 8;
  16410. //---//
  16411. }
  16412. if (here_op && (here_op & 0xf0) === 0) {
  16413. last_bits = here_bits;
  16414. last_op = here_op;
  16415. last_val = here_val;
  16416. for (;;) {
  16417. here = state.lencode[last_val +
  16418. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16419. here_bits = here >>> 24;
  16420. here_op = (here >>> 16) & 0xff;
  16421. here_val = here & 0xffff;
  16422. if ((last_bits + here_bits) <= bits) { break; }
  16423. //--- PULLBYTE() ---//
  16424. if (have === 0) { break inf_leave; }
  16425. have--;
  16426. hold += input[next++] << bits;
  16427. bits += 8;
  16428. //---//
  16429. }
  16430. //--- DROPBITS(last.bits) ---//
  16431. hold >>>= last_bits;
  16432. bits -= last_bits;
  16433. //---//
  16434. state.back += last_bits;
  16435. }
  16436. //--- DROPBITS(here.bits) ---//
  16437. hold >>>= here_bits;
  16438. bits -= here_bits;
  16439. //---//
  16440. state.back += here_bits;
  16441. state.length = here_val;
  16442. if (here_op === 0) {
  16443. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16444. // "inflate: literal '%c'\n" :
  16445. // "inflate: literal 0x%02x\n", here.val));
  16446. state.mode = LIT;
  16447. break;
  16448. }
  16449. if (here_op & 32) {
  16450. //Tracevv((stderr, "inflate: end of block\n"));
  16451. state.back = -1;
  16452. state.mode = TYPE;
  16453. break;
  16454. }
  16455. if (here_op & 64) {
  16456. strm.msg = 'invalid literal/length code';
  16457. state.mode = BAD;
  16458. break;
  16459. }
  16460. state.extra = here_op & 15;
  16461. state.mode = LENEXT;
  16462. /* falls through */
  16463. case LENEXT:
  16464. if (state.extra) {
  16465. //=== NEEDBITS(state.extra);
  16466. n = state.extra;
  16467. while (bits < n) {
  16468. if (have === 0) { break inf_leave; }
  16469. have--;
  16470. hold += input[next++] << bits;
  16471. bits += 8;
  16472. }
  16473. //===//
  16474. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16475. //--- DROPBITS(state.extra) ---//
  16476. hold >>>= state.extra;
  16477. bits -= state.extra;
  16478. //---//
  16479. state.back += state.extra;
  16480. }
  16481. //Tracevv((stderr, "inflate: length %u\n", state.length));
  16482. state.was = state.length;
  16483. state.mode = DIST;
  16484. /* falls through */
  16485. case DIST:
  16486. for (;;) {
  16487. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  16488. here_bits = here >>> 24;
  16489. here_op = (here >>> 16) & 0xff;
  16490. here_val = here & 0xffff;
  16491. if ((here_bits) <= bits) { break; }
  16492. //--- PULLBYTE() ---//
  16493. if (have === 0) { break inf_leave; }
  16494. have--;
  16495. hold += input[next++] << bits;
  16496. bits += 8;
  16497. //---//
  16498. }
  16499. if ((here_op & 0xf0) === 0) {
  16500. last_bits = here_bits;
  16501. last_op = here_op;
  16502. last_val = here_val;
  16503. for (;;) {
  16504. here = state.distcode[last_val +
  16505. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16506. here_bits = here >>> 24;
  16507. here_op = (here >>> 16) & 0xff;
  16508. here_val = here & 0xffff;
  16509. if ((last_bits + here_bits) <= bits) { break; }
  16510. //--- PULLBYTE() ---//
  16511. if (have === 0) { break inf_leave; }
  16512. have--;
  16513. hold += input[next++] << bits;
  16514. bits += 8;
  16515. //---//
  16516. }
  16517. //--- DROPBITS(last.bits) ---//
  16518. hold >>>= last_bits;
  16519. bits -= last_bits;
  16520. //---//
  16521. state.back += last_bits;
  16522. }
  16523. //--- DROPBITS(here.bits) ---//
  16524. hold >>>= here_bits;
  16525. bits -= here_bits;
  16526. //---//
  16527. state.back += here_bits;
  16528. if (here_op & 64) {
  16529. strm.msg = 'invalid distance code';
  16530. state.mode = BAD;
  16531. break;
  16532. }
  16533. state.offset = here_val;
  16534. state.extra = (here_op) & 15;
  16535. state.mode = DISTEXT;
  16536. /* falls through */
  16537. case DISTEXT:
  16538. if (state.extra) {
  16539. //=== NEEDBITS(state.extra);
  16540. n = state.extra;
  16541. while (bits < n) {
  16542. if (have === 0) { break inf_leave; }
  16543. have--;
  16544. hold += input[next++] << bits;
  16545. bits += 8;
  16546. }
  16547. //===//
  16548. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16549. //--- DROPBITS(state.extra) ---//
  16550. hold >>>= state.extra;
  16551. bits -= state.extra;
  16552. //---//
  16553. state.back += state.extra;
  16554. }
  16555. //#ifdef INFLATE_STRICT
  16556. if (state.offset > state.dmax) {
  16557. strm.msg = 'invalid distance too far back';
  16558. state.mode = BAD;
  16559. break;
  16560. }
  16561. //#endif
  16562. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  16563. state.mode = MATCH;
  16564. /* falls through */
  16565. case MATCH:
  16566. if (left === 0) { break inf_leave; }
  16567. copy = _out - left;
  16568. if (state.offset > copy) { /* copy from window */
  16569. copy = state.offset - copy;
  16570. if (copy > state.whave) {
  16571. if (state.sane) {
  16572. strm.msg = 'invalid distance too far back';
  16573. state.mode = BAD;
  16574. break;
  16575. }
  16576. // (!) This block is disabled in zlib defailts,
  16577. // don't enable it for binary compatibility
  16578. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16579. // Trace((stderr, "inflate.c too far\n"));
  16580. // copy -= state.whave;
  16581. // if (copy > state.length) { copy = state.length; }
  16582. // if (copy > left) { copy = left; }
  16583. // left -= copy;
  16584. // state.length -= copy;
  16585. // do {
  16586. // output[put++] = 0;
  16587. // } while (--copy);
  16588. // if (state.length === 0) { state.mode = LEN; }
  16589. // break;
  16590. //#endif
  16591. }
  16592. if (copy > state.wnext) {
  16593. copy -= state.wnext;
  16594. from = state.wsize - copy;
  16595. }
  16596. else {
  16597. from = state.wnext - copy;
  16598. }
  16599. if (copy > state.length) { copy = state.length; }
  16600. from_source = state.window;
  16601. }
  16602. else { /* copy from output */
  16603. from_source = output;
  16604. from = put - state.offset;
  16605. copy = state.length;
  16606. }
  16607. if (copy > left) { copy = left; }
  16608. left -= copy;
  16609. state.length -= copy;
  16610. do {
  16611. output[put++] = from_source[from++];
  16612. } while (--copy);
  16613. if (state.length === 0) { state.mode = LEN; }
  16614. break;
  16615. case LIT:
  16616. if (left === 0) { break inf_leave; }
  16617. output[put++] = state.length;
  16618. left--;
  16619. state.mode = LEN;
  16620. break;
  16621. case CHECK:
  16622. if (state.wrap) {
  16623. //=== NEEDBITS(32);
  16624. while (bits < 32) {
  16625. if (have === 0) { break inf_leave; }
  16626. have--;
  16627. // Use '|' insdead of '+' to make sure that result is signed
  16628. hold |= input[next++] << bits;
  16629. bits += 8;
  16630. }
  16631. //===//
  16632. _out -= left;
  16633. strm.total_out += _out;
  16634. state.total += _out;
  16635. if (_out) {
  16636. strm.adler = state.check =
  16637. /*UPDATE(state.check, put - _out, _out);*/
  16638. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  16639. }
  16640. _out = left;
  16641. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  16642. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  16643. strm.msg = 'incorrect data check';
  16644. state.mode = BAD;
  16645. break;
  16646. }
  16647. //=== INITBITS();
  16648. hold = 0;
  16649. bits = 0;
  16650. //===//
  16651. //Tracev((stderr, "inflate: check matches trailer\n"));
  16652. }
  16653. state.mode = LENGTH;
  16654. /* falls through */
  16655. case LENGTH:
  16656. if (state.wrap && state.flags) {
  16657. //=== NEEDBITS(32);
  16658. while (bits < 32) {
  16659. if (have === 0) { break inf_leave; }
  16660. have--;
  16661. hold += input[next++] << bits;
  16662. bits += 8;
  16663. }
  16664. //===//
  16665. if (hold !== (state.total & 0xffffffff)) {
  16666. strm.msg = 'incorrect length check';
  16667. state.mode = BAD;
  16668. break;
  16669. }
  16670. //=== INITBITS();
  16671. hold = 0;
  16672. bits = 0;
  16673. //===//
  16674. //Tracev((stderr, "inflate: length matches trailer\n"));
  16675. }
  16676. state.mode = DONE;
  16677. /* falls through */
  16678. case DONE:
  16679. ret = Z_STREAM_END;
  16680. break inf_leave;
  16681. case BAD:
  16682. ret = Z_DATA_ERROR;
  16683. break inf_leave;
  16684. case MEM:
  16685. return Z_MEM_ERROR;
  16686. case SYNC:
  16687. /* falls through */
  16688. default:
  16689. return Z_STREAM_ERROR;
  16690. }
  16691. }
  16692. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  16693. /*
  16694. Return from inflate(), updating the total counts and the check value.
  16695. If there was no progress during the inflate() call, return a buffer
  16696. error. Call updatewindow() to create and/or update the window state.
  16697. Note: a memory error from inflate() is non-recoverable.
  16698. */
  16699. //--- RESTORE() ---
  16700. strm.next_out = put;
  16701. strm.avail_out = left;
  16702. strm.next_in = next;
  16703. strm.avail_in = have;
  16704. state.hold = hold;
  16705. state.bits = bits;
  16706. //---
  16707. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  16708. (state.mode < CHECK || flush !== Z_FINISH))) {
  16709. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  16710. state.mode = MEM;
  16711. return Z_MEM_ERROR;
  16712. }
  16713. }
  16714. _in -= strm.avail_in;
  16715. _out -= strm.avail_out;
  16716. strm.total_in += _in;
  16717. strm.total_out += _out;
  16718. state.total += _out;
  16719. if (state.wrap && _out) {
  16720. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  16721. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  16722. }
  16723. strm.data_type = state.bits + (state.last ? 64 : 0) +
  16724. (state.mode === TYPE ? 128 : 0) +
  16725. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  16726. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  16727. ret = Z_BUF_ERROR;
  16728. }
  16729. return ret;
  16730. }
  16731. function inflateEnd(strm) {
  16732. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  16733. return Z_STREAM_ERROR;
  16734. }
  16735. var state = strm.state;
  16736. if (state.window) {
  16737. state.window = null;
  16738. }
  16739. strm.state = null;
  16740. return Z_OK;
  16741. }
  16742. function inflateGetHeader(strm, head) {
  16743. var state;
  16744. /* check state */
  16745. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16746. state = strm.state;
  16747. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  16748. /* save header structure */
  16749. state.head = head;
  16750. head.done = false;
  16751. return Z_OK;
  16752. }
  16753. exports.inflateReset = inflateReset;
  16754. exports.inflateReset2 = inflateReset2;
  16755. exports.inflateResetKeep = inflateResetKeep;
  16756. exports.inflateInit = inflateInit;
  16757. exports.inflateInit2 = inflateInit2;
  16758. exports.inflate = inflate;
  16759. exports.inflateEnd = inflateEnd;
  16760. exports.inflateGetHeader = inflateGetHeader;
  16761. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  16762. /* Not implemented
  16763. exports.inflateCopy = inflateCopy;
  16764. exports.inflateGetDictionary = inflateGetDictionary;
  16765. exports.inflateMark = inflateMark;
  16766. exports.inflatePrime = inflatePrime;
  16767. exports.inflateSetDictionary = inflateSetDictionary;
  16768. exports.inflateSync = inflateSync;
  16769. exports.inflateSyncPoint = inflateSyncPoint;
  16770. exports.inflateUndermine = inflateUndermine;
  16771. */
  16772. },{"../utils/common":51,"./adler32":53,"./crc32":55,"./inffast":58,"./inftrees":60}],60:[function(require,module,exports){
  16773. 'use strict';
  16774. var utils = require('../utils/common');
  16775. var MAXBITS = 15;
  16776. var ENOUGH_LENS = 852;
  16777. var ENOUGH_DISTS = 592;
  16778. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16779. var CODES = 0;
  16780. var LENS = 1;
  16781. var DISTS = 2;
  16782. var lbase = [ /* Length codes 257..285 base */
  16783. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  16784. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  16785. ];
  16786. var lext = [ /* Length codes 257..285 extra */
  16787. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  16788. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  16789. ];
  16790. var dbase = [ /* Distance codes 0..29 base */
  16791. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  16792. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  16793. 8193, 12289, 16385, 24577, 0, 0
  16794. ];
  16795. var dext = [ /* Distance codes 0..29 extra */
  16796. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  16797. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  16798. 28, 28, 29, 29, 64, 64
  16799. ];
  16800. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  16801. {
  16802. var bits = opts.bits;
  16803. //here = opts.here; /* table entry for duplication */
  16804. var len = 0; /* a code's length in bits */
  16805. var sym = 0; /* index of code symbols */
  16806. var min = 0, max = 0; /* minimum and maximum code lengths */
  16807. var root = 0; /* number of index bits for root table */
  16808. var curr = 0; /* number of index bits for current table */
  16809. var drop = 0; /* code bits to drop for sub-table */
  16810. var left = 0; /* number of prefix codes available */
  16811. var used = 0; /* code entries in table used */
  16812. var huff = 0; /* Huffman code */
  16813. var incr; /* for incrementing code, index */
  16814. var fill; /* index for replicating entries */
  16815. var low; /* low bits for current root entry */
  16816. var mask; /* mask for low root bits */
  16817. var next; /* next available space in table */
  16818. var base = null; /* base value table to use */
  16819. var base_index = 0;
  16820. // var shoextra; /* extra bits table to use */
  16821. var end; /* use base and extra for symbol > end */
  16822. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  16823. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  16824. var extra = null;
  16825. var extra_index = 0;
  16826. var here_bits, here_op, here_val;
  16827. /*
  16828. Process a set of code lengths to create a canonical Huffman code. The
  16829. code lengths are lens[0..codes-1]. Each length corresponds to the
  16830. symbols 0..codes-1. The Huffman code is generated by first sorting the
  16831. symbols by length from short to long, and retaining the symbol order
  16832. for codes with equal lengths. Then the code starts with all zero bits
  16833. for the first code of the shortest length, and the codes are integer
  16834. increments for the same length, and zeros are appended as the length
  16835. increases. For the deflate format, these bits are stored backwards
  16836. from their more natural integer increment ordering, and so when the
  16837. decoding tables are built in the large loop below, the integer codes
  16838. are incremented backwards.
  16839. This routine assumes, but does not check, that all of the entries in
  16840. lens[] are in the range 0..MAXBITS. The caller must assure this.
  16841. 1..MAXBITS is interpreted as that code length. zero means that that
  16842. symbol does not occur in this code.
  16843. The codes are sorted by computing a count of codes for each length,
  16844. creating from that a table of starting indices for each length in the
  16845. sorted table, and then entering the symbols in order in the sorted
  16846. table. The sorted table is work[], with that space being provided by
  16847. the caller.
  16848. The length counts are used for other purposes as well, i.e. finding
  16849. the minimum and maximum length codes, determining if there are any
  16850. codes at all, checking for a valid set of lengths, and looking ahead
  16851. at length counts to determine sub-table sizes when building the
  16852. decoding tables.
  16853. */
  16854. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  16855. for (len = 0; len <= MAXBITS; len++) {
  16856. count[len] = 0;
  16857. }
  16858. for (sym = 0; sym < codes; sym++) {
  16859. count[lens[lens_index + sym]]++;
  16860. }
  16861. /* bound code lengths, force root to be within code lengths */
  16862. root = bits;
  16863. for (max = MAXBITS; max >= 1; max--) {
  16864. if (count[max] !== 0) { break; }
  16865. }
  16866. if (root > max) {
  16867. root = max;
  16868. }
  16869. if (max === 0) { /* no symbols to code at all */
  16870. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  16871. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  16872. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  16873. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  16874. //table.op[opts.table_index] = 64;
  16875. //table.bits[opts.table_index] = 1;
  16876. //table.val[opts.table_index++] = 0;
  16877. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  16878. opts.bits = 1;
  16879. return 0; /* no symbols, but wait for decoding to report error */
  16880. }
  16881. for (min = 1; min < max; min++) {
  16882. if (count[min] !== 0) { break; }
  16883. }
  16884. if (root < min) {
  16885. root = min;
  16886. }
  16887. /* check for an over-subscribed or incomplete set of lengths */
  16888. left = 1;
  16889. for (len = 1; len <= MAXBITS; len++) {
  16890. left <<= 1;
  16891. left -= count[len];
  16892. if (left < 0) {
  16893. return -1;
  16894. } /* over-subscribed */
  16895. }
  16896. if (left > 0 && (type === CODES || max !== 1)) {
  16897. return -1; /* incomplete set */
  16898. }
  16899. /* generate offsets into symbol table for each length for sorting */
  16900. offs[1] = 0;
  16901. for (len = 1; len < MAXBITS; len++) {
  16902. offs[len + 1] = offs[len] + count[len];
  16903. }
  16904. /* sort symbols by length, by symbol order within each length */
  16905. for (sym = 0; sym < codes; sym++) {
  16906. if (lens[lens_index + sym] !== 0) {
  16907. work[offs[lens[lens_index + sym]]++] = sym;
  16908. }
  16909. }
  16910. /*
  16911. Create and fill in decoding tables. In this loop, the table being
  16912. filled is at next and has curr index bits. The code being used is huff
  16913. with length len. That code is converted to an index by dropping drop
  16914. bits off of the bottom. For codes where len is less than drop + curr,
  16915. those top drop + curr - len bits are incremented through all values to
  16916. fill the table with replicated entries.
  16917. root is the number of index bits for the root table. When len exceeds
  16918. root, sub-tables are created pointed to by the root entry with an index
  16919. of the low root bits of huff. This is saved in low to check for when a
  16920. new sub-table should be started. drop is zero when the root table is
  16921. being filled, and drop is root when sub-tables are being filled.
  16922. When a new sub-table is needed, it is necessary to look ahead in the
  16923. code lengths to determine what size sub-table is needed. The length
  16924. counts are used for this, and so count[] is decremented as codes are
  16925. entered in the tables.
  16926. used keeps track of how many table entries have been allocated from the
  16927. provided *table space. It is checked for LENS and DIST tables against
  16928. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  16929. the initial root table size constants. See the comments in inftrees.h
  16930. for more information.
  16931. sym increments through all symbols, and the loop terminates when
  16932. all codes of length max, i.e. all codes, have been processed. This
  16933. routine permits incomplete codes, so another loop after this one fills
  16934. in the rest of the decoding tables with invalid code markers.
  16935. */
  16936. /* set up for code type */
  16937. // poor man optimization - use if-else instead of switch,
  16938. // to avoid deopts in old v8
  16939. if (type === CODES) {
  16940. base = extra = work; /* dummy value--not used */
  16941. end = 19;
  16942. } else if (type === LENS) {
  16943. base = lbase;
  16944. base_index -= 257;
  16945. extra = lext;
  16946. extra_index -= 257;
  16947. end = 256;
  16948. } else { /* DISTS */
  16949. base = dbase;
  16950. extra = dext;
  16951. end = -1;
  16952. }
  16953. /* initialize opts for loop */
  16954. huff = 0; /* starting code */
  16955. sym = 0; /* starting code symbol */
  16956. len = min; /* starting code length */
  16957. next = table_index; /* current table to fill in */
  16958. curr = root; /* current table index bits */
  16959. drop = 0; /* current bits to drop from code for index */
  16960. low = -1; /* trigger new sub-table when len > root */
  16961. used = 1 << root; /* use root table entries */
  16962. mask = used - 1; /* mask for comparing low */
  16963. /* check available table space */
  16964. if ((type === LENS && used > ENOUGH_LENS) ||
  16965. (type === DISTS && used > ENOUGH_DISTS)) {
  16966. return 1;
  16967. }
  16968. var i=0;
  16969. /* process all codes and make table entries */
  16970. for (;;) {
  16971. i++;
  16972. /* create table entry */
  16973. here_bits = len - drop;
  16974. if (work[sym] < end) {
  16975. here_op = 0;
  16976. here_val = work[sym];
  16977. }
  16978. else if (work[sym] > end) {
  16979. here_op = extra[extra_index + work[sym]];
  16980. here_val = base[base_index + work[sym]];
  16981. }
  16982. else {
  16983. here_op = 32 + 64; /* end of block */
  16984. here_val = 0;
  16985. }
  16986. /* replicate for those indices with low len bits equal to huff */
  16987. incr = 1 << (len - drop);
  16988. fill = 1 << curr;
  16989. min = fill; /* save offset to next table */
  16990. do {
  16991. fill -= incr;
  16992. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  16993. } while (fill !== 0);
  16994. /* backwards increment the len-bit code huff */
  16995. incr = 1 << (len - 1);
  16996. while (huff & incr) {
  16997. incr >>= 1;
  16998. }
  16999. if (incr !== 0) {
  17000. huff &= incr - 1;
  17001. huff += incr;
  17002. } else {
  17003. huff = 0;
  17004. }
  17005. /* go to next symbol, update count, len */
  17006. sym++;
  17007. if (--count[len] === 0) {
  17008. if (len === max) { break; }
  17009. len = lens[lens_index + work[sym]];
  17010. }
  17011. /* create new sub-table if needed */
  17012. if (len > root && (huff & mask) !== low) {
  17013. /* if first time, transition to sub-tables */
  17014. if (drop === 0) {
  17015. drop = root;
  17016. }
  17017. /* increment past last table */
  17018. next += min; /* here min is 1 << curr */
  17019. /* determine length of next table */
  17020. curr = len - drop;
  17021. left = 1 << curr;
  17022. while (curr + drop < max) {
  17023. left -= count[curr + drop];
  17024. if (left <= 0) { break; }
  17025. curr++;
  17026. left <<= 1;
  17027. }
  17028. /* check for enough space */
  17029. used += 1 << curr;
  17030. if ((type === LENS && used > ENOUGH_LENS) ||
  17031. (type === DISTS && used > ENOUGH_DISTS)) {
  17032. return 1;
  17033. }
  17034. /* point entry in root table to sub-table */
  17035. low = huff & mask;
  17036. /*table.op[low] = curr;
  17037. table.bits[low] = root;
  17038. table.val[low] = next - opts.table_index;*/
  17039. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17040. }
  17041. }
  17042. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17043. at most one remaining entry, since if the code is incomplete, the
  17044. maximum code length that was allowed to get this far is one bit) */
  17045. if (huff !== 0) {
  17046. //table.op[next + huff] = 64; /* invalid code marker */
  17047. //table.bits[next + huff] = len - drop;
  17048. //table.val[next + huff] = 0;
  17049. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17050. }
  17051. /* set return parameters */
  17052. //opts.table_index += used;
  17053. opts.bits = root;
  17054. return 0;
  17055. };
  17056. },{"../utils/common":51}],61:[function(require,module,exports){
  17057. 'use strict';
  17058. module.exports = {
  17059. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  17060. '1': 'stream end', /* Z_STREAM_END 1 */
  17061. '0': '', /* Z_OK 0 */
  17062. '-1': 'file error', /* Z_ERRNO (-1) */
  17063. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17064. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17065. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17066. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17067. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17068. };
  17069. },{}],62:[function(require,module,exports){
  17070. 'use strict';
  17071. var utils = require('../utils/common');
  17072. /* Public constants ==========================================================*/
  17073. /* ===========================================================================*/
  17074. //var Z_FILTERED = 1;
  17075. //var Z_HUFFMAN_ONLY = 2;
  17076. //var Z_RLE = 3;
  17077. var Z_FIXED = 4;
  17078. //var Z_DEFAULT_STRATEGY = 0;
  17079. /* Possible values of the data_type field (though see inflate()) */
  17080. var Z_BINARY = 0;
  17081. var Z_TEXT = 1;
  17082. //var Z_ASCII = 1; // = Z_TEXT
  17083. var Z_UNKNOWN = 2;
  17084. /*============================================================================*/
  17085. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17086. // From zutil.h
  17087. var STORED_BLOCK = 0;
  17088. var STATIC_TREES = 1;
  17089. var DYN_TREES = 2;
  17090. /* The three kinds of block type */
  17091. var MIN_MATCH = 3;
  17092. var MAX_MATCH = 258;
  17093. /* The minimum and maximum match lengths */
  17094. // From deflate.h
  17095. /* ===========================================================================
  17096. * Internal compression state.
  17097. */
  17098. var LENGTH_CODES = 29;
  17099. /* number of length codes, not counting the special END_BLOCK code */
  17100. var LITERALS = 256;
  17101. /* number of literal bytes 0..255 */
  17102. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17103. /* number of Literal or Length codes, including the END_BLOCK code */
  17104. var D_CODES = 30;
  17105. /* number of distance codes */
  17106. var BL_CODES = 19;
  17107. /* number of codes used to transfer the bit lengths */
  17108. var HEAP_SIZE = 2*L_CODES + 1;
  17109. /* maximum heap size */
  17110. var MAX_BITS = 15;
  17111. /* All codes must not exceed MAX_BITS bits */
  17112. var Buf_size = 16;
  17113. /* size of bit buffer in bi_buf */
  17114. /* ===========================================================================
  17115. * Constants
  17116. */
  17117. var MAX_BL_BITS = 7;
  17118. /* Bit length codes must not exceed MAX_BL_BITS bits */
  17119. var END_BLOCK = 256;
  17120. /* end of block literal code */
  17121. var REP_3_6 = 16;
  17122. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  17123. var REPZ_3_10 = 17;
  17124. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  17125. var REPZ_11_138 = 18;
  17126. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  17127. var extra_lbits = /* extra bits for each length code */
  17128. [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];
  17129. var extra_dbits = /* extra bits for each distance code */
  17130. [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];
  17131. var extra_blbits = /* extra bits for each bit length code */
  17132. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  17133. var bl_order =
  17134. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  17135. /* The lengths of the bit length codes are sent in order of decreasing
  17136. * probability, to avoid transmitting the lengths for unused bit length codes.
  17137. */
  17138. /* ===========================================================================
  17139. * Local data. These are initialized only once.
  17140. */
  17141. // We pre-fill arrays with 0 to avoid uninitialized gaps
  17142. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  17143. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  17144. var static_ltree = new Array((L_CODES+2) * 2);
  17145. zero(static_ltree);
  17146. /* The static literal tree. Since the bit lengths are imposed, there is no
  17147. * need for the L_CODES extra codes used during heap construction. However
  17148. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  17149. * below).
  17150. */
  17151. var static_dtree = new Array(D_CODES * 2);
  17152. zero(static_dtree);
  17153. /* The static distance tree. (Actually a trivial tree since all codes use
  17154. * 5 bits.)
  17155. */
  17156. var _dist_code = new Array(DIST_CODE_LEN);
  17157. zero(_dist_code);
  17158. /* Distance codes. The first 256 values correspond to the distances
  17159. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  17160. * the 15 bit distances.
  17161. */
  17162. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  17163. zero(_length_code);
  17164. /* length code for each normalized match length (0 == MIN_MATCH) */
  17165. var base_length = new Array(LENGTH_CODES);
  17166. zero(base_length);
  17167. /* First normalized length for each code (0 = MIN_MATCH) */
  17168. var base_dist = new Array(D_CODES);
  17169. zero(base_dist);
  17170. /* First normalized distance for each code (0 = distance of 1) */
  17171. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  17172. this.static_tree = static_tree; /* static tree or NULL */
  17173. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  17174. this.extra_base = extra_base; /* base index for extra_bits */
  17175. this.elems = elems; /* max number of elements in the tree */
  17176. this.max_length = max_length; /* max bit length for the codes */
  17177. // show if `static_tree` has data or dummy - needed for monomorphic objects
  17178. this.has_stree = static_tree && static_tree.length;
  17179. };
  17180. var static_l_desc;
  17181. var static_d_desc;
  17182. var static_bl_desc;
  17183. var TreeDesc = function(dyn_tree, stat_desc) {
  17184. this.dyn_tree = dyn_tree; /* the dynamic tree */
  17185. this.max_code = 0; /* largest code with non zero frequency */
  17186. this.stat_desc = stat_desc; /* the corresponding static tree */
  17187. };
  17188. function d_code(dist) {
  17189. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17190. }
  17191. /* ===========================================================================
  17192. * Output a short LSB first on the stream.
  17193. * IN assertion: there is enough room in pendingBuf.
  17194. */
  17195. function put_short (s, w) {
  17196. // put_byte(s, (uch)((w) & 0xff));
  17197. // put_byte(s, (uch)((ush)(w) >> 8));
  17198. s.pending_buf[s.pending++] = (w) & 0xff;
  17199. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  17200. }
  17201. /* ===========================================================================
  17202. * Send a value on a given number of bits.
  17203. * IN assertion: length <= 16 and value fits in length bits.
  17204. */
  17205. function send_bits(s, value, length) {
  17206. if (s.bi_valid > (Buf_size - length)) {
  17207. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17208. put_short(s, s.bi_buf);
  17209. s.bi_buf = value >> (Buf_size - s.bi_valid);
  17210. s.bi_valid += length - Buf_size;
  17211. } else {
  17212. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17213. s.bi_valid += length;
  17214. }
  17215. }
  17216. function send_code(s, c, tree) {
  17217. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  17218. }
  17219. /* ===========================================================================
  17220. * Reverse the first len bits of a code, using straightforward code (a faster
  17221. * method would use a table)
  17222. * IN assertion: 1 <= len <= 15
  17223. */
  17224. function bi_reverse(code, len) {
  17225. var res = 0;
  17226. do {
  17227. res |= code & 1;
  17228. code >>>= 1;
  17229. res <<= 1;
  17230. } while (--len > 0);
  17231. return res >>> 1;
  17232. }
  17233. /* ===========================================================================
  17234. * Flush the bit buffer, keeping at most 7 bits in it.
  17235. */
  17236. function bi_flush(s) {
  17237. if (s.bi_valid === 16) {
  17238. put_short(s, s.bi_buf);
  17239. s.bi_buf = 0;
  17240. s.bi_valid = 0;
  17241. } else if (s.bi_valid >= 8) {
  17242. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  17243. s.bi_buf >>= 8;
  17244. s.bi_valid -= 8;
  17245. }
  17246. }
  17247. /* ===========================================================================
  17248. * Compute the optimal bit lengths for a tree and update the total bit length
  17249. * for the current block.
  17250. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  17251. * above are the tree nodes sorted by increasing frequency.
  17252. * OUT assertions: the field len is set to the optimal bit length, the
  17253. * array bl_count contains the frequencies for each bit length.
  17254. * The length opt_len is updated; static_len is also updated if stree is
  17255. * not null.
  17256. */
  17257. function gen_bitlen(s, desc)
  17258. // deflate_state *s;
  17259. // tree_desc *desc; /* the tree descriptor */
  17260. {
  17261. var tree = desc.dyn_tree;
  17262. var max_code = desc.max_code;
  17263. var stree = desc.stat_desc.static_tree;
  17264. var has_stree = desc.stat_desc.has_stree;
  17265. var extra = desc.stat_desc.extra_bits;
  17266. var base = desc.stat_desc.extra_base;
  17267. var max_length = desc.stat_desc.max_length;
  17268. var h; /* heap index */
  17269. var n, m; /* iterate over the tree elements */
  17270. var bits; /* bit length */
  17271. var xbits; /* extra bits */
  17272. var f; /* frequency */
  17273. var overflow = 0; /* number of elements with bit length too large */
  17274. for (bits = 0; bits <= MAX_BITS; bits++) {
  17275. s.bl_count[bits] = 0;
  17276. }
  17277. /* In a first pass, compute the optimal bit lengths (which may
  17278. * overflow in the case of the bit length tree).
  17279. */
  17280. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  17281. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  17282. n = s.heap[h];
  17283. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  17284. if (bits > max_length) {
  17285. bits = max_length;
  17286. overflow++;
  17287. }
  17288. tree[n*2 + 1]/*.Len*/ = bits;
  17289. /* We overwrite tree[n].Dad which is no longer needed */
  17290. if (n > max_code) { continue; } /* not a leaf node */
  17291. s.bl_count[bits]++;
  17292. xbits = 0;
  17293. if (n >= base) {
  17294. xbits = extra[n-base];
  17295. }
  17296. f = tree[n * 2]/*.Freq*/;
  17297. s.opt_len += f * (bits + xbits);
  17298. if (has_stree) {
  17299. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  17300. }
  17301. }
  17302. if (overflow === 0) { return; }
  17303. // Trace((stderr,"\nbit length overflow\n"));
  17304. /* This happens for example on obj2 and pic of the Calgary corpus */
  17305. /* Find the first bit length which could increase: */
  17306. do {
  17307. bits = max_length-1;
  17308. while (s.bl_count[bits] === 0) { bits--; }
  17309. s.bl_count[bits]--; /* move one leaf down the tree */
  17310. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  17311. s.bl_count[max_length]--;
  17312. /* The brother of the overflow item also moves one step up,
  17313. * but this does not affect bl_count[max_length]
  17314. */
  17315. overflow -= 2;
  17316. } while (overflow > 0);
  17317. /* Now recompute all bit lengths, scanning in increasing frequency.
  17318. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  17319. * lengths instead of fixing only the wrong ones. This idea is taken
  17320. * from 'ar' written by Haruhiko Okumura.)
  17321. */
  17322. for (bits = max_length; bits !== 0; bits--) {
  17323. n = s.bl_count[bits];
  17324. while (n !== 0) {
  17325. m = s.heap[--h];
  17326. if (m > max_code) { continue; }
  17327. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  17328. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  17329. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  17330. tree[m*2 + 1]/*.Len*/ = bits;
  17331. }
  17332. n--;
  17333. }
  17334. }
  17335. }
  17336. /* ===========================================================================
  17337. * Generate the codes for a given tree and bit counts (which need not be
  17338. * optimal).
  17339. * IN assertion: the array bl_count contains the bit length statistics for
  17340. * the given tree and the field len is set for all tree elements.
  17341. * OUT assertion: the field code is set for all tree elements of non
  17342. * zero code length.
  17343. */
  17344. function gen_codes(tree, max_code, bl_count)
  17345. // ct_data *tree; /* the tree to decorate */
  17346. // int max_code; /* largest code with non zero frequency */
  17347. // ushf *bl_count; /* number of codes at each bit length */
  17348. {
  17349. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  17350. var code = 0; /* running code value */
  17351. var bits; /* bit index */
  17352. var n; /* code index */
  17353. /* The distribution counts are first used to generate the code values
  17354. * without bit reversal.
  17355. */
  17356. for (bits = 1; bits <= MAX_BITS; bits++) {
  17357. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  17358. }
  17359. /* Check that the bit counts in bl_count are consistent. The last code
  17360. * must be all ones.
  17361. */
  17362. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17363. // "inconsistent bit counts");
  17364. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17365. for (n = 0; n <= max_code; n++) {
  17366. var len = tree[n*2 + 1]/*.Len*/;
  17367. if (len === 0) { continue; }
  17368. /* Now reverse the bits */
  17369. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  17370. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  17371. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  17372. }
  17373. }
  17374. /* ===========================================================================
  17375. * Initialize the various 'constant' tables.
  17376. */
  17377. function tr_static_init() {
  17378. var n; /* iterates over tree elements */
  17379. var bits; /* bit counter */
  17380. var length; /* length value */
  17381. var code; /* code value */
  17382. var dist; /* distance index */
  17383. var bl_count = new Array(MAX_BITS+1);
  17384. /* number of codes at each bit length for an optimal tree */
  17385. // do check in _tr_init()
  17386. //if (static_init_done) return;
  17387. /* For some embedded targets, global variables are not initialized: */
  17388. /*#ifdef NO_INIT_GLOBAL_POINTERS
  17389. static_l_desc.static_tree = static_ltree;
  17390. static_l_desc.extra_bits = extra_lbits;
  17391. static_d_desc.static_tree = static_dtree;
  17392. static_d_desc.extra_bits = extra_dbits;
  17393. static_bl_desc.extra_bits = extra_blbits;
  17394. #endif*/
  17395. /* Initialize the mapping length (0..255) -> length code (0..28) */
  17396. length = 0;
  17397. for (code = 0; code < LENGTH_CODES-1; code++) {
  17398. base_length[code] = length;
  17399. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  17400. _length_code[length++] = code;
  17401. }
  17402. }
  17403. //Assert (length == 256, "tr_static_init: length != 256");
  17404. /* Note that the length 255 (match length 258) can be represented
  17405. * in two different ways: code 284 + 5 bits or code 285, so we
  17406. * overwrite length_code[255] to use the best encoding:
  17407. */
  17408. _length_code[length-1] = code;
  17409. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  17410. dist = 0;
  17411. for (code = 0 ; code < 16; code++) {
  17412. base_dist[code] = dist;
  17413. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  17414. _dist_code[dist++] = code;
  17415. }
  17416. }
  17417. //Assert (dist == 256, "tr_static_init: dist != 256");
  17418. dist >>= 7; /* from now on, all distances are divided by 128 */
  17419. for (; code < D_CODES; code++) {
  17420. base_dist[code] = dist << 7;
  17421. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  17422. _dist_code[256 + dist++] = code;
  17423. }
  17424. }
  17425. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  17426. /* Construct the codes of the static literal tree */
  17427. for (bits = 0; bits <= MAX_BITS; bits++) {
  17428. bl_count[bits] = 0;
  17429. }
  17430. n = 0;
  17431. while (n <= 143) {
  17432. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17433. n++;
  17434. bl_count[8]++;
  17435. }
  17436. while (n <= 255) {
  17437. static_ltree[n*2 + 1]/*.Len*/ = 9;
  17438. n++;
  17439. bl_count[9]++;
  17440. }
  17441. while (n <= 279) {
  17442. static_ltree[n*2 + 1]/*.Len*/ = 7;
  17443. n++;
  17444. bl_count[7]++;
  17445. }
  17446. while (n <= 287) {
  17447. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17448. n++;
  17449. bl_count[8]++;
  17450. }
  17451. /* Codes 286 and 287 do not exist, but we must include them in the
  17452. * tree construction to get a canonical Huffman tree (longest code
  17453. * all ones)
  17454. */
  17455. gen_codes(static_ltree, L_CODES+1, bl_count);
  17456. /* The static distance tree is trivial: */
  17457. for (n = 0; n < D_CODES; n++) {
  17458. static_dtree[n*2 + 1]/*.Len*/ = 5;
  17459. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  17460. }
  17461. // Now data ready and we can init static trees
  17462. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  17463. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  17464. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  17465. //static_init_done = true;
  17466. }
  17467. /* ===========================================================================
  17468. * Initialize a new block.
  17469. */
  17470. function init_block(s) {
  17471. var n; /* iterates over tree elements */
  17472. /* Initialize the trees. */
  17473. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  17474. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  17475. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  17476. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  17477. s.opt_len = s.static_len = 0;
  17478. s.last_lit = s.matches = 0;
  17479. }
  17480. /* ===========================================================================
  17481. * Flush the bit buffer and align the output on a byte boundary
  17482. */
  17483. function bi_windup(s)
  17484. {
  17485. if (s.bi_valid > 8) {
  17486. put_short(s, s.bi_buf);
  17487. } else if (s.bi_valid > 0) {
  17488. //put_byte(s, (Byte)s->bi_buf);
  17489. s.pending_buf[s.pending++] = s.bi_buf;
  17490. }
  17491. s.bi_buf = 0;
  17492. s.bi_valid = 0;
  17493. }
  17494. /* ===========================================================================
  17495. * Copy a stored block, storing first the length and its
  17496. * one's complement if requested.
  17497. */
  17498. function copy_block(s, buf, len, header)
  17499. //DeflateState *s;
  17500. //charf *buf; /* the input data */
  17501. //unsigned len; /* its length */
  17502. //int header; /* true if block header must be written */
  17503. {
  17504. bi_windup(s); /* align on byte boundary */
  17505. if (header) {
  17506. put_short(s, len);
  17507. put_short(s, ~len);
  17508. }
  17509. // while (len--) {
  17510. // put_byte(s, *buf++);
  17511. // }
  17512. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  17513. s.pending += len;
  17514. }
  17515. /* ===========================================================================
  17516. * Compares to subtrees, using the tree depth as tie breaker when
  17517. * the subtrees have equal frequency. This minimizes the worst case length.
  17518. */
  17519. function smaller(tree, n, m, depth) {
  17520. var _n2 = n*2;
  17521. var _m2 = m*2;
  17522. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  17523. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  17524. }
  17525. /* ===========================================================================
  17526. * Restore the heap property by moving down the tree starting at node k,
  17527. * exchanging a node with the smallest of its two sons if necessary, stopping
  17528. * when the heap property is re-established (each father smaller than its
  17529. * two sons).
  17530. */
  17531. function pqdownheap(s, tree, k)
  17532. // deflate_state *s;
  17533. // ct_data *tree; /* the tree to restore */
  17534. // int k; /* node to move down */
  17535. {
  17536. var v = s.heap[k];
  17537. var j = k << 1; /* left son of k */
  17538. while (j <= s.heap_len) {
  17539. /* Set j to the smallest of the two sons: */
  17540. if (j < s.heap_len &&
  17541. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  17542. j++;
  17543. }
  17544. /* Exit if v is smaller than both sons */
  17545. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  17546. /* Exchange v with the smallest son */
  17547. s.heap[k] = s.heap[j];
  17548. k = j;
  17549. /* And continue down the tree, setting j to the left son of k */
  17550. j <<= 1;
  17551. }
  17552. s.heap[k] = v;
  17553. }
  17554. // inlined manually
  17555. // var SMALLEST = 1;
  17556. /* ===========================================================================
  17557. * Send the block data compressed using the given Huffman trees
  17558. */
  17559. function compress_block(s, ltree, dtree)
  17560. // deflate_state *s;
  17561. // const ct_data *ltree; /* literal tree */
  17562. // const ct_data *dtree; /* distance tree */
  17563. {
  17564. var dist; /* distance of matched string */
  17565. var lc; /* match length or unmatched char (if dist == 0) */
  17566. var lx = 0; /* running index in l_buf */
  17567. var code; /* the code to send */
  17568. var extra; /* number of extra bits to send */
  17569. if (s.last_lit !== 0) {
  17570. do {
  17571. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  17572. lc = s.pending_buf[s.l_buf + lx];
  17573. lx++;
  17574. if (dist === 0) {
  17575. send_code(s, lc, ltree); /* send a literal byte */
  17576. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  17577. } else {
  17578. /* Here, lc is the match length - MIN_MATCH */
  17579. code = _length_code[lc];
  17580. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  17581. extra = extra_lbits[code];
  17582. if (extra !== 0) {
  17583. lc -= base_length[code];
  17584. send_bits(s, lc, extra); /* send the extra length bits */
  17585. }
  17586. dist--; /* dist is now the match distance - 1 */
  17587. code = d_code(dist);
  17588. //Assert (code < D_CODES, "bad d_code");
  17589. send_code(s, code, dtree); /* send the distance code */
  17590. extra = extra_dbits[code];
  17591. if (extra !== 0) {
  17592. dist -= base_dist[code];
  17593. send_bits(s, dist, extra); /* send the extra distance bits */
  17594. }
  17595. } /* literal or match pair ? */
  17596. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  17597. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  17598. // "pendingBuf overflow");
  17599. } while (lx < s.last_lit);
  17600. }
  17601. send_code(s, END_BLOCK, ltree);
  17602. }
  17603. /* ===========================================================================
  17604. * Construct one Huffman tree and assigns the code bit strings and lengths.
  17605. * Update the total bit length for the current block.
  17606. * IN assertion: the field freq is set for all tree elements.
  17607. * OUT assertions: the fields len and code are set to the optimal bit length
  17608. * and corresponding code. The length opt_len is updated; static_len is
  17609. * also updated if stree is not null. The field max_code is set.
  17610. */
  17611. function build_tree(s, desc)
  17612. // deflate_state *s;
  17613. // tree_desc *desc; /* the tree descriptor */
  17614. {
  17615. var tree = desc.dyn_tree;
  17616. var stree = desc.stat_desc.static_tree;
  17617. var has_stree = desc.stat_desc.has_stree;
  17618. var elems = desc.stat_desc.elems;
  17619. var n, m; /* iterate over heap elements */
  17620. var max_code = -1; /* largest code with non zero frequency */
  17621. var node; /* new node being created */
  17622. /* Construct the initial heap, with least frequent element in
  17623. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  17624. * heap[0] is not used.
  17625. */
  17626. s.heap_len = 0;
  17627. s.heap_max = HEAP_SIZE;
  17628. for (n = 0; n < elems; n++) {
  17629. if (tree[n * 2]/*.Freq*/ !== 0) {
  17630. s.heap[++s.heap_len] = max_code = n;
  17631. s.depth[n] = 0;
  17632. } else {
  17633. tree[n*2 + 1]/*.Len*/ = 0;
  17634. }
  17635. }
  17636. /* The pkzip format requires that at least one distance code exists,
  17637. * and that at least one bit should be sent even if there is only one
  17638. * possible code. So to avoid special checks later on we force at least
  17639. * two codes of non zero frequency.
  17640. */
  17641. while (s.heap_len < 2) {
  17642. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  17643. tree[node * 2]/*.Freq*/ = 1;
  17644. s.depth[node] = 0;
  17645. s.opt_len--;
  17646. if (has_stree) {
  17647. s.static_len -= stree[node*2 + 1]/*.Len*/;
  17648. }
  17649. /* node is 0 or 1 so it does not have extra bits */
  17650. }
  17651. desc.max_code = max_code;
  17652. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  17653. * establish sub-heaps of increasing lengths:
  17654. */
  17655. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  17656. /* Construct the Huffman tree by repeatedly combining the least two
  17657. * frequent nodes.
  17658. */
  17659. node = elems; /* next internal node of the tree */
  17660. do {
  17661. //pqremove(s, tree, n); /* n = node of least frequency */
  17662. /*** pqremove ***/
  17663. n = s.heap[1/*SMALLEST*/];
  17664. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  17665. pqdownheap(s, tree, 1/*SMALLEST*/);
  17666. /***/
  17667. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  17668. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  17669. s.heap[--s.heap_max] = m;
  17670. /* Create a new node father of n and m */
  17671. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  17672. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  17673. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  17674. /* and insert the new node in the heap */
  17675. s.heap[1/*SMALLEST*/] = node++;
  17676. pqdownheap(s, tree, 1/*SMALLEST*/);
  17677. } while (s.heap_len >= 2);
  17678. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  17679. /* At this point, the fields freq and dad are set. We can now
  17680. * generate the bit lengths.
  17681. */
  17682. gen_bitlen(s, desc);
  17683. /* The field len is now set, we can generate the bit codes */
  17684. gen_codes(tree, max_code, s.bl_count);
  17685. }
  17686. /* ===========================================================================
  17687. * Scan a literal or distance tree to determine the frequencies of the codes
  17688. * in the bit length tree.
  17689. */
  17690. function scan_tree(s, tree, max_code)
  17691. // deflate_state *s;
  17692. // ct_data *tree; /* the tree to be scanned */
  17693. // int max_code; /* and its largest code of non zero frequency */
  17694. {
  17695. var n; /* iterates over all tree elements */
  17696. var prevlen = -1; /* last emitted length */
  17697. var curlen; /* length of current code */
  17698. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17699. var count = 0; /* repeat count of the current code */
  17700. var max_count = 7; /* max repeat count */
  17701. var min_count = 4; /* min repeat count */
  17702. if (nextlen === 0) {
  17703. max_count = 138;
  17704. min_count = 3;
  17705. }
  17706. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  17707. for (n = 0; n <= max_code; n++) {
  17708. curlen = nextlen;
  17709. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17710. if (++count < max_count && curlen === nextlen) {
  17711. continue;
  17712. } else if (count < min_count) {
  17713. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  17714. } else if (curlen !== 0) {
  17715. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  17716. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  17717. } else if (count <= 10) {
  17718. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  17719. } else {
  17720. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  17721. }
  17722. count = 0;
  17723. prevlen = curlen;
  17724. if (nextlen === 0) {
  17725. max_count = 138;
  17726. min_count = 3;
  17727. } else if (curlen === nextlen) {
  17728. max_count = 6;
  17729. min_count = 3;
  17730. } else {
  17731. max_count = 7;
  17732. min_count = 4;
  17733. }
  17734. }
  17735. }
  17736. /* ===========================================================================
  17737. * Send a literal or distance tree in compressed form, using the codes in
  17738. * bl_tree.
  17739. */
  17740. function send_tree(s, tree, max_code)
  17741. // deflate_state *s;
  17742. // ct_data *tree; /* the tree to be scanned */
  17743. // int max_code; /* and its largest code of non zero frequency */
  17744. {
  17745. var n; /* iterates over all tree elements */
  17746. var prevlen = -1; /* last emitted length */
  17747. var curlen; /* length of current code */
  17748. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17749. var count = 0; /* repeat count of the current code */
  17750. var max_count = 7; /* max repeat count */
  17751. var min_count = 4; /* min repeat count */
  17752. /* tree[max_code+1].Len = -1; */ /* guard already set */
  17753. if (nextlen === 0) {
  17754. max_count = 138;
  17755. min_count = 3;
  17756. }
  17757. for (n = 0; n <= max_code; n++) {
  17758. curlen = nextlen;
  17759. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17760. if (++count < max_count && curlen === nextlen) {
  17761. continue;
  17762. } else if (count < min_count) {
  17763. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  17764. } else if (curlen !== 0) {
  17765. if (curlen !== prevlen) {
  17766. send_code(s, curlen, s.bl_tree);
  17767. count--;
  17768. }
  17769. //Assert(count >= 3 && count <= 6, " 3_6?");
  17770. send_code(s, REP_3_6, s.bl_tree);
  17771. send_bits(s, count-3, 2);
  17772. } else if (count <= 10) {
  17773. send_code(s, REPZ_3_10, s.bl_tree);
  17774. send_bits(s, count-3, 3);
  17775. } else {
  17776. send_code(s, REPZ_11_138, s.bl_tree);
  17777. send_bits(s, count-11, 7);
  17778. }
  17779. count = 0;
  17780. prevlen = curlen;
  17781. if (nextlen === 0) {
  17782. max_count = 138;
  17783. min_count = 3;
  17784. } else if (curlen === nextlen) {
  17785. max_count = 6;
  17786. min_count = 3;
  17787. } else {
  17788. max_count = 7;
  17789. min_count = 4;
  17790. }
  17791. }
  17792. }
  17793. /* ===========================================================================
  17794. * Construct the Huffman tree for the bit lengths and return the index in
  17795. * bl_order of the last bit length code to send.
  17796. */
  17797. function build_bl_tree(s) {
  17798. var max_blindex; /* index of last bit length code of non zero freq */
  17799. /* Determine the bit length frequencies for literal and distance trees */
  17800. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  17801. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  17802. /* Build the bit length tree: */
  17803. build_tree(s, s.bl_desc);
  17804. /* opt_len now includes the length of the tree representations, except
  17805. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  17806. */
  17807. /* Determine the number of bit length codes to send. The pkzip format
  17808. * requires that at least 4 bit length codes be sent. (appnote.txt says
  17809. * 3 but the actual value used is 4.)
  17810. */
  17811. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  17812. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  17813. break;
  17814. }
  17815. }
  17816. /* Update opt_len to include the bit length tree and counts */
  17817. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  17818. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  17819. // s->opt_len, s->static_len));
  17820. return max_blindex;
  17821. }
  17822. /* ===========================================================================
  17823. * Send the header for a block using dynamic Huffman trees: the counts, the
  17824. * lengths of the bit length codes, the literal tree and the distance tree.
  17825. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  17826. */
  17827. function send_all_trees(s, lcodes, dcodes, blcodes)
  17828. // deflate_state *s;
  17829. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  17830. {
  17831. var rank; /* index in bl_order */
  17832. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  17833. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  17834. // "too many codes");
  17835. //Tracev((stderr, "\nbl counts: "));
  17836. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  17837. send_bits(s, dcodes-1, 5);
  17838. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  17839. for (rank = 0; rank < blcodes; rank++) {
  17840. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  17841. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  17842. }
  17843. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  17844. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  17845. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  17846. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  17847. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  17848. }
  17849. /* ===========================================================================
  17850. * Check if the data type is TEXT or BINARY, using the following algorithm:
  17851. * - TEXT if the two conditions below are satisfied:
  17852. * a) There are no non-portable control characters belonging to the
  17853. * "black list" (0..6, 14..25, 28..31).
  17854. * b) There is at least one printable character belonging to the
  17855. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  17856. * - BINARY otherwise.
  17857. * - The following partially-portable control characters form a
  17858. * "gray list" that is ignored in this detection algorithm:
  17859. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  17860. * IN assertion: the fields Freq of dyn_ltree are set.
  17861. */
  17862. function detect_data_type(s) {
  17863. /* black_mask is the bit mask of black-listed bytes
  17864. * set bits 0..6, 14..25, and 28..31
  17865. * 0xf3ffc07f = binary 11110011111111111100000001111111
  17866. */
  17867. var black_mask = 0xf3ffc07f;
  17868. var n;
  17869. /* Check for non-textual ("black-listed") bytes. */
  17870. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  17871. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  17872. return Z_BINARY;
  17873. }
  17874. }
  17875. /* Check for textual ("white-listed") bytes. */
  17876. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  17877. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  17878. return Z_TEXT;
  17879. }
  17880. for (n = 32; n < LITERALS; n++) {
  17881. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  17882. return Z_TEXT;
  17883. }
  17884. }
  17885. /* There are no "black-listed" or "white-listed" bytes:
  17886. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  17887. */
  17888. return Z_BINARY;
  17889. }
  17890. var static_init_done = false;
  17891. /* ===========================================================================
  17892. * Initialize the tree data structures for a new zlib stream.
  17893. */
  17894. function _tr_init(s)
  17895. {
  17896. if (!static_init_done) {
  17897. tr_static_init();
  17898. static_init_done = true;
  17899. }
  17900. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  17901. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  17902. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  17903. s.bi_buf = 0;
  17904. s.bi_valid = 0;
  17905. /* Initialize the first block of the first file: */
  17906. init_block(s);
  17907. }
  17908. /* ===========================================================================
  17909. * Send a stored block
  17910. */
  17911. function _tr_stored_block(s, buf, stored_len, last)
  17912. //DeflateState *s;
  17913. //charf *buf; /* input block */
  17914. //ulg stored_len; /* length of input block */
  17915. //int last; /* one if this is the last block for a file */
  17916. {
  17917. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  17918. copy_block(s, buf, stored_len, true); /* with header */
  17919. }
  17920. /* ===========================================================================
  17921. * Send one empty static block to give enough lookahead for inflate.
  17922. * This takes 10 bits, of which 7 may remain in the bit buffer.
  17923. */
  17924. function _tr_align(s) {
  17925. send_bits(s, STATIC_TREES<<1, 3);
  17926. send_code(s, END_BLOCK, static_ltree);
  17927. bi_flush(s);
  17928. }
  17929. /* ===========================================================================
  17930. * Determine the best encoding for the current block: dynamic trees, static
  17931. * trees or store, and output the encoded block to the zip file.
  17932. */
  17933. function _tr_flush_block(s, buf, stored_len, last)
  17934. //DeflateState *s;
  17935. //charf *buf; /* input block, or NULL if too old */
  17936. //ulg stored_len; /* length of input block */
  17937. //int last; /* one if this is the last block for a file */
  17938. {
  17939. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  17940. var max_blindex = 0; /* index of last bit length code of non zero freq */
  17941. /* Build the Huffman trees unless a stored block is forced */
  17942. if (s.level > 0) {
  17943. /* Check if the file is binary or text */
  17944. if (s.strm.data_type === Z_UNKNOWN) {
  17945. s.strm.data_type = detect_data_type(s);
  17946. }
  17947. /* Construct the literal and distance trees */
  17948. build_tree(s, s.l_desc);
  17949. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  17950. // s->static_len));
  17951. build_tree(s, s.d_desc);
  17952. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  17953. // s->static_len));
  17954. /* At this point, opt_len and static_len are the total bit lengths of
  17955. * the compressed block data, excluding the tree representations.
  17956. */
  17957. /* Build the bit length tree for the above two trees, and get the index
  17958. * in bl_order of the last bit length code to send.
  17959. */
  17960. max_blindex = build_bl_tree(s);
  17961. /* Determine the best encoding. Compute the block lengths in bytes. */
  17962. opt_lenb = (s.opt_len+3+7) >>> 3;
  17963. static_lenb = (s.static_len+3+7) >>> 3;
  17964. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  17965. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  17966. // s->last_lit));
  17967. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  17968. } else {
  17969. // Assert(buf != (char*)0, "lost buf");
  17970. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  17971. }
  17972. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  17973. /* 4: two words for the lengths */
  17974. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  17975. * Otherwise we can't have processed more than WSIZE input bytes since
  17976. * the last block flush, because compression would have been
  17977. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  17978. * transform a block into a stored block.
  17979. */
  17980. _tr_stored_block(s, buf, stored_len, last);
  17981. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  17982. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  17983. compress_block(s, static_ltree, static_dtree);
  17984. } else {
  17985. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  17986. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  17987. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  17988. }
  17989. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  17990. /* The above check is made mod 2^32, for files larger than 512 MB
  17991. * and uLong implemented on 32 bits.
  17992. */
  17993. init_block(s);
  17994. if (last) {
  17995. bi_windup(s);
  17996. }
  17997. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  17998. // s->compressed_len-7*last));
  17999. }
  18000. /* ===========================================================================
  18001. * Save the match info and tally the frequency counts. Return true if
  18002. * the current block must be flushed.
  18003. */
  18004. function _tr_tally(s, dist, lc)
  18005. // deflate_state *s;
  18006. // unsigned dist; /* distance of matched string */
  18007. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18008. {
  18009. //var out_length, in_length, dcode;
  18010. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18011. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18012. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18013. s.last_lit++;
  18014. if (dist === 0) {
  18015. /* lc is the unmatched char */
  18016. s.dyn_ltree[lc*2]/*.Freq*/++;
  18017. } else {
  18018. s.matches++;
  18019. /* Here, lc is the match length - MIN_MATCH */
  18020. dist--; /* dist = match distance - 1 */
  18021. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18022. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18023. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18024. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18025. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18026. }
  18027. // (!) This block is disabled in zlib defailts,
  18028. // don't enable it for binary compatibility
  18029. //#ifdef TRUNCATE_BLOCK
  18030. // /* Try to guess if it is profitable to stop the current block here */
  18031. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18032. // /* Compute an upper bound for the compressed length */
  18033. // out_length = s.last_lit*8;
  18034. // in_length = s.strstart - s.block_start;
  18035. //
  18036. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18037. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18038. // }
  18039. // out_length >>>= 3;
  18040. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18041. // // s->last_lit, in_length, out_length,
  18042. // // 100L - out_length*100L/in_length));
  18043. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18044. // return true;
  18045. // }
  18046. // }
  18047. //#endif
  18048. return (s.last_lit === s.lit_bufsize-1);
  18049. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18050. * on 16 bit machines and because stored blocks are restricted to
  18051. * 64K-1 bytes.
  18052. */
  18053. }
  18054. exports._tr_init = _tr_init;
  18055. exports._tr_stored_block = _tr_stored_block;
  18056. exports._tr_flush_block = _tr_flush_block;
  18057. exports._tr_tally = _tr_tally;
  18058. exports._tr_align = _tr_align;
  18059. },{"../utils/common":51}],63:[function(require,module,exports){
  18060. 'use strict';
  18061. function ZStream() {
  18062. /* next input byte */
  18063. this.input = null; // JS specific, because we have no pointers
  18064. this.next_in = 0;
  18065. /* number of bytes available at input */
  18066. this.avail_in = 0;
  18067. /* total number of input bytes read so far */
  18068. this.total_in = 0;
  18069. /* next output byte should be put there */
  18070. this.output = null; // JS specific, because we have no pointers
  18071. this.next_out = 0;
  18072. /* remaining free space at output */
  18073. this.avail_out = 0;
  18074. /* total number of bytes output so far */
  18075. this.total_out = 0;
  18076. /* last error message, NULL if no error */
  18077. this.msg = ''/*Z_NULL*/;
  18078. /* not visible by applications */
  18079. this.state = null;
  18080. /* best guess about the data type: binary or text */
  18081. this.data_type = 2/*Z_UNKNOWN*/;
  18082. /* adler32 value of the uncompressed data */
  18083. this.adler = 0;
  18084. }
  18085. module.exports = ZStream;
  18086. },{}],64:[function(require,module,exports){
  18087. /* Copyright @ 2015 Atlassian Pty Ltd
  18088. *
  18089. * Licensed under the Apache License, Version 2.0 (the "License");
  18090. * you may not use this file except in compliance with the License.
  18091. * You may obtain a copy of the License at
  18092. *
  18093. * http://www.apache.org/licenses/LICENSE-2.0
  18094. *
  18095. * Unless required by applicable law or agreed to in writing, software
  18096. * distributed under the License is distributed on an "AS IS" BASIS,
  18097. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18098. * See the License for the specific language governing permissions and
  18099. * limitations under the License.
  18100. */
  18101. module.exports = function arrayEquals(array) {
  18102. // if the other array is a falsy value, return
  18103. if (!array)
  18104. return false;
  18105. // compare lengths - can save a lot of time
  18106. if (this.length != array.length)
  18107. return false;
  18108. for (var i = 0, l = this.length; i < l; i++) {
  18109. // Check if we have nested arrays
  18110. if (this[i] instanceof Array && array[i] instanceof Array) {
  18111. // recurse into the nested arrays
  18112. if (!arrayEquals.apply(this[i], [array[i]]))
  18113. return false;
  18114. } else if (this[i] != array[i]) {
  18115. // Warning - two different object instances will never be equal:
  18116. // {x:20} != {x:20}
  18117. return false;
  18118. }
  18119. }
  18120. return true;
  18121. };
  18122. },{}],65:[function(require,module,exports){
  18123. /* Copyright @ 2015 Atlassian Pty Ltd
  18124. *
  18125. * Licensed under the Apache License, Version 2.0 (the "License");
  18126. * you may not use this file except in compliance with the License.
  18127. * You may obtain a copy of the License at
  18128. *
  18129. * http://www.apache.org/licenses/LICENSE-2.0
  18130. *
  18131. * Unless required by applicable law or agreed to in writing, software
  18132. * distributed under the License is distributed on an "AS IS" BASIS,
  18133. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18134. * See the License for the specific language governing permissions and
  18135. * limitations under the License.
  18136. */
  18137. exports.Interop = require('./interop');
  18138. },{"./interop":66}],66:[function(require,module,exports){
  18139. /* Copyright @ 2015 Atlassian Pty Ltd
  18140. *
  18141. * Licensed under the Apache License, Version 2.0 (the "License");
  18142. * you may not use this file except in compliance with the License.
  18143. * You may obtain a copy of the License at
  18144. *
  18145. * http://www.apache.org/licenses/LICENSE-2.0
  18146. *
  18147. * Unless required by applicable law or agreed to in writing, software
  18148. * distributed under the License is distributed on an "AS IS" BASIS,
  18149. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18150. * See the License for the specific language governing permissions and
  18151. * limitations under the License.
  18152. */
  18153. /* global RTCSessionDescription */
  18154. /* jshint -W097 */
  18155. "use strict";
  18156. var transform = require('./transform');
  18157. var arrayEquals = require('./array-equals');
  18158. function Interop() {
  18159. /**
  18160. * This map holds the most recent Unified Plan offer/answer SDP that was
  18161. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  18162. * the SDP string as values.
  18163. *
  18164. * @type {{}}
  18165. */
  18166. this.cache = {};
  18167. }
  18168. module.exports = Interop;
  18169. /**
  18170. * Returns the index of the first m-line with the given media type and with a
  18171. * direction which allows sending, in the last Unified Plan description with
  18172. * type "answer" converted to Plan B. Returns {null} if there is no saved
  18173. * answer, or if none of its m-lines with the given type allow sending.
  18174. * @param type the media type ("audio" or "video").
  18175. * @returns {*}
  18176. */
  18177. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  18178. if (!this.cache.answer) {
  18179. return null;
  18180. }
  18181. var session = transform.parse(this.cache.answer);
  18182. if (session && session.media && Array.isArray(session.media)){
  18183. for (var i = 0; i < session.media.length; i++) {
  18184. if (session.media[i].type == type &&
  18185. (!session.media[i].direction /* default to sendrecv */ ||
  18186. session.media[i].direction === 'sendrecv' ||
  18187. session.media[i].direction === 'sendonly')){
  18188. return i;
  18189. }
  18190. }
  18191. }
  18192. return null;
  18193. };
  18194. /**
  18195. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  18196. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  18197. * application.
  18198. *
  18199. * @param desc
  18200. * @returns {*}
  18201. */
  18202. Interop.prototype.toPlanB = function(desc) {
  18203. var self = this;
  18204. //#region Preliminary input validation.
  18205. if (typeof desc !== 'object' || desc === null ||
  18206. typeof desc.sdp !== 'string') {
  18207. console.warn('An empty description was passed as an argument.');
  18208. return desc;
  18209. }
  18210. // Objectify the SDP for easier manipulation.
  18211. var session = transform.parse(desc.sdp);
  18212. // If the SDP contains no media, there's nothing to transform.
  18213. if (typeof session.media === 'undefined' ||
  18214. !Array.isArray(session.media) || session.media.length === 0) {
  18215. console.warn('The description has no media.');
  18216. return desc;
  18217. }
  18218. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  18219. // SDP has a video, an audio and a data "channel" at most.
  18220. if (session.media.length <= 3 && session.media.every(function(m) {
  18221. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18222. })) {
  18223. console.warn('This description does not look like Unified Plan.');
  18224. return desc;
  18225. }
  18226. //#endregion
  18227. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  18228. var sdp = desc.sdp;
  18229. var rewrite = false;
  18230. for (var i = 0; i < session.media.length; i++) {
  18231. var uLine = session.media[i];
  18232. uLine.rtp.forEach(function(rtp) {
  18233. if (rtp.codec === 'NULL')
  18234. {
  18235. rewrite = true;
  18236. var offer = transform.parse(self.cache['offer']);
  18237. rtp.codec = offer.media[i].rtp[0].codec;
  18238. }
  18239. });
  18240. };
  18241. if (rewrite) {
  18242. sdp = transform.write(session);
  18243. }
  18244. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  18245. // -> Unified Plan transformation.
  18246. this.cache[desc.type] = sdp;
  18247. //#region Convert from Unified Plan to Plan B.
  18248. // We rebuild the session.media array.
  18249. var media = session.media;
  18250. session.media = [];
  18251. // Associative array that maps channel types to channel objects for fast
  18252. // access to channel objects by their type, e.g. type2bl['audio']->channel
  18253. // obj.
  18254. var type2bl = {};
  18255. // Used to build the group:BUNDLE value after the channels construction
  18256. // loop.
  18257. var types = [];
  18258. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  18259. media.forEach(function(uLine) {
  18260. // rtcp-mux is required in the Plan B SDP.
  18261. if ((typeof uLine.rtcpMux !== 'string' ||
  18262. uLine.rtcpMux !== 'rtcp-mux') &&
  18263. uLine.direction !== 'inactive') {
  18264. throw new Error('Cannot convert to Plan B because m-lines ' +
  18265. 'without the rtcp-mux attribute were found.');
  18266. }
  18267. if (uLine.type === 'application') {
  18268. session.media.push(uLine);
  18269. types.push(uLine.mid);
  18270. return;
  18271. }
  18272. // If we don't have a channel for this uLine.type, then use this
  18273. // uLine as the channel basis.
  18274. if (typeof type2bl[uLine.type] === 'undefined') {
  18275. type2bl[uLine.type] = uLine;
  18276. }
  18277. // Add sources to the channel and handle a=msid.
  18278. if (typeof uLine.sources === 'object') {
  18279. Object.keys(uLine.sources).forEach(function(ssrc) {
  18280. if (typeof type2bl[uLine.type].sources !== 'object')
  18281. type2bl[uLine.type].sources = {};
  18282. // Assign the sources to the channel.
  18283. type2bl[uLine.type].sources[ssrc] =
  18284. uLine.sources[ssrc];
  18285. if (typeof uLine.msid !== 'undefined') {
  18286. // In Plan B the msid is an SSRC attribute. Also, we don't
  18287. // care about the obsolete label and mslabel attributes.
  18288. //
  18289. // Note that it is not guaranteed that the uLine will
  18290. // have an msid. recvonly channels in particular don't have
  18291. // one.
  18292. type2bl[uLine.type].sources[ssrc].msid =
  18293. uLine.msid;
  18294. }
  18295. // NOTE ssrcs in ssrc groups will share msids, as
  18296. // draft-uberti-rtcweb-plan-00 mandates.
  18297. });
  18298. }
  18299. // Add ssrc groups to the channel.
  18300. if (typeof uLine.ssrcGroups !== 'undefined' &&
  18301. Array.isArray(uLine.ssrcGroups)) {
  18302. // Create the ssrcGroups array, if it's not defined.
  18303. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  18304. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  18305. type2bl[uLine.type].ssrcGroups = [];
  18306. }
  18307. type2bl[uLine.type].ssrcGroups =
  18308. type2bl[uLine.type].ssrcGroups.concat(
  18309. uLine.ssrcGroups);
  18310. }
  18311. if (type2bl[uLine.type] === uLine) {
  18312. // Copy ICE related stuff from the principal media line.
  18313. uLine.candidates = media[0].candidates;
  18314. uLine.iceUfrag = media[0].iceUfrag;
  18315. uLine.icePwd = media[0].icePwd;
  18316. uLine.fingerprint = media[0].fingerprint;
  18317. // Plan B mids are in ['audio', 'video', 'data']
  18318. uLine.mid = uLine.type;
  18319. // Plan B doesn't support/need the bundle-only attribute.
  18320. delete uLine.bundleOnly;
  18321. // In Plan B the msid is an SSRC attribute.
  18322. delete uLine.msid;
  18323. // Used to build the group:BUNDLE value after this loop.
  18324. types.push(uLine.type);
  18325. // Add the channel to the new media array.
  18326. session.media.push(uLine);
  18327. }
  18328. });
  18329. // We regenerate the BUNDLE group with the new mids.
  18330. session.groups.some(function(group) {
  18331. if (group.type === 'BUNDLE') {
  18332. group.mids = types.join(' ');
  18333. return true;
  18334. }
  18335. });
  18336. // msid semantic
  18337. session.msidSemantic = {
  18338. semantic: 'WMS',
  18339. token: '*'
  18340. };
  18341. var resStr = transform.write(session);
  18342. return new RTCSessionDescription({
  18343. type: desc.type,
  18344. sdp: resStr
  18345. });
  18346. //#endregion
  18347. };
  18348. /**
  18349. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  18350. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  18351. * to FF.
  18352. *
  18353. * @param desc
  18354. * @returns {*}
  18355. */
  18356. Interop.prototype.toUnifiedPlan = function(desc) {
  18357. var self = this;
  18358. //#region Preliminary input validation.
  18359. if (typeof desc !== 'object' || desc === null ||
  18360. typeof desc.sdp !== 'string') {
  18361. console.warn('An empty description was passed as an argument.');
  18362. return desc;
  18363. }
  18364. var session = transform.parse(desc.sdp);
  18365. // If the SDP contains no media, there's nothing to transform.
  18366. if (typeof session.media === 'undefined' ||
  18367. !Array.isArray(session.media) || session.media.length === 0) {
  18368. console.warn('The description has no media.');
  18369. return desc;
  18370. }
  18371. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  18372. // a video, an audio and a data "channel" at most.
  18373. if (session.media.length > 3 || !session.media.every(function(m) {
  18374. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18375. })) {
  18376. console.warn('This description does not look like Plan B.');
  18377. return desc;
  18378. }
  18379. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  18380. var mids = [];
  18381. session.media.forEach(function(m) {
  18382. mids.push(m.mid);
  18383. });
  18384. var hasBundle = false;
  18385. if (typeof session.groups !== 'undefined' &&
  18386. Array.isArray(session.groups)) {
  18387. hasBundle = session.groups.every(function(g) {
  18388. return g.type !== 'BUNDLE' ||
  18389. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  18390. });
  18391. }
  18392. if (!hasBundle) {
  18393. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  18394. " are not bundled were found.");
  18395. }
  18396. //#endregion
  18397. //#region Convert from Plan B to Unified Plan.
  18398. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  18399. // rebuild an equivalent Unified Plan offer/answer.
  18400. //
  18401. // For example, if this is a local answer (in Unified Plan style) that we
  18402. // convert to Plan B prior to handing it over to the application (the
  18403. // PeerConnection wrapper called us, for instance, after a successful
  18404. // createAnswer), we want to remember the m-line at which we've seen the
  18405. // (local) SSRC. That's because when the application wants to do call the
  18406. // SLD method, forcing us to do the inverse transformation (from Plan B to
  18407. // Unified Plan), we need to know to which m-line to assign the (local)
  18408. // SSRC. We also need to know all the other m-lines that the original
  18409. // answer had and include them in the transformed answer as well.
  18410. //
  18411. // Another example is if this is a remote offer that we convert to Plan B
  18412. // prior to giving it to the application, we want to remember the mid at
  18413. // which we've seen the (remote) SSRC.
  18414. //
  18415. // In the iteration that follows, we use the cached Unified Plan (if it
  18416. // exists) to assign mids to ssrcs.
  18417. var cached;
  18418. if (typeof this.cache[desc.type] !== 'undefined') {
  18419. cached = transform.parse(this.cache[desc.type]);
  18420. }
  18421. var recvonlySsrcs = {
  18422. audio: {},
  18423. video: {}
  18424. };
  18425. // A helper map that sends mids to m-line objects. We use it later to
  18426. // rebuild the Unified Plan style session.media array.
  18427. var mid2ul = {};
  18428. session.media.forEach(function(bLine) {
  18429. if ((typeof bLine.rtcpMux !== 'string' ||
  18430. bLine.rtcpMux !== 'rtcp-mux') &&
  18431. bLine.direction !== 'inactive') {
  18432. throw new Error("Cannot convert to Unified Plan because m-lines " +
  18433. "without the rtcp-mux attribute were found.");
  18434. }
  18435. if (bLine.type === 'application') {
  18436. mid2ul[bLine.mid] = bLine;
  18437. return;
  18438. }
  18439. // With rtcp-mux and bundle all the channels should have the same ICE
  18440. // stuff.
  18441. var sources = bLine.sources;
  18442. var ssrcGroups = bLine.ssrcGroups;
  18443. var candidates = bLine.candidates;
  18444. var iceUfrag = bLine.iceUfrag;
  18445. var icePwd = bLine.icePwd;
  18446. var fingerprint = bLine.fingerprint;
  18447. var port = bLine.port;
  18448. // We'll use the "bLine" object as a prototype for each new "mLine"
  18449. // that we create, but first we need to clean it up a bit.
  18450. delete bLine.sources;
  18451. delete bLine.ssrcGroups;
  18452. delete bLine.candidates;
  18453. delete bLine.iceUfrag;
  18454. delete bLine.icePwd;
  18455. delete bLine.fingerprint;
  18456. delete bLine.port;
  18457. delete bLine.mid;
  18458. // inverted ssrc group map
  18459. var ssrc2group = {};
  18460. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  18461. ssrcGroups.forEach(function (ssrcGroup) {
  18462. // TODO(gp) find out how to receive simulcast with FF. For the
  18463. // time being, hide it.
  18464. if (ssrcGroup.semantics === 'SIM') {
  18465. return;
  18466. }
  18467. // XXX This might brake if an SSRC is in more than one group
  18468. // for some reason.
  18469. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18470. Array.isArray(ssrcGroup.ssrcs)) {
  18471. ssrcGroup.ssrcs.forEach(function (ssrc) {
  18472. if (typeof ssrc2group[ssrc] === 'undefined') {
  18473. ssrc2group[ssrc] = [];
  18474. }
  18475. ssrc2group[ssrc].push(ssrcGroup);
  18476. });
  18477. }
  18478. });
  18479. }
  18480. // ssrc to m-line index.
  18481. var ssrc2ml = {};
  18482. if (typeof sources === 'object') {
  18483. // Explode the Plan B channel sources with one m-line per source.
  18484. Object.keys(sources).forEach(function(ssrc) {
  18485. // The (unified) m-line for this SSRC. We either create it from
  18486. // scratch or, if it's a grouped SSRC, we re-use a related
  18487. // mline. In other words, if the source is grouped with another
  18488. // source, put the two together in the same m-line.
  18489. var uLine;
  18490. // We assume here that we are the answerer in the O/A, so any
  18491. // offers which we translate come from the remote side, while
  18492. // answers are local. So the check below is to make that we
  18493. // handle receive-only SSRCs in a special way only if they come
  18494. // from the remote side.
  18495. if (desc.type==='offer') {
  18496. // We want to detect SSRCs which are used by a remote peer
  18497. // in an m-line with direction=recvonly (i.e. they are
  18498. // being used for RTCP only).
  18499. // This information would have gotten lost if the remote
  18500. // peer used Unified Plan and their local description was
  18501. // translated to Plan B. So we use the lack of an MSID
  18502. // attribute to deduce a "receive only" SSRC.
  18503. if (!sources[ssrc].msid) {
  18504. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  18505. // Receive-only SSRCs must not create new m-lines. We
  18506. // will assign them to an existing m-line later.
  18507. return;
  18508. }
  18509. }
  18510. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  18511. Array.isArray(ssrc2group[ssrc])) {
  18512. ssrc2group[ssrc].some(function (ssrcGroup) {
  18513. // ssrcGroup.ssrcs *is* an Array, no need to check
  18514. // again here.
  18515. return ssrcGroup.ssrcs.some(function (related) {
  18516. if (typeof ssrc2ml[related] === 'object') {
  18517. uLine = ssrc2ml[related];
  18518. return true;
  18519. }
  18520. });
  18521. });
  18522. }
  18523. if (typeof uLine === 'object') {
  18524. // the m-line already exists. Just add the source.
  18525. uLine.sources[ssrc] = sources[ssrc];
  18526. delete sources[ssrc].msid;
  18527. } else {
  18528. // Use the "bLine" as a prototype for the "uLine".
  18529. uLine = Object.create(bLine);
  18530. ssrc2ml[ssrc] = uLine;
  18531. if (typeof sources[ssrc].msid !== 'undefined') {
  18532. // Assign the msid of the source to the m-line. Note
  18533. // that it is not guaranteed that the source will have
  18534. // msid. In particular "recvonly" sources don't have an
  18535. // msid. Note that "recvonly" is a term only defined
  18536. // for m-lines.
  18537. uLine.msid = sources[ssrc].msid;
  18538. uLine.direction = 'sendrecv';
  18539. delete sources[ssrc].msid;
  18540. }
  18541. // We assign one SSRC per media line.
  18542. uLine.sources = {};
  18543. uLine.sources[ssrc] = sources[ssrc];
  18544. uLine.ssrcGroups = ssrc2group[ssrc];
  18545. // Use the cached Unified Plan SDP (if it exists) to assign
  18546. // SSRCs to mids.
  18547. if (typeof cached !== 'undefined' &&
  18548. typeof cached.media !== 'undefined' &&
  18549. Array.isArray(cached.media)) {
  18550. cached.media.forEach(function (m) {
  18551. if (typeof m.sources === 'object') {
  18552. Object.keys(m.sources).forEach(function (s) {
  18553. if (s === ssrc) {
  18554. uLine.mid = m.mid;
  18555. }
  18556. });
  18557. }
  18558. });
  18559. }
  18560. if (typeof uLine.mid === 'undefined') {
  18561. // If this is an SSRC that we see for the first time
  18562. // assign it a new mid. This is typically the case when
  18563. // this method is called to transform a remote
  18564. // description for the first time or when there is a
  18565. // new SSRC in the remote description because a new
  18566. // peer has joined the conference. Local SSRCs should
  18567. // have already been added to the map in the toPlanB
  18568. // method.
  18569. //
  18570. // Because FF generates answers in Unified Plan style,
  18571. // we MUST already have a cached answer with all the
  18572. // local SSRCs mapped to some m-line/mid.
  18573. if (desc.type === 'answer') {
  18574. throw new Error("An unmapped SSRC was found.");
  18575. }
  18576. uLine.mid = [bLine.type, '-', ssrc].join('');
  18577. }
  18578. // Include the candidates in the 1st media line.
  18579. uLine.candidates = candidates;
  18580. uLine.iceUfrag = iceUfrag;
  18581. uLine.icePwd = icePwd;
  18582. uLine.fingerprint = fingerprint;
  18583. uLine.port = port;
  18584. mid2ul[uLine.mid] = uLine;
  18585. }
  18586. });
  18587. }
  18588. });
  18589. // Rebuild the media array in the right order and add the missing mLines
  18590. // (missing from the Plan B SDP).
  18591. session.media = [];
  18592. mids = []; // reuse
  18593. if (desc.type === 'answer') {
  18594. // The media lines in the answer must match the media lines in the
  18595. // offer. The order is important too. Here we assume that Firefox is
  18596. // the answerer, so we merely have to use the reconstructed (unified)
  18597. // answer to update the cached (unified) answer accordingly.
  18598. //
  18599. // In the general case, one would have to use the cached (unified)
  18600. // offer to find the m-lines that are missing from the reconstructed
  18601. // answer, potentially grabbing them from the cached (unified) answer.
  18602. // One has to be careful with this approach because inactive m-lines do
  18603. // not always have an mid, making it tricky (impossible?) to find where
  18604. // exactly and which m-lines are missing from the reconstructed answer.
  18605. for (var i = 0; i < cached.media.length; i++) {
  18606. var uLine = cached.media[i];
  18607. if (typeof mid2ul[uLine.mid] === 'undefined') {
  18608. // The mid isn't in the reconstructed (unified) answer.
  18609. // This is either a (unified) m-line containing a remote
  18610. // track only, or a (unified) m-line containing a remote
  18611. // track and a local track that has been removed.
  18612. // In either case, it MUST exist in the cached
  18613. // (unified) answer.
  18614. //
  18615. // In case this is a removed local track, clean-up
  18616. // the (unified) m-line and make sure it's 'recvonly' or
  18617. // 'inactive'.
  18618. delete uLine.msid;
  18619. delete uLine.sources;
  18620. delete uLine.ssrcGroups;
  18621. if (!uLine.direction
  18622. || uLine.direction === 'sendrecv')
  18623. uLine.direction = 'recvonly';
  18624. else if (uLine.direction === 'sendonly')
  18625. uLine.direction = 'inactive';
  18626. } else {
  18627. // This is an (unified) m-line/channel that contains a local
  18628. // track (sendrecv or sendonly channel) or it's a unified
  18629. // recvonly m-line/channel. In either case, since we're
  18630. // going from PlanB -> Unified Plan this m-line MUST
  18631. // exist in the cached answer.
  18632. }
  18633. session.media.push(uLine);
  18634. if (typeof uLine.mid === 'string') {
  18635. // inactive lines don't/may not have an mid.
  18636. mids.push(uLine.mid);
  18637. }
  18638. }
  18639. } else {
  18640. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  18641. // under any circumstances. If we are no longer interested in sending a
  18642. // track, we just remove the msid and ssrc attributes and set it to
  18643. // either a=recvonly (as the reofferer, we must use recvonly if the
  18644. // other side was previously sending on the m-section, but we can also
  18645. // leave the possibility open if it wasn't previously in use), or
  18646. // a=inactive.
  18647. if (typeof cached !== 'undefined' &&
  18648. typeof cached.media !== 'undefined' &&
  18649. Array.isArray(cached.media)) {
  18650. cached.media.forEach(function(uLine) {
  18651. mids.push(uLine.mid);
  18652. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  18653. session.media.push(mid2ul[uLine.mid]);
  18654. } else {
  18655. delete uLine.msid;
  18656. delete uLine.sources;
  18657. delete uLine.ssrcGroups;
  18658. if (!uLine.direction
  18659. || uLine.direction === 'sendrecv')
  18660. uLine.direction = 'recvonly';
  18661. if (!uLine.direction
  18662. || uLine.direction === 'sendonly')
  18663. uLine.direction = 'inactive';
  18664. session.media.push(uLine);
  18665. }
  18666. });
  18667. }
  18668. // Add all the remaining (new) m-lines of the transformed SDP.
  18669. Object.keys(mid2ul).forEach(function(mid) {
  18670. if (mids.indexOf(mid) === -1) {
  18671. mids.push(mid);
  18672. if (mid2ul[mid].direction === 'recvonly') {
  18673. // This is a remote recvonly channel. Add its SSRC to the
  18674. // appropriate sendrecv or sendonly channel.
  18675. // TODO(gp) what if we don't have sendrecv/sendonly
  18676. // channel?
  18677. session.media.some(function (uLine) {
  18678. if ((uLine.direction === 'sendrecv' ||
  18679. uLine.direction === 'sendonly') &&
  18680. uLine.type === mid2ul[mid].type) {
  18681. // mid2ul[mid] shouldn't have any ssrc-groups
  18682. Object.keys(mid2ul[mid].sources).forEach(
  18683. function (ssrc) {
  18684. uLine.sources[ssrc] =
  18685. mid2ul[mid].sources[ssrc];
  18686. });
  18687. return true;
  18688. }
  18689. });
  18690. } else {
  18691. session.media.push(mid2ul[mid]);
  18692. }
  18693. }
  18694. });
  18695. }
  18696. // After we have constructed the Plan Unified m-lines we can figure out
  18697. // where (in which m-line) to place the 'recvonly SSRCs'.
  18698. // Note: we assume here that we are the answerer in the O/A, so any offers
  18699. // which we translate come from the remote side, while answers are local
  18700. // (and so our last local description is cached as an 'answer').
  18701. ["audio", "video"].forEach(function (type) {
  18702. if (!session || !session.media || !Array.isArray(session.media))
  18703. return;
  18704. var idx = null;
  18705. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  18706. idx = self.getFirstSendingIndexFromAnswer(type);
  18707. if (idx === null){
  18708. // If this is the first offer we receive, we don't have a
  18709. // cached answer. Assume that we will be sending media using
  18710. // the first m-line for each media type.
  18711. for (var i = 0; i < session.media.length; i++) {
  18712. if (session.media[i].type === type) {
  18713. idx = i;
  18714. break;
  18715. }
  18716. }
  18717. }
  18718. }
  18719. if (idx && session.media.length > idx) {
  18720. var mLine = session.media[idx];
  18721. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  18722. if (mLine.sources && mLine.sources[ssrc]) {
  18723. console.warn("Replacing an existing SSRC.");
  18724. }
  18725. if (!mLine.sources) {
  18726. mLine.sources = {};
  18727. }
  18728. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  18729. });
  18730. }
  18731. });
  18732. // We regenerate the BUNDLE group (since we regenerated the mids)
  18733. session.groups.some(function(group) {
  18734. if (group.type === 'BUNDLE') {
  18735. group.mids = mids.join(' ');
  18736. return true;
  18737. }
  18738. });
  18739. // msid semantic
  18740. session.msidSemantic = {
  18741. semantic: 'WMS',
  18742. token: '*'
  18743. };
  18744. var resStr = transform.write(session);
  18745. // Cache the transformed SDP (Unified Plan) for later re-use in this
  18746. // function.
  18747. this.cache[desc.type] = resStr;
  18748. return new RTCSessionDescription({
  18749. type: desc.type,
  18750. sdp: resStr
  18751. });
  18752. //#endregion
  18753. };
  18754. },{"./array-equals":64,"./transform":67}],67:[function(require,module,exports){
  18755. /* Copyright @ 2015 Atlassian Pty Ltd
  18756. *
  18757. * Licensed under the Apache License, Version 2.0 (the "License");
  18758. * you may not use this file except in compliance with the License.
  18759. * You may obtain a copy of the License at
  18760. *
  18761. * http://www.apache.org/licenses/LICENSE-2.0
  18762. *
  18763. * Unless required by applicable law or agreed to in writing, software
  18764. * distributed under the License is distributed on an "AS IS" BASIS,
  18765. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18766. * See the License for the specific language governing permissions and
  18767. * limitations under the License.
  18768. */
  18769. var transform = require('sdp-transform');
  18770. exports.write = function(session, opts) {
  18771. if (typeof session !== 'undefined' &&
  18772. typeof session.media !== 'undefined' &&
  18773. Array.isArray(session.media)) {
  18774. session.media.forEach(function (mLine) {
  18775. // expand sources to ssrcs
  18776. if (typeof mLine.sources !== 'undefined' &&
  18777. Object.keys(mLine.sources).length !== 0) {
  18778. mLine.ssrcs = [];
  18779. Object.keys(mLine.sources).forEach(function (ssrc) {
  18780. var source = mLine.sources[ssrc];
  18781. Object.keys(source).forEach(function (attribute) {
  18782. mLine.ssrcs.push({
  18783. id: ssrc,
  18784. attribute: attribute,
  18785. value: source[attribute]
  18786. });
  18787. });
  18788. });
  18789. delete mLine.sources;
  18790. }
  18791. // join ssrcs in ssrc groups
  18792. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18793. Array.isArray(mLine.ssrcGroups)) {
  18794. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  18795. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18796. Array.isArray(ssrcGroup.ssrcs)) {
  18797. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  18798. }
  18799. });
  18800. }
  18801. });
  18802. }
  18803. // join group mids
  18804. if (typeof session !== 'undefined' &&
  18805. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  18806. session.groups.forEach(function (g) {
  18807. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  18808. g.mids = g.mids.join(' ');
  18809. }
  18810. });
  18811. }
  18812. return transform.write(session, opts);
  18813. };
  18814. exports.parse = function(sdp) {
  18815. var session = transform.parse(sdp);
  18816. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  18817. Array.isArray(session.media)) {
  18818. session.media.forEach(function (mLine) {
  18819. // group sources attributes by ssrc
  18820. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  18821. mLine.sources = {};
  18822. mLine.ssrcs.forEach(function (ssrc) {
  18823. if (!mLine.sources[ssrc.id])
  18824. mLine.sources[ssrc.id] = {};
  18825. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  18826. });
  18827. delete mLine.ssrcs;
  18828. }
  18829. // split ssrcs in ssrc groups
  18830. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18831. Array.isArray(mLine.ssrcGroups)) {
  18832. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  18833. if (typeof ssrcGroup.ssrcs === 'string') {
  18834. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  18835. }
  18836. });
  18837. }
  18838. });
  18839. }
  18840. // split group mids
  18841. if (typeof session !== 'undefined' &&
  18842. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  18843. session.groups.forEach(function (g) {
  18844. if (typeof g.mids === 'string') {
  18845. g.mids = g.mids.split(' ');
  18846. }
  18847. });
  18848. }
  18849. return session;
  18850. };
  18851. },{"sdp-transform":75}],68:[function(require,module,exports){
  18852. /* Copyright @ 2015 Atlassian Pty Ltd
  18853. *
  18854. * Licensed under the Apache License, Version 2.0 (the "License");
  18855. * you may not use this file except in compliance with the License.
  18856. * You may obtain a copy of the License at
  18857. *
  18858. * http://www.apache.org/licenses/LICENSE-2.0
  18859. *
  18860. * Unless required by applicable law or agreed to in writing, software
  18861. * distributed under the License is distributed on an "AS IS" BASIS,
  18862. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18863. * See the License for the specific language governing permissions and
  18864. * limitations under the License.
  18865. */
  18866. var transform = require('sdp-transform');
  18867. var transformUtils = require('./transform-utils');
  18868. var parseSsrcs = transformUtils.parseSsrcs;
  18869. var writeSsrcs = transformUtils.writeSsrcs;
  18870. //region Constants
  18871. var DEFAULT_NUM_OF_LAYERS = 3;
  18872. //endregion
  18873. //region Ctor
  18874. function Simulcast(options) {
  18875. this.options = options ? options : {};
  18876. if (!this.options.numOfLayers) {
  18877. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  18878. }
  18879. this.layers = [];
  18880. }
  18881. //endregion
  18882. //region Stateless private utility functions
  18883. /**
  18884. * Returns a random integer between min (included) and max (excluded)
  18885. * Using Math.round() gives a non-uniform distribution!
  18886. * @returns {number}
  18887. */
  18888. function generateSSRC() {
  18889. var min = 0, max = 0xffffffff;
  18890. return Math.floor(Math.random() * (max - min)) + min;
  18891. };
  18892. function processVideo(session, action) {
  18893. if (session == null || !Array.isArray(session.media)) {
  18894. return;
  18895. }
  18896. session.media.forEach(function (mLine) {
  18897. if (mLine.type === 'video') {
  18898. action(mLine);
  18899. }
  18900. });
  18901. }
  18902. function validateDescription(desc)
  18903. {
  18904. return desc && desc != null
  18905. && desc.type && desc.type != ''
  18906. && desc.sdp && desc.sdp != '';
  18907. }
  18908. function explodeRemoteSimulcast(mLine) {
  18909. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18910. return;
  18911. }
  18912. var sources = parseSsrcs(mLine);
  18913. var order = [];
  18914. // Find the SIM group and explode its sources.
  18915. var j = mLine.ssrcGroups.length;
  18916. while (j--) {
  18917. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  18918. continue;
  18919. }
  18920. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  18921. for (var i = 0; i < simulcastSsrcs.length; i++) {
  18922. var ssrc = simulcastSsrcs[i];
  18923. order.push(ssrc);
  18924. var parts = sources[ssrc].msid.split(' ');
  18925. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  18926. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  18927. // Remove all the groups that this SSRC participates in.
  18928. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18929. if (relatedGroup.semantics === 'SIM') {
  18930. return;
  18931. }
  18932. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18933. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18934. return;
  18935. }
  18936. // Nuke all the related SSRCs.
  18937. relatedSsrcs.forEach(function (relatedSSRC) {
  18938. sources[relatedSSRC].msid = sources[ssrc].msid;
  18939. sources[relatedSSRC].cname = sources[ssrc].cname;
  18940. if (relatedSSRC !== ssrc) {
  18941. order.push(relatedSSRC);
  18942. }
  18943. });
  18944. // Schedule the related group for nuking.
  18945. })
  18946. }
  18947. mLine.ssrcs = writeSsrcs(sources, order);
  18948. mLine.ssrcGroups.splice(j, 1);
  18949. };
  18950. }
  18951. function implodeRemoteSimulcast(mLine) {
  18952. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18953. console.debug('Halt: There are no SSRC groups in the remote ' +
  18954. 'description.');
  18955. return;
  18956. }
  18957. var sources = parseSsrcs(mLine);
  18958. // Find the SIM group and nuke it.
  18959. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  18960. if (simulcastGroup.semantics !== 'SIM') {
  18961. return;
  18962. }
  18963. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  18964. // Schedule the SIM group for nuking.
  18965. simulcastGroup.nuke = true;
  18966. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  18967. // Nuke all the higher layer SSRCs.
  18968. for (var i = 1; i < simulcastSsrcs.length; i++) {
  18969. var ssrc = simulcastSsrcs[i];
  18970. delete sources[ssrc];
  18971. // Remove all the groups that this SSRC participates in.
  18972. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18973. if (relatedGroup.semantics === 'SIM') {
  18974. return;
  18975. }
  18976. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18977. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18978. return;
  18979. }
  18980. // Nuke all the related SSRCs.
  18981. relatedSsrcs.forEach(function (relatedSSRC) {
  18982. delete sources[relatedSSRC];
  18983. });
  18984. // Schedule the related group for nuking.
  18985. relatedGroup.nuke = true;
  18986. })
  18987. }
  18988. return;
  18989. });
  18990. mLine.ssrcs = writeSsrcs(sources);
  18991. // Nuke all the scheduled groups.
  18992. var i = mLine.ssrcGroups.length;
  18993. while (i--) {
  18994. if (mLine.ssrcGroups[i].nuke) {
  18995. mLine.ssrcGroups.splice(i, 1);
  18996. }
  18997. }
  18998. }
  18999. function removeGoogConference(mLine) {
  19000. if (!mLine || !Array.isArray(mLine.invalid)) {
  19001. return;
  19002. }
  19003. var i = mLine.invalid.length;
  19004. while (i--) {
  19005. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  19006. mLine.invalid.splice(i, 1);
  19007. }
  19008. }
  19009. }
  19010. function assertGoogConference(mLine) {
  19011. if (!mLine) {
  19012. return;
  19013. }
  19014. if (!Array.isArray(mLine.invalid)) {
  19015. mLine.invalid = [];
  19016. }
  19017. if (!mLine.invalid.some(
  19018. function (i) { return i.value === 'x-google-flag:conference' })) {
  19019. mLine.invalid.push({'value': 'x-google-flag:conference'});
  19020. }
  19021. }
  19022. //endregion
  19023. //region "Private" functions
  19024. /**
  19025. *
  19026. * @param mLine
  19027. * @private
  19028. */
  19029. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  19030. if (!mLine || mLine.type !== 'video') {
  19031. return;
  19032. }
  19033. var sources = parseSsrcs(mLine);
  19034. if (Object.keys(sources).length === 0) {
  19035. // no sources, disable simulcast.
  19036. if (this.layers.length !== 0) {
  19037. this.layers = [];
  19038. }
  19039. return;
  19040. }
  19041. // find the base layer (we'll reuse its msid and cname).
  19042. var baseLayerSSRC = Object.keys(sources)[0];
  19043. var baseLayer = sources[baseLayerSSRC];
  19044. // todo(gp) handle screen sharing.
  19045. // check if base CNAME has changed and reinitialise layers.
  19046. if (this.layers.length > 0
  19047. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  19048. this.layers = [];
  19049. }
  19050. // (re)initialise layers
  19051. if (this.layers.length < 1) {
  19052. // first push the base layer.
  19053. this.layers.push({
  19054. ssrc: baseLayerSSRC,
  19055. msid: baseLayer.msid,
  19056. cname: baseLayer.cname
  19057. });
  19058. var rtx = false; // RFC 4588
  19059. if (Array.isArray(mLine.rtp)) {
  19060. rtx = mLine.rtp.some(
  19061. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  19062. }
  19063. if (rtx) {
  19064. this.layers[0].rtx = generateSSRC();
  19065. }
  19066. // now push additional layers.
  19067. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  19068. var layer = { ssrc: generateSSRC() };
  19069. if (rtx) {
  19070. layer.rtx = generateSSRC();
  19071. }
  19072. this.layers.push(layer);
  19073. }
  19074. }
  19075. };
  19076. /**
  19077. *
  19078. * @param mLine
  19079. * @private
  19080. */
  19081. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  19082. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  19083. var sources = {};
  19084. var msid = this.layers[0].msid;
  19085. var cname = this.layers[0].cname;
  19086. var simulcastSsrcs = [];
  19087. var ssrcGroups = [];
  19088. for (var i = 0; i < this.layers.length; i++) {
  19089. var layer = this.layers[i];
  19090. sources[layer.ssrc] = { msid: msid, cname: cname };
  19091. simulcastSsrcs.push(layer.ssrc);
  19092. if (layer.rtx) {
  19093. sources[layer.rtx] = {
  19094. msid: msid,
  19095. cname: cname
  19096. }
  19097. ssrcGroups.push({
  19098. semantics: 'FID',
  19099. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  19100. });
  19101. }
  19102. }
  19103. ssrcGroups.push({
  19104. semantics: 'SIM',
  19105. ssrcs: simulcastSsrcs.join(' ')
  19106. });
  19107. mLine.ssrcGroups = ssrcGroups;
  19108. mLine.ssrcs = writeSsrcs(sources);
  19109. }
  19110. }
  19111. //endregion
  19112. //region "Public" functions
  19113. Simulcast.prototype.isSupported = function () {
  19114. return window.chrome;
  19115. // TODO this needs improvements. For example I doubt that Chrome in Android
  19116. // has simulcast support. Also, only recent versions of Chromium have native
  19117. // simulcast support.
  19118. }
  19119. /**
  19120. *
  19121. * @param desc
  19122. * @returns {RTCSessionDescription}
  19123. */
  19124. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  19125. if (!validateDescription(desc)) {
  19126. return desc;
  19127. }
  19128. var session = transform.parse(desc.sdp);
  19129. var self = this;
  19130. processVideo(session, function (mLine) {
  19131. // Handle simulcast reception.
  19132. if (self.options.explodeRemoteSimulcast) {
  19133. explodeRemoteSimulcast(mLine);
  19134. } else {
  19135. implodeRemoteSimulcast(mLine);
  19136. }
  19137. // If native simulcast is enabled, we must append the x-goog-conference
  19138. // attribute to the SDP.
  19139. if (self.layers.length < 1) {
  19140. removeGoogConference(mLine);
  19141. } else {
  19142. assertGoogConference(mLine);
  19143. }
  19144. });
  19145. return new RTCSessionDescription({
  19146. type: desc.type,
  19147. sdp: transform.write(session)
  19148. });
  19149. };
  19150. /**
  19151. *
  19152. * @param desc
  19153. * @returns {RTCSessionDescription}
  19154. */
  19155. Simulcast.prototype.mungeLocalDescription = function (desc) {
  19156. if (!validateDescription(desc) || !this.isSupported()) {
  19157. return desc;
  19158. }
  19159. var session = transform.parse(desc.sdp);
  19160. var self = this;
  19161. processVideo(session, function (mLine) {
  19162. // Initialize native simulcast layers, if not already done.
  19163. self._maybeInitializeLayers(mLine);
  19164. // Update the SDP with the simulcast layers.
  19165. self._restoreSimulcastView(mLine);
  19166. });
  19167. return new RTCSessionDescription({
  19168. type: desc.type,
  19169. sdp: transform.write(session)
  19170. });
  19171. };
  19172. //endregion
  19173. module.exports = Simulcast;
  19174. },{"./transform-utils":69,"sdp-transform":71}],69:[function(require,module,exports){
  19175. /* Copyright @ 2015 Atlassian Pty Ltd
  19176. *
  19177. * Licensed under the Apache License, Version 2.0 (the "License");
  19178. * you may not use this file except in compliance with the License.
  19179. * You may obtain a copy of the License at
  19180. *
  19181. * http://www.apache.org/licenses/LICENSE-2.0
  19182. *
  19183. * Unless required by applicable law or agreed to in writing, software
  19184. * distributed under the License is distributed on an "AS IS" BASIS,
  19185. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19186. * See the License for the specific language governing permissions and
  19187. * limitations under the License.
  19188. */
  19189. exports.writeSsrcs = function(sources, order) {
  19190. var ssrcs = [];
  19191. // expand sources to ssrcs
  19192. if (typeof sources !== 'undefined' &&
  19193. Object.keys(sources).length !== 0) {
  19194. if (Array.isArray(order)) {
  19195. for (var i = 0; i < order.length; i++) {
  19196. var ssrc = order[i];
  19197. var source = sources[ssrc];
  19198. Object.keys(source).forEach(function (attribute) {
  19199. ssrcs.push({
  19200. id: ssrc,
  19201. attribute: attribute,
  19202. value: source[attribute]
  19203. });
  19204. });
  19205. }
  19206. } else {
  19207. Object.keys(sources).forEach(function (ssrc) {
  19208. var source = sources[ssrc];
  19209. Object.keys(source).forEach(function (attribute) {
  19210. ssrcs.push({
  19211. id: ssrc,
  19212. attribute: attribute,
  19213. value: source[attribute]
  19214. });
  19215. });
  19216. });
  19217. }
  19218. }
  19219. return ssrcs;
  19220. };
  19221. exports.parseSsrcs = function (mLine) {
  19222. var sources = {};
  19223. // group sources attributes by ssrc.
  19224. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19225. mLine.ssrcs.forEach(function (ssrc) {
  19226. if (!sources[ssrc.id])
  19227. sources[ssrc.id] = {};
  19228. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19229. });
  19230. }
  19231. return sources;
  19232. };
  19233. },{}],70:[function(require,module,exports){
  19234. var grammar = module.exports = {
  19235. v: [{
  19236. name: 'version',
  19237. reg: /^(\d*)$/
  19238. }],
  19239. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19240. // NB: sessionId will be a String in most cases because it is huge
  19241. name: 'origin',
  19242. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19243. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19244. format: "%s %s %d %s IP%d %s"
  19245. }],
  19246. // default parsing of these only (though some of these feel outdated)
  19247. s: [{ name: 'name' }],
  19248. i: [{ name: 'description' }],
  19249. u: [{ name: 'uri' }],
  19250. e: [{ name: 'email' }],
  19251. p: [{ name: 'phone' }],
  19252. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19253. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19254. //k: [{}], // outdated thing ignored
  19255. t: [{ //t=0 0
  19256. name: 'timing',
  19257. reg: /^(\d*) (\d*)/,
  19258. names: ['start', 'stop'],
  19259. format: "%d %d"
  19260. }],
  19261. c: [{ //c=IN IP4 10.47.197.26
  19262. name: 'connection',
  19263. reg: /^IN IP(\d) (\S*)/,
  19264. names: ['version', 'ip'],
  19265. format: "IN IP%d %s"
  19266. }],
  19267. b: [{ //b=AS:4000
  19268. push: 'bandwidth',
  19269. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19270. names: ['type', 'limit'],
  19271. format: "%s:%s"
  19272. }],
  19273. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19274. // NB: special - pushes to session
  19275. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19276. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19277. names: ['type', 'port', 'protocol', 'payloads'],
  19278. format: "%s %d %s %s"
  19279. }],
  19280. a: [
  19281. { //a=rtpmap:110 opus/48000/2
  19282. push: 'rtp',
  19283. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19284. names: ['payload', 'codec', 'rate', 'encoding'],
  19285. format: function (o) {
  19286. return (o.encoding) ?
  19287. "rtpmap:%d %s/%s/%s":
  19288. "rtpmap:%d %s/%s";
  19289. }
  19290. },
  19291. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19292. push: 'fmtp',
  19293. reg: /^fmtp:(\d*) (\S*)/,
  19294. names: ['payload', 'config'],
  19295. format: "fmtp:%d %s"
  19296. },
  19297. { //a=control:streamid=0
  19298. name: 'control',
  19299. reg: /^control:(.*)/,
  19300. format: "control:%s"
  19301. },
  19302. { //a=rtcp:65179 IN IP4 193.84.77.194
  19303. name: 'rtcp',
  19304. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19305. names: ['port', 'netType', 'ipVer', 'address'],
  19306. format: function (o) {
  19307. return (o.address != null) ?
  19308. "rtcp:%d %s IP%d %s":
  19309. "rtcp:%d";
  19310. }
  19311. },
  19312. { //a=rtcp-fb:98 trr-int 100
  19313. push: 'rtcpFbTrrInt',
  19314. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19315. names: ['payload', 'value'],
  19316. format: "rtcp-fb:%d trr-int %d"
  19317. },
  19318. { //a=rtcp-fb:98 nack rpsi
  19319. push: 'rtcpFb',
  19320. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19321. names: ['payload', 'type', 'subtype'],
  19322. format: function (o) {
  19323. return (o.subtype != null) ?
  19324. "rtcp-fb:%s %s %s":
  19325. "rtcp-fb:%s %s";
  19326. }
  19327. },
  19328. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19329. //a=extmap:1/recvonly URI-gps-string
  19330. push: 'ext',
  19331. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19332. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19333. format: function (o) {
  19334. return (o.config != null) ?
  19335. "extmap:%s %s %s":
  19336. "extmap:%s %s";
  19337. }
  19338. },
  19339. {
  19340. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19341. push: 'crypto',
  19342. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19343. names: ['id', 'suite', 'config', 'sessionConfig'],
  19344. format: function (o) {
  19345. return (o.sessionConfig != null) ?
  19346. "crypto:%d %s %s %s":
  19347. "crypto:%d %s %s";
  19348. }
  19349. },
  19350. { //a=setup:actpass
  19351. name: 'setup',
  19352. reg: /^setup:(\w*)/,
  19353. format: "setup:%s"
  19354. },
  19355. { //a=mid:1
  19356. name: 'mid',
  19357. reg: /^mid:([^\s]*)/,
  19358. format: "mid:%s"
  19359. },
  19360. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19361. name: 'msid',
  19362. reg: /^msid:(.*)/,
  19363. format: "msid:%s"
  19364. },
  19365. { //a=ptime:20
  19366. name: 'ptime',
  19367. reg: /^ptime:(\d*)/,
  19368. format: "ptime:%d"
  19369. },
  19370. { //a=maxptime:60
  19371. name: 'maxptime',
  19372. reg: /^maxptime:(\d*)/,
  19373. format: "maxptime:%d"
  19374. },
  19375. { //a=sendrecv
  19376. name: 'direction',
  19377. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19378. },
  19379. { //a=ice-lite
  19380. name: 'icelite',
  19381. reg: /^(ice-lite)/
  19382. },
  19383. { //a=ice-ufrag:F7gI
  19384. name: 'iceUfrag',
  19385. reg: /^ice-ufrag:(\S*)/,
  19386. format: "ice-ufrag:%s"
  19387. },
  19388. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19389. name: 'icePwd',
  19390. reg: /^ice-pwd:(\S*)/,
  19391. format: "ice-pwd:%s"
  19392. },
  19393. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19394. name: 'fingerprint',
  19395. reg: /^fingerprint:(\S*) (\S*)/,
  19396. names: ['type', 'hash'],
  19397. format: "fingerprint:%s %s"
  19398. },
  19399. {
  19400. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19401. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19402. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19403. push:'candidates',
  19404. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19405. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19406. format: function (o) {
  19407. var str = "candidate:%s %d %s %d %s %d typ %s";
  19408. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19409. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19410. if (o.generation != null) {
  19411. str += " generation %d";
  19412. }
  19413. return str;
  19414. }
  19415. },
  19416. { //a=end-of-candidates (keep after the candidates line for readability)
  19417. name: 'endOfCandidates',
  19418. reg: /^(end-of-candidates)/
  19419. },
  19420. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19421. name: 'remoteCandidates',
  19422. reg: /^remote-candidates:(.*)/,
  19423. format: "remote-candidates:%s"
  19424. },
  19425. { //a=ice-options:google-ice
  19426. name: 'iceOptions',
  19427. reg: /^ice-options:(\S*)/,
  19428. format: "ice-options:%s"
  19429. },
  19430. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19431. push: "ssrcs",
  19432. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19433. names: ['id', 'attribute', 'value'],
  19434. format: "ssrc:%d %s:%s"
  19435. },
  19436. { //a=ssrc-group:FEC 1 2
  19437. push: "ssrcGroups",
  19438. reg: /^ssrc-group:(\w*) (.*)/,
  19439. names: ['semantics', 'ssrcs'],
  19440. format: "ssrc-group:%s %s"
  19441. },
  19442. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19443. name: "msidSemantic",
  19444. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19445. names: ['semantic', 'token'],
  19446. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19447. },
  19448. { //a=group:BUNDLE audio video
  19449. push: 'groups',
  19450. reg: /^group:(\w*) (.*)/,
  19451. names: ['type', 'mids'],
  19452. format: "group:%s %s"
  19453. },
  19454. { //a=rtcp-mux
  19455. name: 'rtcpMux',
  19456. reg: /^(rtcp-mux)/
  19457. },
  19458. { //a=rtcp-rsize
  19459. name: 'rtcpRsize',
  19460. reg: /^(rtcp-rsize)/
  19461. },
  19462. { // any a= that we don't understand is kepts verbatim on media.invalid
  19463. push: 'invalid',
  19464. names: ["value"]
  19465. }
  19466. ]
  19467. };
  19468. // set sensible defaults to avoid polluting the grammar with boring details
  19469. Object.keys(grammar).forEach(function (key) {
  19470. var objs = grammar[key];
  19471. objs.forEach(function (obj) {
  19472. if (!obj.reg) {
  19473. obj.reg = /(.*)/;
  19474. }
  19475. if (!obj.format) {
  19476. obj.format = "%s";
  19477. }
  19478. });
  19479. });
  19480. },{}],71:[function(require,module,exports){
  19481. var parser = require('./parser');
  19482. var writer = require('./writer');
  19483. exports.write = writer;
  19484. exports.parse = parser.parse;
  19485. exports.parseFmtpConfig = parser.parseFmtpConfig;
  19486. exports.parsePayloads = parser.parsePayloads;
  19487. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  19488. },{"./parser":72,"./writer":73}],72:[function(require,module,exports){
  19489. var toIntIfInt = function (v) {
  19490. return String(Number(v)) === v ? Number(v) : v;
  19491. };
  19492. var attachProperties = function (match, location, names, rawName) {
  19493. if (rawName && !names) {
  19494. location[rawName] = toIntIfInt(match[1]);
  19495. }
  19496. else {
  19497. for (var i = 0; i < names.length; i += 1) {
  19498. if (match[i+1] != null) {
  19499. location[names[i]] = toIntIfInt(match[i+1]);
  19500. }
  19501. }
  19502. }
  19503. };
  19504. var parseReg = function (obj, location, content) {
  19505. var needsBlank = obj.name && obj.names;
  19506. if (obj.push && !location[obj.push]) {
  19507. location[obj.push] = [];
  19508. }
  19509. else if (needsBlank && !location[obj.name]) {
  19510. location[obj.name] = {};
  19511. }
  19512. var keyLocation = obj.push ?
  19513. {} : // blank object that will be pushed
  19514. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19515. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19516. if (obj.push) {
  19517. location[obj.push].push(keyLocation);
  19518. }
  19519. };
  19520. var grammar = require('./grammar');
  19521. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19522. exports.parse = function (sdp) {
  19523. var session = {}
  19524. , media = []
  19525. , location = session; // points at where properties go under (one of the above)
  19526. // parse lines we understand
  19527. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19528. var type = l[0];
  19529. var content = l.slice(2);
  19530. if (type === 'm') {
  19531. media.push({rtp: [], fmtp: []});
  19532. location = media[media.length-1]; // point at latest media line
  19533. }
  19534. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19535. var obj = grammar[type][j];
  19536. if (obj.reg.test(content)) {
  19537. return parseReg(obj, location, content);
  19538. }
  19539. }
  19540. });
  19541. session.media = media; // link it up
  19542. return session;
  19543. };
  19544. var fmtpReducer = function (acc, expr) {
  19545. var s = expr.split('=');
  19546. if (s.length === 2) {
  19547. acc[s[0]] = toIntIfInt(s[1]);
  19548. }
  19549. return acc;
  19550. };
  19551. exports.parseFmtpConfig = function (str) {
  19552. return str.split(';').reduce(fmtpReducer, {});
  19553. };
  19554. exports.parsePayloads = function (str) {
  19555. return str.split(' ').map(Number);
  19556. };
  19557. exports.parseRemoteCandidates = function (str) {
  19558. var candidates = [];
  19559. var parts = str.split(' ').map(toIntIfInt);
  19560. for (var i = 0; i < parts.length; i += 3) {
  19561. candidates.push({
  19562. component: parts[i],
  19563. ip: parts[i + 1],
  19564. port: parts[i + 2]
  19565. });
  19566. }
  19567. return candidates;
  19568. };
  19569. },{"./grammar":70}],73:[function(require,module,exports){
  19570. var grammar = require('./grammar');
  19571. // customized util.format - discards excess arguments and can void middle ones
  19572. var formatRegExp = /%[sdv%]/g;
  19573. var format = function (formatStr) {
  19574. var i = 1;
  19575. var args = arguments;
  19576. var len = args.length;
  19577. return formatStr.replace(formatRegExp, function (x) {
  19578. if (i >= len) {
  19579. return x; // missing argument
  19580. }
  19581. var arg = args[i];
  19582. i += 1;
  19583. switch (x) {
  19584. case '%%':
  19585. return '%';
  19586. case '%s':
  19587. return String(arg);
  19588. case '%d':
  19589. return Number(arg);
  19590. case '%v':
  19591. return '';
  19592. }
  19593. });
  19594. // NB: we discard excess arguments - they are typically undefined from makeLine
  19595. };
  19596. var makeLine = function (type, obj, location) {
  19597. var str = obj.format instanceof Function ?
  19598. (obj.format(obj.push ? location : location[obj.name])) :
  19599. obj.format;
  19600. var args = [type + '=' + str];
  19601. if (obj.names) {
  19602. for (var i = 0; i < obj.names.length; i += 1) {
  19603. var n = obj.names[i];
  19604. if (obj.name) {
  19605. args.push(location[obj.name][n]);
  19606. }
  19607. else { // for mLine and push attributes
  19608. args.push(location[obj.names[i]]);
  19609. }
  19610. }
  19611. }
  19612. else {
  19613. args.push(location[obj.name]);
  19614. }
  19615. return format.apply(null, args);
  19616. };
  19617. // RFC specified order
  19618. // TODO: extend this with all the rest
  19619. var defaultOuterOrder = [
  19620. 'v', 'o', 's', 'i',
  19621. 'u', 'e', 'p', 'c',
  19622. 'b', 't', 'r', 'z', 'a'
  19623. ];
  19624. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  19625. module.exports = function (session, opts) {
  19626. opts = opts || {};
  19627. // ensure certain properties exist
  19628. if (session.version == null) {
  19629. session.version = 0; // "v=0" must be there (only defined version atm)
  19630. }
  19631. if (session.name == null) {
  19632. session.name = " "; // "s= " must be there if no meaningful name set
  19633. }
  19634. session.media.forEach(function (mLine) {
  19635. if (mLine.payloads == null) {
  19636. mLine.payloads = "";
  19637. }
  19638. });
  19639. var outerOrder = opts.outerOrder || defaultOuterOrder;
  19640. var innerOrder = opts.innerOrder || defaultInnerOrder;
  19641. var sdp = [];
  19642. // loop through outerOrder for matching properties on session
  19643. outerOrder.forEach(function (type) {
  19644. grammar[type].forEach(function (obj) {
  19645. if (obj.name in session && session[obj.name] != null) {
  19646. sdp.push(makeLine(type, obj, session));
  19647. }
  19648. else if (obj.push in session && session[obj.push] != null) {
  19649. session[obj.push].forEach(function (el) {
  19650. sdp.push(makeLine(type, obj, el));
  19651. });
  19652. }
  19653. });
  19654. });
  19655. // then for each media line, follow the innerOrder
  19656. session.media.forEach(function (mLine) {
  19657. sdp.push(makeLine('m', grammar.m[0], mLine));
  19658. innerOrder.forEach(function (type) {
  19659. grammar[type].forEach(function (obj) {
  19660. if (obj.name in mLine && mLine[obj.name] != null) {
  19661. sdp.push(makeLine(type, obj, mLine));
  19662. }
  19663. else if (obj.push in mLine && mLine[obj.push] != null) {
  19664. mLine[obj.push].forEach(function (el) {
  19665. sdp.push(makeLine(type, obj, el));
  19666. });
  19667. }
  19668. });
  19669. });
  19670. });
  19671. return sdp.join('\r\n') + '\r\n';
  19672. };
  19673. },{"./grammar":70}],74:[function(require,module,exports){
  19674. var grammar = module.exports = {
  19675. v: [{
  19676. name: 'version',
  19677. reg: /^(\d*)$/
  19678. }],
  19679. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19680. // NB: sessionId will be a String in most cases because it is huge
  19681. name: 'origin',
  19682. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19683. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19684. format: "%s %s %d %s IP%d %s"
  19685. }],
  19686. // default parsing of these only (though some of these feel outdated)
  19687. s: [{ name: 'name' }],
  19688. i: [{ name: 'description' }],
  19689. u: [{ name: 'uri' }],
  19690. e: [{ name: 'email' }],
  19691. p: [{ name: 'phone' }],
  19692. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19693. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19694. //k: [{}], // outdated thing ignored
  19695. t: [{ //t=0 0
  19696. name: 'timing',
  19697. reg: /^(\d*) (\d*)/,
  19698. names: ['start', 'stop'],
  19699. format: "%d %d"
  19700. }],
  19701. c: [{ //c=IN IP4 10.47.197.26
  19702. name: 'connection',
  19703. reg: /^IN IP(\d) (\S*)/,
  19704. names: ['version', 'ip'],
  19705. format: "IN IP%d %s"
  19706. }],
  19707. b: [{ //b=AS:4000
  19708. push: 'bandwidth',
  19709. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19710. names: ['type', 'limit'],
  19711. format: "%s:%s"
  19712. }],
  19713. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19714. // NB: special - pushes to session
  19715. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19716. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19717. names: ['type', 'port', 'protocol', 'payloads'],
  19718. format: "%s %d %s %s"
  19719. }],
  19720. a: [
  19721. { //a=rtpmap:110 opus/48000/2
  19722. push: 'rtp',
  19723. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19724. names: ['payload', 'codec', 'rate', 'encoding'],
  19725. format: function (o) {
  19726. return (o.encoding) ?
  19727. "rtpmap:%d %s/%s/%s":
  19728. "rtpmap:%d %s/%s";
  19729. }
  19730. },
  19731. {
  19732. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19733. //a=fmtp:111 minptime=10; useinbandfec=1
  19734. push: 'fmtp',
  19735. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19736. names: ['payload', 'config'],
  19737. format: "fmtp:%d %s"
  19738. },
  19739. { //a=control:streamid=0
  19740. name: 'control',
  19741. reg: /^control:(.*)/,
  19742. format: "control:%s"
  19743. },
  19744. { //a=rtcp:65179 IN IP4 193.84.77.194
  19745. name: 'rtcp',
  19746. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19747. names: ['port', 'netType', 'ipVer', 'address'],
  19748. format: function (o) {
  19749. return (o.address != null) ?
  19750. "rtcp:%d %s IP%d %s":
  19751. "rtcp:%d";
  19752. }
  19753. },
  19754. { //a=rtcp-fb:98 trr-int 100
  19755. push: 'rtcpFbTrrInt',
  19756. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19757. names: ['payload', 'value'],
  19758. format: "rtcp-fb:%d trr-int %d"
  19759. },
  19760. { //a=rtcp-fb:98 nack rpsi
  19761. push: 'rtcpFb',
  19762. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19763. names: ['payload', 'type', 'subtype'],
  19764. format: function (o) {
  19765. return (o.subtype != null) ?
  19766. "rtcp-fb:%s %s %s":
  19767. "rtcp-fb:%s %s";
  19768. }
  19769. },
  19770. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19771. //a=extmap:1/recvonly URI-gps-string
  19772. push: 'ext',
  19773. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19774. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19775. format: function (o) {
  19776. return (o.config != null) ?
  19777. "extmap:%s %s %s":
  19778. "extmap:%s %s";
  19779. }
  19780. },
  19781. {
  19782. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19783. push: 'crypto',
  19784. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19785. names: ['id', 'suite', 'config', 'sessionConfig'],
  19786. format: function (o) {
  19787. return (o.sessionConfig != null) ?
  19788. "crypto:%d %s %s %s":
  19789. "crypto:%d %s %s";
  19790. }
  19791. },
  19792. { //a=setup:actpass
  19793. name: 'setup',
  19794. reg: /^setup:(\w*)/,
  19795. format: "setup:%s"
  19796. },
  19797. { //a=mid:1
  19798. name: 'mid',
  19799. reg: /^mid:([^\s]*)/,
  19800. format: "mid:%s"
  19801. },
  19802. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19803. name: 'msid',
  19804. reg: /^msid:(.*)/,
  19805. format: "msid:%s"
  19806. },
  19807. { //a=ptime:20
  19808. name: 'ptime',
  19809. reg: /^ptime:(\d*)/,
  19810. format: "ptime:%d"
  19811. },
  19812. { //a=maxptime:60
  19813. name: 'maxptime',
  19814. reg: /^maxptime:(\d*)/,
  19815. format: "maxptime:%d"
  19816. },
  19817. { //a=sendrecv
  19818. name: 'direction',
  19819. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19820. },
  19821. { //a=ice-lite
  19822. name: 'icelite',
  19823. reg: /^(ice-lite)/
  19824. },
  19825. { //a=ice-ufrag:F7gI
  19826. name: 'iceUfrag',
  19827. reg: /^ice-ufrag:(\S*)/,
  19828. format: "ice-ufrag:%s"
  19829. },
  19830. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19831. name: 'icePwd',
  19832. reg: /^ice-pwd:(\S*)/,
  19833. format: "ice-pwd:%s"
  19834. },
  19835. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19836. name: 'fingerprint',
  19837. reg: /^fingerprint:(\S*) (\S*)/,
  19838. names: ['type', 'hash'],
  19839. format: "fingerprint:%s %s"
  19840. },
  19841. {
  19842. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19843. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19844. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19845. push:'candidates',
  19846. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19847. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19848. format: function (o) {
  19849. var str = "candidate:%s %d %s %d %s %d typ %s";
  19850. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19851. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19852. if (o.generation != null) {
  19853. str += " generation %d";
  19854. }
  19855. return str;
  19856. }
  19857. },
  19858. { //a=end-of-candidates (keep after the candidates line for readability)
  19859. name: 'endOfCandidates',
  19860. reg: /^(end-of-candidates)/
  19861. },
  19862. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19863. name: 'remoteCandidates',
  19864. reg: /^remote-candidates:(.*)/,
  19865. format: "remote-candidates:%s"
  19866. },
  19867. { //a=ice-options:google-ice
  19868. name: 'iceOptions',
  19869. reg: /^ice-options:(\S*)/,
  19870. format: "ice-options:%s"
  19871. },
  19872. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19873. push: "ssrcs",
  19874. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19875. names: ['id', 'attribute', 'value'],
  19876. format: "ssrc:%d %s:%s"
  19877. },
  19878. { //a=ssrc-group:FEC 1 2
  19879. push: "ssrcGroups",
  19880. reg: /^ssrc-group:(\w*) (.*)/,
  19881. names: ['semantics', 'ssrcs'],
  19882. format: "ssrc-group:%s %s"
  19883. },
  19884. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19885. name: "msidSemantic",
  19886. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19887. names: ['semantic', 'token'],
  19888. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19889. },
  19890. { //a=group:BUNDLE audio video
  19891. push: 'groups',
  19892. reg: /^group:(\w*) (.*)/,
  19893. names: ['type', 'mids'],
  19894. format: "group:%s %s"
  19895. },
  19896. { //a=rtcp-mux
  19897. name: 'rtcpMux',
  19898. reg: /^(rtcp-mux)/
  19899. },
  19900. { //a=rtcp-rsize
  19901. name: 'rtcpRsize',
  19902. reg: /^(rtcp-rsize)/
  19903. },
  19904. { // any a= that we don't understand is kepts verbatim on media.invalid
  19905. push: 'invalid',
  19906. names: ["value"]
  19907. }
  19908. ]
  19909. };
  19910. // set sensible defaults to avoid polluting the grammar with boring details
  19911. Object.keys(grammar).forEach(function (key) {
  19912. var objs = grammar[key];
  19913. objs.forEach(function (obj) {
  19914. if (!obj.reg) {
  19915. obj.reg = /(.*)/;
  19916. }
  19917. if (!obj.format) {
  19918. obj.format = "%s";
  19919. }
  19920. });
  19921. });
  19922. },{}],75:[function(require,module,exports){
  19923. arguments[4][71][0].apply(exports,arguments)
  19924. },{"./parser":76,"./writer":77,"dup":71}],76:[function(require,module,exports){
  19925. var toIntIfInt = function (v) {
  19926. return String(Number(v)) === v ? Number(v) : v;
  19927. };
  19928. var attachProperties = function (match, location, names, rawName) {
  19929. if (rawName && !names) {
  19930. location[rawName] = toIntIfInt(match[1]);
  19931. }
  19932. else {
  19933. for (var i = 0; i < names.length; i += 1) {
  19934. if (match[i+1] != null) {
  19935. location[names[i]] = toIntIfInt(match[i+1]);
  19936. }
  19937. }
  19938. }
  19939. };
  19940. var parseReg = function (obj, location, content) {
  19941. var needsBlank = obj.name && obj.names;
  19942. if (obj.push && !location[obj.push]) {
  19943. location[obj.push] = [];
  19944. }
  19945. else if (needsBlank && !location[obj.name]) {
  19946. location[obj.name] = {};
  19947. }
  19948. var keyLocation = obj.push ?
  19949. {} : // blank object that will be pushed
  19950. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19951. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19952. if (obj.push) {
  19953. location[obj.push].push(keyLocation);
  19954. }
  19955. };
  19956. var grammar = require('./grammar');
  19957. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19958. exports.parse = function (sdp) {
  19959. var session = {}
  19960. , media = []
  19961. , location = session; // points at where properties go under (one of the above)
  19962. // parse lines we understand
  19963. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19964. var type = l[0];
  19965. var content = l.slice(2);
  19966. if (type === 'm') {
  19967. media.push({rtp: [], fmtp: []});
  19968. location = media[media.length-1]; // point at latest media line
  19969. }
  19970. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19971. var obj = grammar[type][j];
  19972. if (obj.reg.test(content)) {
  19973. return parseReg(obj, location, content);
  19974. }
  19975. }
  19976. });
  19977. session.media = media; // link it up
  19978. return session;
  19979. };
  19980. var fmtpReducer = function (acc, expr) {
  19981. var s = expr.split('=');
  19982. if (s.length === 2) {
  19983. acc[s[0]] = toIntIfInt(s[1]);
  19984. }
  19985. return acc;
  19986. };
  19987. exports.parseFmtpConfig = function (str) {
  19988. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  19989. };
  19990. exports.parsePayloads = function (str) {
  19991. return str.split(' ').map(Number);
  19992. };
  19993. exports.parseRemoteCandidates = function (str) {
  19994. var candidates = [];
  19995. var parts = str.split(' ').map(toIntIfInt);
  19996. for (var i = 0; i < parts.length; i += 3) {
  19997. candidates.push({
  19998. component: parts[i],
  19999. ip: parts[i + 1],
  20000. port: parts[i + 2]
  20001. });
  20002. }
  20003. return candidates;
  20004. };
  20005. },{"./grammar":74}],77:[function(require,module,exports){
  20006. arguments[4][73][0].apply(exports,arguments)
  20007. },{"./grammar":74,"dup":73}],78:[function(require,module,exports){
  20008. var MediaStreamType = {
  20009. VIDEO_TYPE: "Video",
  20010. AUDIO_TYPE: "Audio"
  20011. };
  20012. module.exports = MediaStreamType;
  20013. },{}],79:[function(require,module,exports){
  20014. var RTCEvents = {
  20015. RTC_READY: "rtc.ready",
  20016. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20017. LASTN_CHANGED: "rtc.lastn_changed",
  20018. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20019. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20020. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20021. };
  20022. module.exports = RTCEvents;
  20023. },{}],80:[function(require,module,exports){
  20024. var Resolutions = {
  20025. "1080": {
  20026. width: 1920,
  20027. height: 1080,
  20028. order: 7
  20029. },
  20030. "fullhd": {
  20031. width: 1920,
  20032. height: 1080,
  20033. order: 7
  20034. },
  20035. "720": {
  20036. width: 1280,
  20037. height: 720,
  20038. order: 6
  20039. },
  20040. "hd": {
  20041. width: 1280,
  20042. height: 720,
  20043. order: 6
  20044. },
  20045. "960": {
  20046. width: 960,
  20047. height: 720,
  20048. order: 5
  20049. },
  20050. "640": {
  20051. width: 640,
  20052. height: 480,
  20053. order: 4
  20054. },
  20055. "vga": {
  20056. width: 640,
  20057. height: 480,
  20058. order: 4
  20059. },
  20060. "360": {
  20061. width: 640,
  20062. height: 360,
  20063. order: 3
  20064. },
  20065. "320": {
  20066. width: 320,
  20067. height: 240,
  20068. order: 2
  20069. },
  20070. "180": {
  20071. width: 320,
  20072. height: 180,
  20073. order: 1
  20074. }
  20075. };
  20076. module.exports = Resolutions;
  20077. },{}],81:[function(require,module,exports){
  20078. var StreamEventTypes = {
  20079. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  20080. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  20081. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  20082. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  20083. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  20084. TRACK_MUTE_CHANGED: "rtc.track_mute_changed"
  20085. };
  20086. module.exports = StreamEventTypes;
  20087. },{}],82:[function(require,module,exports){
  20088. var AuthenticationEvents = {
  20089. /**
  20090. * Event callback arguments:
  20091. * function(authenticationEnabled, userIdentity)
  20092. * authenticationEnabled - indicates whether authentication has been enabled
  20093. * in this session
  20094. * userIdentity - if user has been logged in then it contains user name. If
  20095. * contains 'null' or 'undefined' then user is not logged in.
  20096. */
  20097. IDENTITY_UPDATED: "authentication.identity_updated"
  20098. };
  20099. module.exports = AuthenticationEvents;
  20100. },{}],83:[function(require,module,exports){
  20101. var DesktopSharingEventTypes = {
  20102. INIT: "ds.init",
  20103. SWITCHING_DONE: "ds.switching_done",
  20104. NEW_STREAM_CREATED: "ds.new_stream_created",
  20105. /**
  20106. * An event which indicates that the jidesha extension for Firefox is
  20107. * needed to proceed with screen sharing, and that it is not installed.
  20108. */
  20109. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  20110. };
  20111. module.exports = DesktopSharingEventTypes;
  20112. },{}],84:[function(require,module,exports){
  20113. module.exports = {
  20114. /**
  20115. * An event carrying connection statistics.
  20116. */
  20117. CONNECTION_STATS: "statistics.connectionstats",
  20118. /**
  20119. * FIXME: needs documentation.
  20120. */
  20121. AUDIO_LEVEL: "statistics.audioLevel",
  20122. /**
  20123. * FIXME: needs documentation.
  20124. */
  20125. STOP: "statistics.stop"
  20126. };
  20127. },{}],85:[function(require,module,exports){
  20128. var Constants = {
  20129. LOCAL_JID: 'local'
  20130. };
  20131. module.exports = Constants;
  20132. },{}],86:[function(require,module,exports){
  20133. var XMPPEvents = {
  20134. // Designates an event indicating that the connection to the XMPP server
  20135. // failed.
  20136. CONNECTION_FAILED: "xmpp.connection.failed",
  20137. // Designates an event indicating that the media (ICE) connection was
  20138. // interrupted. This should go to the RTC module.
  20139. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20140. // Designates an event indicating that the media (ICE) connection was
  20141. // restored. This should go to the RTC module.
  20142. CONNECTION_RESTORED: "xmpp.connection.restored",
  20143. // Designates an event indicating that an offer (e.g. Jingle
  20144. // session-initiate) was received.
  20145. CALL_INCOMING: "xmpp.callincoming.jingle",
  20146. // Designates an event indicating that we were kicked from the XMPP MUC.
  20147. KICKED: "xmpp.kicked",
  20148. // Designates an event indicating that the userID for a specific JID has
  20149. // changed.
  20150. // Note: currently this event fires every time we receive presence from
  20151. // someone (regardless of whether or not the "userID" changed).
  20152. USER_ID_CHANGED: "xmpp.user_id_changed",
  20153. // Designates an event indicating that we have joined the XMPP MUC.
  20154. MUC_JOINED: "xmpp.muc_joined",
  20155. // Designates an event indicating that a participant joined the XMPP MUC.
  20156. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20157. // Designates an event indicating that a participant left the XMPP MUC.
  20158. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20159. // Designates an event indicating that the MUC role of a participant has
  20160. // changed.
  20161. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20162. // Designates an event indicating that the XMPP MUC was destroyed.
  20163. MUC_DESTROYED: "xmpp.muc_destroyed",
  20164. // Designates an event indicating that the display name of a participant
  20165. // has changed.
  20166. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20167. // Designates an event indicating that we received statistics from a
  20168. // participant in the MUC.
  20169. REMOTE_STATS: "xmpp.remote_stats",
  20170. // Designates an event indicating that our role in the XMPP MUC has changed.
  20171. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20172. // Designates an event indicating that the subject of the XMPP MUC has
  20173. // changed.
  20174. SUBJECT_CHANGED: "xmpp.subject_changed",
  20175. // Designates an event indicating that an XMPP message in the MUC was
  20176. // received.
  20177. MESSAGE_RECEIVED: "xmpp.message_received",
  20178. // Designates an event indicating that we sent an XMPP message to the MUC.
  20179. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20180. // Designates an event indicating that the video type (e.g. 'camera' or
  20181. // 'screen') for a participant has changed.
  20182. // Note: currently this event fires every time we receive presence from
  20183. // someone (regardless of whether or not the "video type" changed).
  20184. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20185. // Designates an event indicating that a participant in the XMPP MUC has
  20186. // advertised that they have audio muted (or unmuted).
  20187. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20188. // Designates an event indicating that a participant in the XMPP MUC has
  20189. // advertised that they have video muted (or unmuted).
  20190. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20191. // Designates an event indicating that the focus has asked us to mute our
  20192. // audio.
  20193. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20194. // Designates an event indicating that a moderator in the room changed the
  20195. // "start muted" settings for the conference.
  20196. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20197. // Designates an event indicating that we should join the conference with
  20198. // audio and/or video muted.
  20199. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20200. // Designates an event indicating that a remote participant's available
  20201. // devices (whether he supports a audio and/or video) changed.
  20202. // Note: currently this event fires every time we receive presence from
  20203. // someone (regardless of whether or not the devices changed).
  20204. DEVICE_AVAILABLE: "xmpp.device_available",
  20205. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20206. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20207. PASSWORD_REQUIRED: "xmpp.password_required",
  20208. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20209. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20210. ETHERPAD: "xmpp.etherpad",
  20211. BRIDGE_DOWN: "xmpp.bridge_down",
  20212. PRESENCE_STATUS: "xmpp.presence_status",
  20213. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20214. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20215. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20216. // TODO: only used in a hack, should probably be removed.
  20217. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20218. // TODO: only used in a hack, should probably be removed.
  20219. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20220. // TODO: only used in a hack, should probably be removed.
  20221. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20222. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20223. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20224. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20225. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20226. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20227. // xmpp is connected and obtained user media
  20228. READY_TO_JOIN: 'xmpp.ready_to_join',
  20229. FOCUS_LEFT: "xmpp.focus_left",
  20230. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  20231. };
  20232. module.exports = XMPPEvents;
  20233. },{}]},{},[7])(7)
  20234. });