modified lib-jitsi-meet dev repo
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 746KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899
  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. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4. var RTC = require("./modules/RTC/RTC");
  5. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  6. var StreamEventTypes = require("./service/RTC/StreamEventTypes");
  7. var RTCEvents = require("./service/RTC/RTCEvents");
  8. var EventEmitter = require("events");
  9. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  10. var JitsiParticipant = require("./JitsiParticipant");
  11. var Statistics = require("./modules/statistics/statistics");
  12. /**
  13. * Creates a JitsiConference object with the given name and properties.
  14. * Note: this constructor is not a part of the public API (objects should be
  15. * created using JitsiConnection.createConference).
  16. * @param options.config properties / settings related to the conference that will be created.
  17. * @param options.name the name of the conference
  18. * @param options.connection the JitsiConnection object for this JitsiConference.
  19. * @constructor
  20. */
  21. function JitsiConference(options) {
  22. if(!options.name || options.name.toLowerCase() !== options.name) {
  23. logger.error("Invalid conference name (no conference name passed or it"
  24. + "contains invalid characters like capital letters)!");
  25. return;
  26. }
  27. this.options = options;
  28. this.connection = this.options.connection;
  29. this.xmpp = this.connection.xmpp;
  30. this.eventEmitter = new EventEmitter();
  31. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  32. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  33. this.rtc = new RTC(this.room, options);
  34. if(!options.config.disableAudioLevels)
  35. this.statistics = new Statistics();
  36. setupListeners(this);
  37. this.participants = {};
  38. this.lastActiveSpeaker = null;
  39. }
  40. /**
  41. * Joins the conference.
  42. * @param password {string} the password
  43. */
  44. JitsiConference.prototype.join = function (password) {
  45. if(this.room)
  46. this.room.join(password, this.connection.tokenPassword);
  47. }
  48. /**
  49. * Leaves the conference.
  50. */
  51. JitsiConference.prototype.leave = function () {
  52. if(this.xmpp)
  53. this.xmpp.leaveRoom(this.room.roomjid);
  54. this.room = null;
  55. }
  56. /**
  57. * Returns the local tracks.
  58. */
  59. JitsiConference.prototype.getLocalTracks = function () {
  60. if(this.rtc)
  61. return this.rtc.localStreams;
  62. };
  63. /**
  64. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  65. * in JitsiConferenceEvents.
  66. * @param eventId the event ID.
  67. * @param handler handler for the event.
  68. *
  69. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  70. */
  71. JitsiConference.prototype.on = function (eventId, handler) {
  72. if(this.eventEmitter)
  73. this.eventEmitter.on(eventId, handler);
  74. }
  75. /**
  76. * Removes event listener
  77. * @param eventId the event ID.
  78. * @param [handler] optional, the specific handler to unbind
  79. *
  80. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  81. */
  82. JitsiConference.prototype.off = function (eventId, handler) {
  83. if(this.eventEmitter)
  84. this.eventEmitter.removeListener(eventId, listener);
  85. }
  86. // Common aliases for event emitter
  87. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  88. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  89. /**
  90. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  91. * @param command {String} the name of the command
  92. * @param handler {Function} handler for the command
  93. */
  94. JitsiConference.prototype.addCommandListener = function (command, handler) {
  95. if(this.room)
  96. this.room.addPresenceListener(command, handler);
  97. }
  98. /**
  99. * Removes command listener
  100. * @param command {String} the name of the command
  101. */
  102. JitsiConference.prototype.removeCommandListener = function (command) {
  103. if(this.room)
  104. this.room.removePresenceListener(command);
  105. }
  106. /**
  107. * Sends text message to the other participants in the conference
  108. * @param message the text message.
  109. */
  110. JitsiConference.prototype.sendTextMessage = function (message) {
  111. if(this.room)
  112. this.room.sendMessage(message);
  113. }
  114. /**
  115. * Send presence command.
  116. * @param name the name of the command.
  117. * @param values Object with keys and values that will be send.
  118. **/
  119. JitsiConference.prototype.sendCommand = function (name, values) {
  120. if(this.room) {
  121. this.room.addToPresence(name, values);
  122. this.room.sendPresence();
  123. }
  124. }
  125. /**
  126. * Send presence command one time.
  127. * @param name the name of the command.
  128. * @param values Object with keys and values that will be send.
  129. **/
  130. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  131. this.sendCommand(name, values);
  132. this.removeCommand(name);
  133. }
  134. /**
  135. * Send presence command.
  136. * @param name the name of the command.
  137. * @param values Object with keys and values that will be send.
  138. * @param persistent if false the command will be sent only one time
  139. **/
  140. JitsiConference.prototype.removeCommand = function (name) {
  141. if(this.room)
  142. this.room.removeFromPresence(name);
  143. }
  144. /**
  145. * Sets the display name for this conference.
  146. * @param name the display name to set
  147. */
  148. JitsiConference.prototype.setDisplayName = function(name) {
  149. if(this.room){
  150. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  151. this.room.sendPresence();
  152. }
  153. }
  154. /**
  155. * Adds JitsiLocalTrack object to the conference.
  156. * @param track the JitsiLocalTrack object.
  157. */
  158. JitsiConference.prototype.addTrack = function (track) {
  159. this.rtc.addLocalStream(track);
  160. this.room.addStream(track.getOriginalStream(), function () {});
  161. }
  162. /**
  163. * Removes JitsiLocalTrack object to the conference.
  164. * @param track the JitsiLocalTrack object.
  165. */
  166. JitsiConference.prototype.removeTrack = function (track) {
  167. this.room.removeStream(track.getOriginalStream());
  168. this.rtc.removeLocalStream(track);
  169. }
  170. /**
  171. * Elects the participant with the given id to be the selected participant or the speaker.
  172. * @param id the identifier of the participant
  173. */
  174. JitsiConference.prototype.selectParticipant = function(participantId) {
  175. if (this.rtc) {
  176. this.rtc.selectedEndpoint(participantId);
  177. }
  178. }
  179. /**
  180. *
  181. * @param id the identifier of the participant
  182. */
  183. JitsiConference.prototype.pinParticipant = function(participantId) {
  184. if(this.rtc)
  185. this.rtc.pinEndpoint(participantId);
  186. }
  187. /**
  188. * Returns the list of participants for this conference.
  189. * @return Object a list of participant identifiers containing all conference participants.
  190. */
  191. JitsiConference.prototype.getParticipants = function() {
  192. return this.participants;
  193. }
  194. /**
  195. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  196. * null if there isn't one).
  197. * @param id the id of the participant.
  198. */
  199. JitsiConference.prototype.getParticipantById = function(id) {
  200. if(this.participants)
  201. return this.participants[id];
  202. return null;
  203. }
  204. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  205. if(this.eventEmitter)
  206. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, Strophe.getResourceFromJid(jid));
  207. // this.participants[jid] = new JitsiParticipant();
  208. }
  209. /**
  210. * Returns the local user's ID
  211. * @return {string} local user's ID
  212. */
  213. JitsiConference.prototype.myUserId = function () {
  214. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  215. }
  216. /**
  217. * Setups the listeners needed for the conference.
  218. * @param conference the conference
  219. */
  220. function setupListeners(conference) {
  221. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  222. conference.rtc.onIncommingCall(event);
  223. if(conference.statistics)
  224. conference.statistics.startRemoteStats(event.peerconnection);
  225. });
  226. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  227. conference.rtc.createRemoteStream.bind(conference.rtc));
  228. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, function (stream) {
  229. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, stream);
  230. });
  231. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, function (stream) {
  232. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  233. });
  234. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, function (stream) {
  235. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  236. conference.removeTrack(stream);
  237. });
  238. conference.rtc.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  239. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  240. });
  241. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  242. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  243. });
  244. // FIXME
  245. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  246. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  247. // });
  248. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  249. if(conference.lastActiveSpeaker !== id && conference.room) {
  250. conference.lastActiveSpeaker = id;
  251. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  252. }
  253. });
  254. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  255. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  256. });
  257. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  258. function (lastNEndpoints, endpointsEnteringLastN) {
  259. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  260. lastNEndpoints, endpointsEnteringLastN);
  261. });
  262. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  263. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT,function (jid) {
  264. conference.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, Strophe.getResourceFromJid(jid));
  265. });
  266. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (from, displayName) {
  267. conference.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  268. Strophe.getResourceFromJid(from), displayName);
  269. });
  270. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  271. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  272. });
  273. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  274. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  275. });
  276. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  277. conference.eventEmitter.emit(JitsiConferenceEvents.SETUP_FAILED);
  278. });
  279. if(conference.statistics) {
  280. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  281. var userId = null;
  282. if (ssrc === Statistics.LOCAL_JID) {
  283. userId = conference.myUserId();
  284. } else {
  285. var jid = conference.room.getJidBySSRC(ssrc);
  286. if (!jid)
  287. return;
  288. userId = Strophe.getResourceFromJid(jid);
  289. }
  290. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  291. userId, level);
  292. });
  293. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_CREATED, function (stream) {
  294. conference.statistics.startLocalStats(stream);
  295. });
  296. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  297. function () {
  298. conference.statistics.dispose();
  299. });
  300. RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  301. conference.room.updateDeviceAvailability(devices);
  302. });
  303. RTC.addListener(StreamEventTypes.TRACK_MUTE_CHANGED, function (track) {
  304. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  305. });
  306. }
  307. }
  308. module.exports = JitsiConference;
  309. }).call(this,"/JitsiConference.js")
  310. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./modules/RTC/RTC":13,"./modules/statistics/statistics":22,"./service/RTC/RTCEvents":77,"./service/RTC/StreamEventTypes":79,"./service/xmpp/XMPPEvents":84,"events":41,"jitsi-meet-logger":45}],2:[function(require,module,exports){
  311. /**
  312. * Enumeration with the errors for the conference.
  313. * @type {{string: string}}
  314. */
  315. var JitsiConferenceErrors = {
  316. /**
  317. * Indicates that a password is required in order to join the conference.
  318. */
  319. PASSWORD_REQUIRED: "conference.passwordRequired",
  320. /**
  321. * Indicates that a connection error occurred when trying to join a
  322. * conference.
  323. */
  324. CONNECTION_ERROR: "conference.connectionError",
  325. /**
  326. * Indicates that there is no available videobridge.
  327. */
  328. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  329. /**
  330. * Many more errors TBD here.
  331. */
  332. };
  333. module.exports = JitsiConferenceErrors;
  334. },{}],3:[function(require,module,exports){
  335. /**
  336. * Enumeration with the events for the conference.
  337. * @type {{string: string}}
  338. */
  339. var JitsiConferenceEvents = {
  340. /**
  341. * A new media track was added to the conference.
  342. */
  343. TRACK_ADDED: "conference.trackAdded",
  344. /**
  345. * The media track was removed to the conference.
  346. */
  347. TRACK_REMOVED: "conference.trackRemoved",
  348. /**
  349. * The active speaker was changed.
  350. */
  351. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  352. /**
  353. * A new user joinned the conference.
  354. */
  355. USER_JOINED: "conference.userJoined",
  356. /**
  357. * A user has left the conference.
  358. */
  359. USER_LEFT: "conference.userLeft",
  360. /**
  361. * New text message was received.
  362. */
  363. MESSAGE_RECEIVED: "conference.messageReceived",
  364. /**
  365. * A user has changed it display name
  366. */
  367. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  368. /**
  369. * A participant avatar has changed.
  370. */
  371. AVATAR_CHANGED: "conference.avatarChanged",
  372. /**
  373. * New connection statistics are received.
  374. */
  375. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  376. /**
  377. * The Last N set is changed.
  378. */
  379. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  380. /**
  381. * You are included / excluded in somebody's last N set
  382. */
  383. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  384. /**
  385. * A media track mute status was changed.
  386. */
  387. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  388. /**
  389. * Audio levels of a media track was changed.
  390. */
  391. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  392. /**
  393. * Indicates that the connection to the conference has been interrupted
  394. * for some reason.
  395. */
  396. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  397. /**
  398. * Indicates that the connection to the conference has been restored.
  399. */
  400. CONNECTION_RESTORED: "conference.connectionRestored",
  401. /**
  402. * Indicates that the conference setup failed.
  403. */
  404. SETUP_FAILED: "conference.setup_failed",
  405. /**
  406. * Indicates that conference has been joined.
  407. */
  408. CONFERENCE_JOINED: "conference.joined",
  409. /**
  410. * Indicates that conference has been left.
  411. */
  412. CONFERENCE_LEFT: "conference.left"
  413. };
  414. module.exports = JitsiConferenceEvents;
  415. },{}],4:[function(require,module,exports){
  416. var JitsiConference = require("./JitsiConference");
  417. var XMPP = require("./modules/xmpp/xmpp");
  418. var RandomUtil = require("./modules/util/RandomUtil");
  419. /**
  420. * Utility method that generates user name based on random hex values.
  421. * Eg. 12345678-1234-1234-12345678
  422. * @returns {string}
  423. */
  424. function generateUserName() {
  425. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  426. "-" + RandomUtil.randomHexString(4) + "-" +
  427. RandomUtil.randomHexDigit(8);
  428. }
  429. /**
  430. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  431. * JitsiConference interface.
  432. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  433. * @param tokenPassword secret generated by the provider of Jitsi Meet video conferencing services.
  434. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  435. * The format is:
  436. * passwordToken = token + "_" + roomName + "_" + ts
  437. * See doc/tokens.md for more info on how tokens are generated.
  438. * @param options Object with properties / settings related to connection with the server.
  439. * @constructor
  440. */
  441. function JitsiConnection(appID, tokenPassword, options) {
  442. this.appID = appID;
  443. this.tokenPassword = tokenPassword;
  444. this.options = options;
  445. this.xmpp = new XMPP(options);
  446. this.conferences = {};
  447. }
  448. /**
  449. * Connect the client with the server.
  450. * @param options {object} connecting options (for example authentications parameters).
  451. */
  452. JitsiConnection.prototype.connect = function (options) {
  453. if(!options)
  454. options = {};
  455. // If we have token provided use it as a password and generate random username
  456. if (this.tokenPassword) {
  457. options.password = this.tokenPassword;
  458. if (!options.id) {
  459. options.id = generateUserName() + "@" + this.options.hosts.domain;
  460. }
  461. }
  462. this.xmpp.connect(options.id, options.password);
  463. }
  464. /**
  465. * Disconnect the client from the server.
  466. */
  467. JitsiConnection.prototype.disconnect = function () {
  468. this.xmpp.disconnect();
  469. }
  470. /**
  471. * This method allows renewal of the tokens if they are expiring.
  472. * @param token the new token.
  473. */
  474. JitsiConnection.prototype.setToken = function (token) {
  475. this.token = token;
  476. }
  477. /**
  478. * Creates and joins new conference.
  479. * @param name the name of the conference; if null - a generated name will be provided from the api
  480. * @param options Object with properties / settings related to the conference that will be created.
  481. * @returns {JitsiConference} returns the new conference object.
  482. */
  483. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  484. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  485. return this.conferences[name];
  486. }
  487. /**
  488. * Subscribes the passed listener to the event.
  489. * @param event {JitsiConnectionEvents} the connection event.
  490. * @param listener {Function} the function that will receive the event
  491. */
  492. JitsiConnection.prototype.addEventListener = function (event, listener) {
  493. this.xmpp.addListener(event, listener);
  494. }
  495. /**
  496. * Unsubscribes the passed handler.
  497. * @param event {JitsiConnectionEvents} the connection event.
  498. * @param listener {Function} the function that will receive the event
  499. */
  500. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  501. this.xmpp.removeListener(event, listener);
  502. }
  503. module.exports = JitsiConnection;
  504. },{"./JitsiConference":1,"./modules/util/RandomUtil":23,"./modules/xmpp/xmpp":39}],5:[function(require,module,exports){
  505. /**
  506. * Enumeration with the errors for the connection.
  507. * @type {{string: string}}
  508. */
  509. var JitsiConnectionErrors = {
  510. /**
  511. * Indicates that a password is required in order to join the conference.
  512. */
  513. PASSWORD_REQUIRED: "connection.passwordRequired",
  514. /**
  515. * Indicates that a connection error occurred when trying to join a
  516. * conference.
  517. */
  518. CONNECTION_ERROR: "connection.connectionError",
  519. /**
  520. * Not specified errors.
  521. */
  522. OTHER_ERROR: "connection.otherError"
  523. };
  524. module.exports = JitsiConnectionErrors;
  525. },{}],6:[function(require,module,exports){
  526. /**
  527. * Enumeration with the events for the connection.
  528. * @type {{string: string}}
  529. */
  530. var JitsiConnnectionEvents = {
  531. /**
  532. * Indicates that the connection has been failed for some reason.
  533. */
  534. CONNECTION_FAILED: "connection.connectionFailed",
  535. /**
  536. * Indicates that the connection has been established.
  537. */
  538. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  539. /**
  540. * Indicates that the connection has been disconnected.
  541. */
  542. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  543. /**
  544. * Indicates that the perfomed action cannot be executed because the
  545. * connection is not in the correct state(connected, disconnected, etc.)
  546. */
  547. WRONG_STATE: "connection.wrongState"
  548. };
  549. module.exports = JitsiConnnectionEvents;
  550. },{}],7:[function(require,module,exports){
  551. var JitsiConnection = require("./JitsiConnection");
  552. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  553. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  554. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  555. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  556. var Logger = require("jitsi-meet-logger");
  557. var RTC = require("./modules/RTC/RTC");
  558. /**
  559. * Namespace for the interface of Jitsi Meet Library.
  560. */
  561. var LibJitsiMeet = {
  562. JitsiConnection: JitsiConnection,
  563. events: {
  564. conference: JitsiConferenceEvents,
  565. connection: JitsiConnectionEvents
  566. },
  567. errors: {
  568. conference: JitsiConferenceErrors,
  569. connection: JitsiConnectionErrors
  570. },
  571. logLevels: Logger.levels,
  572. init: function (options) {
  573. RTC.init(options || {});
  574. },
  575. setLogLevel: function (level) {
  576. Logger.setLogLevel(level);
  577. },
  578. /**
  579. * Creates the media tracks and returns them trough the callback.
  580. * @param options Object with properties / settings specifying the tracks which should be created.
  581. * should be created or some additional configurations about resolution for example.
  582. * @param {Array} options.devices the devices that will be requested
  583. * @param {string} options.resolution resolution constraints
  584. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  585. * type: "audio" or "video", videoType: "camera" or "desktop"}
  586. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  587. * @param {string} options.cameraDeviceId
  588. * @param {string} options.micDeviceId
  589. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  590. * or a JitsiConferenceError if rejected.
  591. */
  592. createLocalTracks: function (options) {
  593. return RTC.obtainAudioAndVideoPermissions(options || {});
  594. },
  595. isDeviceListAvailable: function () {
  596. return RTC.isDeviceListAvailable();
  597. },
  598. enumerateDevices: function (callback) {
  599. RTC.enumerateDevices(callback);
  600. }
  601. };
  602. require("es6-promise").polyfill()
  603. //Setups the promise object.
  604. window.Promise = window.Promise || require("es6-promise").Promise;
  605. module.exports = LibJitsiMeet;
  606. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./modules/RTC/RTC":13,"es6-promise":43,"jitsi-meet-logger":45}],8:[function(require,module,exports){
  607. /**
  608. * Represents a participant in (a member of) a conference.
  609. */
  610. function JitsiParticipant(id, conference, displayName){
  611. this._id = id;
  612. this._conference = conference;
  613. this._displayName = displayName;
  614. }
  615. /**
  616. * @returns {JitsiConference} The conference that this participant belongs to.
  617. */
  618. JitsiParticipant.prototype.getConference = function() {
  619. return this._conference;
  620. }
  621. /**
  622. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  623. */
  624. JitsiParticipant.prototype.getTracks = function() {
  625. }
  626. /**
  627. * @returns {String} The ID (i.e. JID) of this participant.
  628. */
  629. JitsiParticipant.prototype.getId = function() {
  630. return this._id;
  631. }
  632. /**
  633. * @returns {String} The human-readable display name of this participant.
  634. */
  635. JitsiParticipant.prototype.getDisplayName = function() {
  636. return this._displayName;
  637. }
  638. /**
  639. * @returns {Boolean} Whether this participant is a moderator or not.
  640. */
  641. JitsiParticipant.prototype.isModerator = function() {
  642. }
  643. // Gets a link to an etherpad instance advertised by the participant?
  644. //JitsiParticipant.prototype.getEtherpad = function() {
  645. //
  646. //}
  647. /*
  648. * @returns {Boolean} Whether this participant has muted their audio.
  649. */
  650. JitsiParticipant.prototype.isAudioMuted = function() {
  651. }
  652. /*
  653. * @returns {Boolean} Whether this participant has muted their video.
  654. */
  655. JitsiParticipant.prototype.isVideoMuted = function() {
  656. }
  657. /*
  658. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  659. * TODO: do we expose this or handle it internally?
  660. */
  661. JitsiParticipant.prototype.getLatestStats = function() {
  662. }
  663. /**
  664. * @returns {String} The role of this participant.
  665. */
  666. JitsiParticipant.prototype.getRole = function() {
  667. }
  668. /*
  669. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  670. */
  671. JitsiParticipant.prototype.isFocus = function() {
  672. }
  673. /*
  674. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  675. */
  676. JitsiParticipant.prototype.isRecorder = function() {
  677. }
  678. /*
  679. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  680. */
  681. JitsiParticipant.prototype.isSipGateway = function() {
  682. }
  683. /**
  684. * @returns {String} The ID for this participant's avatar.
  685. */
  686. JitsiParticipant.prototype.getAvatarId = function() {
  687. }
  688. /**
  689. * @returns {Boolean} Whether this participant is currently sharing their screen.
  690. */
  691. JitsiParticipant.prototype.isScreenSharing = function() {
  692. }
  693. /**
  694. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  695. */
  696. JitsiParticipant.prototype.getUserAgent = function() {
  697. }
  698. /**
  699. * Kicks the participant from the conference (requires certain privileges).
  700. */
  701. JitsiParticipant.prototype.kick = function() {
  702. }
  703. /**
  704. * Asks this participant to mute themselves.
  705. */
  706. JitsiParticipant.prototype.askToMute = function() {
  707. }
  708. module.exports = JitsiParticipant();
  709. },{}],9:[function(require,module,exports){
  710. (function (__filename){
  711. /* global config, APP, Strophe */
  712. // cache datachannels to avoid garbage collection
  713. // https://code.google.com/p/chromium/issues/detail?id=405545
  714. var logger = require("jitsi-meet-logger").getLogger(__filename);
  715. var RTCEvents = require("../../service/RTC/RTCEvents");
  716. /**
  717. * Binds "ondatachannel" event listener to given PeerConnection instance.
  718. * @param peerConnection WebRTC peer connection instance.
  719. */
  720. function DataChannels(peerConnection, emitter) {
  721. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  722. this.eventEmitter = emitter;
  723. this._dataChannels = [];
  724. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  725. // Although it's not a requirement to open separate channels from both bridge
  726. // and peer as single channel can be used for sending and receiving data.
  727. // So either channel opened by the bridge or the one opened here is enough
  728. // for communication with the bridge.
  729. /*var dataChannelOptions =
  730. {
  731. reliable: true
  732. };
  733. var dataChannel
  734. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  735. // Can be used only when is in open state
  736. dataChannel.onopen = function ()
  737. {
  738. dataChannel.send("My channel !!!");
  739. };
  740. dataChannel.onmessage = function (event)
  741. {
  742. var msgData = event.data;
  743. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  744. };*/
  745. };
  746. /**
  747. * Callback triggered by PeerConnection when new data channel is opened
  748. * on the bridge.
  749. * @param event the event info object.
  750. */
  751. DataChannels.prototype.onDataChannel = function (event) {
  752. var dataChannel = event.channel;
  753. var self = this;
  754. dataChannel.onopen = function () {
  755. logger.info("Data channel opened by the Videobridge!", dataChannel);
  756. // Code sample for sending string and/or binary data
  757. // Sends String message to the bridge
  758. //dataChannel.send("Hello bridge!");
  759. // Sends 12 bytes binary message to the bridge
  760. //dataChannel.send(new ArrayBuffer(12));
  761. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  762. };
  763. dataChannel.onerror = function (error) {
  764. logger.error("Data Channel Error:", error, dataChannel);
  765. };
  766. dataChannel.onmessage = function (event) {
  767. var data = event.data;
  768. // JSON
  769. var obj;
  770. try {
  771. obj = JSON.parse(data);
  772. }
  773. catch (e) {
  774. logger.error(
  775. "Failed to parse data channel message as JSON: ",
  776. data,
  777. dataChannel);
  778. }
  779. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  780. var colibriClass = obj.colibriClass;
  781. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  782. // Endpoint ID from the Videobridge.
  783. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  784. logger.info(
  785. "Data channel new dominant speaker event: ",
  786. dominantSpeakerEndpoint);
  787. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  788. }
  789. else if ("InLastNChangeEvent" === colibriClass) {
  790. var oldValue = obj.oldValue;
  791. var newValue = obj.newValue;
  792. // Make sure that oldValue and newValue are of type boolean.
  793. var type;
  794. if ((type = typeof oldValue) !== 'boolean') {
  795. if (type === 'string') {
  796. oldValue = (oldValue == "true");
  797. } else {
  798. oldValue = new Boolean(oldValue).valueOf();
  799. }
  800. }
  801. if ((type = typeof newValue) !== 'boolean') {
  802. if (type === 'string') {
  803. newValue = (newValue == "true");
  804. } else {
  805. newValue = new Boolean(newValue).valueOf();
  806. }
  807. }
  808. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  809. }
  810. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  811. // The new/latest list of last-n endpoint IDs.
  812. var lastNEndpoints = obj.lastNEndpoints;
  813. // The list of endpoint IDs which are entering the list of
  814. // last-n at this time i.e. were not in the old list of last-n
  815. // endpoint IDs.
  816. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  817. logger.info(
  818. "Data channel new last-n event: ",
  819. lastNEndpoints, endpointsEnteringLastN, obj);
  820. this.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  821. lastNEndpoints, endpointsEnteringLastN, obj);
  822. }
  823. else {
  824. logger.debug("Data channel JSON-formatted message: ", obj);
  825. }
  826. }
  827. };
  828. dataChannel.onclose = function () {
  829. logger.info("The Data Channel closed", dataChannel);
  830. var idx = self._dataChannels.indexOf(dataChannel);
  831. if (idx > -1)
  832. self._dataChannels = self._dataChannels.splice(idx, 1);
  833. };
  834. this._dataChannels.push(dataChannel);
  835. };
  836. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  837. logger.log('selected endpoint changed: ', userResource);
  838. if (this._dataChannels && this._dataChannels.length != 0) {
  839. this._dataChannels.some(function (dataChannel) {
  840. if (dataChannel.readyState == 'open') {
  841. logger.log('sending selected endpoint changed ' +
  842. 'notification to the bridge: ', userResource);
  843. dataChannel.send(JSON.stringify({
  844. 'colibriClass': 'SelectedEndpointChangedEvent',
  845. 'selectedEndpoint':
  846. (!userResource || userResource === null)?
  847. null : userResource
  848. }));
  849. return true;
  850. }
  851. });
  852. }
  853. }
  854. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  855. logger.log('pinned endpoint changed: ', userResource);
  856. if (this._dataChannels && this._dataChannels.length !== 0) {
  857. this._dataChannels.some(function (dataChannel) {
  858. if (dataChannel.readyState == 'open') {
  859. dataChannel.send(JSON.stringify({
  860. 'colibriClass': 'PinnedEndpointChangedEvent',
  861. 'pinnedEndpoint':
  862. userResource ? userResource : null
  863. }));
  864. return true;
  865. }
  866. });
  867. }
  868. }
  869. module.exports = DataChannels;
  870. }).call(this,"/modules/RTC/DataChannels.js")
  871. },{"../../service/RTC/RTCEvents":77,"jitsi-meet-logger":45}],10:[function(require,module,exports){
  872. var JitsiTrack = require("./JitsiTrack");
  873. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  874. var RTCBrowserType = require("./RTCBrowserType");
  875. /**
  876. * Represents a single media track (either audio or video).
  877. * @constructor
  878. */
  879. function JitsiLocalTrack(RTC, stream, eventEmitter, videoType,
  880. resolution)
  881. {
  882. JitsiTrack.call(this, RTC, stream,
  883. function () {
  884. if(!self.dontFireRemoveEvent)
  885. self.eventEmitter.emit(
  886. StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, self);
  887. self.dontFireRemoveEvent = false;
  888. });
  889. this.eventEmitter = eventEmitter;
  890. this.videoType = videoType;
  891. this.dontFireRemoveEvent = false;
  892. this.resolution = resolution;
  893. var self = this;
  894. }
  895. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  896. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  897. /**
  898. * Mutes / unmutes the track.
  899. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  900. */
  901. JitsiLocalTrack.prototype._setMute = function (mute) {
  902. if(!this.rtc) {
  903. console.error("Mute is not supported for streams not attached to conference!");
  904. return;
  905. }
  906. var isAudio = this.type === JitsiTrack.AUDIO;
  907. this.dontFireRemoveEvent = false;
  908. if ((window.location.protocol != "https:") ||
  909. (isAudio) || this.videoType === "screen" ||
  910. // FIXME FF does not support 'removeStream' method used to mute
  911. RTCBrowserType.isFirefox()) {
  912. var tracks = this._getTracks();
  913. for (var idx = 0; idx < tracks.length; idx++) {
  914. tracks[idx].enabled = !mute;
  915. }
  916. if(isAudio)
  917. this.rtc.room.setAudioMute(mute);
  918. else
  919. this.rtc.room.setVideoMute(mute);
  920. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  921. } else {
  922. if (mute) {
  923. this.dontFireRemoveEvent = true;
  924. this.rtc.room.removeStream(this.stream);
  925. this.rtc.stopMediaStream(this.stream);
  926. if(isAudio)
  927. this.rtc.room.setAudioMute(mute);
  928. else
  929. this.rtc.room.setVideoMute(mute);
  930. this.stream = null;
  931. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  932. //FIXME: Maybe here we should set the SRC for the containers to something
  933. } else {
  934. var self = this;
  935. var RTC = require("./RTCUtils");
  936. RTC.obtainAudioAndVideoPermissions({
  937. devices: (isAudio ? ["audio"] : ["video"]),
  938. resolution: self.resolution,
  939. dontCreateJitsiTrack: true})
  940. .then(function (streams) {
  941. var stream = null;
  942. for(var i = 0; i < streams.length; i++) {
  943. stream = streams[i];
  944. if(stream.type === self.type) {
  945. self.stream = stream.stream;
  946. self.videoType = stream.videoType;
  947. break;
  948. }
  949. }
  950. if(!stream)
  951. return;
  952. for(var i = 0; i < self.containers.length; i++)
  953. {
  954. RTC.attachMediaStream(self.containers[i], self.stream);
  955. }
  956. self.rtc.room.addStream(stream.stream,
  957. function () {
  958. if(isAudio)
  959. self.rtc.room.setAudioMute(mute);
  960. else
  961. self.rtc.room.setVideoMute(mute);
  962. self.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, self);
  963. });
  964. });
  965. }
  966. }
  967. }
  968. /**
  969. * Stops sending the media track. And removes it from the HTML.
  970. * NOTE: Works for local tracks only.
  971. */
  972. JitsiLocalTrack.prototype.stop = function () {
  973. if(!this.stream)
  974. return;
  975. if(this.rtc)
  976. this.rtc.room.removeStream(this.stream);
  977. this.rtc.stopMediaStream(this.stream);
  978. this.detach();
  979. }
  980. /**
  981. * Returns <tt>true</tt> - if the stream is muted
  982. * and <tt>false</tt> otherwise.
  983. * @returns {boolean} <tt>true</tt> - if the stream is muted
  984. * and <tt>false</tt> otherwise.
  985. */
  986. JitsiLocalTrack.prototype.isMuted = function () {
  987. if (!this.stream)
  988. return true;
  989. var tracks = [];
  990. var isAudio = this.type === JitsiTrack.AUDIO;
  991. if (isAudio) {
  992. tracks = this.stream.getAudioTracks();
  993. } else {
  994. if (!this.isActive())
  995. return true;
  996. tracks = this.stream.getVideoTracks();
  997. }
  998. for (var idx = 0; idx < tracks.length; idx++) {
  999. if(tracks[idx].enabled)
  1000. return false;
  1001. }
  1002. return true;
  1003. };
  1004. /**
  1005. * Private method. Updates rtc property of the track.
  1006. * @param rtc the rtc instance.
  1007. */
  1008. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1009. this.rtc = rtc;
  1010. };
  1011. module.exports = JitsiLocalTrack;
  1012. },{"../../service/RTC/StreamEventTypes":79,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils":15}],11:[function(require,module,exports){
  1013. var JitsiTrack = require("./JitsiTrack");
  1014. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1015. /**
  1016. * Represents a single media track (either audio or video).
  1017. * @param RTC the rtc instance.
  1018. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1019. * @param sid sid for the Media Stream
  1020. * @param ssrc ssrc for the Media Stream
  1021. * @param eventEmitter the event emitter
  1022. * @constructor
  1023. */
  1024. function JitsiRemoteTrack(RTC, data, sid, ssrc, eventEmitter) {
  1025. JitsiTrack.call(this, RTC, data.stream,
  1026. function () {
  1027. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, self);
  1028. });
  1029. this.rtc = RTC;
  1030. this.sid = sid;
  1031. this.stream = data.stream;
  1032. this.peerjid = data.peerjid;
  1033. this.videoType = data.videoType;
  1034. this.ssrc = ssrc;
  1035. this.muted = false;
  1036. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1037. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1038. this.muted = true
  1039. }
  1040. this.eventEmitter = eventEmitter;
  1041. var self = this;
  1042. }
  1043. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1044. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1045. /**
  1046. * Sets current muted status and fires an events for the change.
  1047. * @param value the muted status.
  1048. */
  1049. JitsiRemoteTrack.prototype.setMute = function (value) {
  1050. this.stream.muted = value;
  1051. this.muted = value;
  1052. this.eventEmitter.emit(StreamEventTypes.TRACK_MUTE_CHANGED, this);
  1053. };
  1054. /**
  1055. * Returns the current muted status of the track.
  1056. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1057. */
  1058. JitsiRemoteTrack.prototype.isMuted = function () {
  1059. return this.muted;
  1060. }
  1061. /**
  1062. * Returns the participant id which owns the track.
  1063. * @returns {string} the id of the participants.
  1064. */
  1065. JitsiRemoteTrack.prototype.getParitcipantId = function() {
  1066. return Strophe.getResourceFromJid(this.peerjid);
  1067. };
  1068. delete JitsiRemoteTrack.prototype.stop;
  1069. delete JitsiRemoteTrack.prototype.start;
  1070. module.exports = JitsiRemoteTrack;
  1071. },{"../../service/RTC/StreamEventTypes":79,"./JitsiTrack":12}],12:[function(require,module,exports){
  1072. var RTCBrowserType = require("./RTCBrowserType");
  1073. /**
  1074. * This implements 'onended' callback normally fired by WebRTC after the stream
  1075. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1076. * @param jitsiTrack our track object holding the original WebRTC stream object
  1077. * to which 'onended' handling will be added.
  1078. */
  1079. function implementOnEndedHandling(jitsiTrack) {
  1080. var stream = jitsiTrack.getOriginalStream();
  1081. var originalStop = stream.stop;
  1082. stream.stop = function () {
  1083. originalStop.apply(stream);
  1084. if (jitsiTrack.isActive()) {
  1085. stream.onended();
  1086. }
  1087. };
  1088. }
  1089. /**
  1090. * Adds onended/oninactive handler to a MediaStream.
  1091. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1092. * @param handler the handler
  1093. */
  1094. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1095. if (mediaStream.addEventListener) {
  1096. // chrome
  1097. if(typeof mediaStream.active !== "undefined")
  1098. mediaStream.oninactive = handler;
  1099. else
  1100. mediaStream.onended = handler;
  1101. } else {
  1102. // themasys
  1103. mediaStream.attachEvent('ended', function () {
  1104. handler(mediaStream);
  1105. });
  1106. }
  1107. }
  1108. /**
  1109. * Represents a single media track (either audio or video).
  1110. * @constructor
  1111. * @param rtc the rtc instance
  1112. * @param stream the stream
  1113. * @param streamInactiveHandler the function that will handle
  1114. * onended/oninactive events of the stream.
  1115. */
  1116. function JitsiTrack(rtc, stream, streamInactiveHandler)
  1117. {
  1118. /**
  1119. * Array with the HTML elements that are displaying the streams.
  1120. * @type {Array}
  1121. */
  1122. this.containers = [];
  1123. this.rtc = rtc;
  1124. this.stream = stream;
  1125. this.type = (this.stream.getVideoTracks().length > 0)?
  1126. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1127. if(this.type == "audio") {
  1128. this._getTracks = function () {
  1129. return this.stream.getAudioTracks();
  1130. }.bind(this);
  1131. } else {
  1132. this._getTracks = function () {
  1133. return this.stream.getVideoTracks();
  1134. }.bind(this);
  1135. }
  1136. if (RTCBrowserType.isFirefox() && this.stream) {
  1137. implementOnEndedHandling(this);
  1138. }
  1139. if(stream)
  1140. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1141. }
  1142. /**
  1143. * JitsiTrack video type.
  1144. * @type {string}
  1145. */
  1146. JitsiTrack.VIDEO = "video";
  1147. /**
  1148. * JitsiTrack audio type.
  1149. * @type {string}
  1150. */
  1151. JitsiTrack.AUDIO = "audio";
  1152. /**
  1153. * Returns the type (audio or video) of this track.
  1154. */
  1155. JitsiTrack.prototype.getType = function() {
  1156. return this.type;
  1157. };
  1158. /**
  1159. * Returns the RTCMediaStream from the browser (?).
  1160. */
  1161. JitsiTrack.prototype.getOriginalStream = function() {
  1162. return this.stream;
  1163. }
  1164. /**
  1165. * Mutes the track.
  1166. */
  1167. JitsiTrack.prototype.mute = function () {
  1168. this._setMute(true);
  1169. }
  1170. /**
  1171. * Unmutes the stream.
  1172. */
  1173. JitsiTrack.prototype.unmute = function () {
  1174. this._setMute(false);
  1175. }
  1176. /**
  1177. * Attaches the MediaStream of this track to an HTML container (?).
  1178. * Adds the container to the list of containers that are displaying the track.
  1179. * @param container the HTML container
  1180. */
  1181. JitsiTrack.prototype.attach = function (container) {
  1182. if(this.stream)
  1183. require("./RTCUtils").attachMediaStream(container, this.stream);
  1184. this.containers.push(container);
  1185. }
  1186. /**
  1187. * Removes the track from the passed HTML container.
  1188. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  1189. */
  1190. JitsiTrack.prototype.detach = function (container) {
  1191. for(var i = 0; i < this.containers.length; i++)
  1192. {
  1193. if(this.containers[i].is(container))
  1194. {
  1195. this.containers.splice(i,1);
  1196. }
  1197. if(!container)
  1198. {
  1199. this.containers[i].find(">video").remove();
  1200. }
  1201. }
  1202. if(container)
  1203. $(container).find(">video").remove();
  1204. }
  1205. /**
  1206. * Stops sending the media track. And removes it from the HTML.
  1207. * NOTE: Works for local tracks only.
  1208. */
  1209. JitsiTrack.prototype.stop = function () {
  1210. }
  1211. /**
  1212. * Returns true if this is a video track and the source of the video is a
  1213. * screen capture as opposed to a camera.
  1214. */
  1215. JitsiTrack.prototype.isScreenSharing = function(){
  1216. }
  1217. /**
  1218. * Returns id of the track.
  1219. * @returns {string} id of the track or null if this is fake track.
  1220. */
  1221. JitsiTrack.prototype.getId = function () {
  1222. var tracks = this.stream.getTracks();
  1223. if(!tracks || tracks.length === 0)
  1224. return null;
  1225. return tracks[0].id;
  1226. };
  1227. /**
  1228. * Checks whether the MediaStream is avtive/not ended.
  1229. * When there is no check for active we don't have information and so
  1230. * will return that stream is active (in case of FF).
  1231. * @returns {boolean} whether MediaStream is active.
  1232. */
  1233. JitsiTrack.prototype.isActive = function () {
  1234. if((typeof this.stream.active !== "undefined"))
  1235. return this.stream.active;
  1236. else
  1237. return true;
  1238. };
  1239. module.exports = JitsiTrack;
  1240. },{"./RTCBrowserType":14,"./RTCUtils":15}],13:[function(require,module,exports){
  1241. /* global APP */
  1242. var EventEmitter = require("events");
  1243. var RTCBrowserType = require("./RTCBrowserType");
  1244. var RTCUtils = require("./RTCUtils.js");
  1245. var JitsiTrack = require("./JitsiTrack");
  1246. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  1247. var DataChannels = require("./DataChannels");
  1248. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  1249. var DesktopSharingEventTypes
  1250. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1251. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  1252. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1253. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  1254. var desktopsharing = require("../desktopsharing/desktopsharing");
  1255. function RTC(room, options) {
  1256. this.room = room;
  1257. this.localStreams = [];
  1258. this.remoteStreams = {};
  1259. this.localAudio = null;
  1260. this.localVideo = null;
  1261. this.eventEmitter = new EventEmitter();
  1262. var self = this;
  1263. this.options = options || {};
  1264. desktopsharing.addListener(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  1265. function (stream, isUsingScreenStream, callback) {
  1266. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1267. });
  1268. room.addPresenceListener("videomuted", function (values, from) {
  1269. if(self.remoteStreams[from])
  1270. self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
  1271. });
  1272. room.addPresenceListener("audiomuted", function (values, from) {
  1273. if(self.remoteStreams[from])
  1274. self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
  1275. });
  1276. }
  1277. /**
  1278. * Creates the local MediaStreams.
  1279. * @param {Object} [options] optional parameters
  1280. * @param {Array} options.devices the devices that will be requested
  1281. * @param {string} options.resolution resolution constraints
  1282. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1283. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1284. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1285. * @param {string} options.cameraDeviceId
  1286. * @param {string} options.micDeviceId
  1287. * @returns {*} Promise object that will receive the new JitsiTracks
  1288. */
  1289. RTC.obtainAudioAndVideoPermissions = function (options) {
  1290. return RTCUtils.obtainAudioAndVideoPermissions(options);
  1291. }
  1292. RTC.prototype.onIncommingCall = function(event) {
  1293. if(this.options.config.openSctp)
  1294. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1295. for(var i = 0; i < this.localStreams.length; i++)
  1296. if(this.localStreams[i])
  1297. {
  1298. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  1299. }
  1300. }
  1301. RTC.prototype.selectedEndpoint = function (id) {
  1302. if(this.dataChannels)
  1303. this.dataChannels.handleSelectedEndpointEvent(id);
  1304. }
  1305. RTC.prototype.pinEndpoint = function (id) {
  1306. if(this.dataChannels)
  1307. this.dataChannels.handlePinnedEndpointEvent(id);
  1308. }
  1309. RTC.prototype.addListener = function (type, listener) {
  1310. this.eventEmitter.on(type, listener);
  1311. };
  1312. RTC.prototype.removeListener = function (eventType, listener) {
  1313. this.eventEmitter.removeListener(eventType, listener);
  1314. };
  1315. RTC.addListener = function (eventType, listener) {
  1316. RTCUtils.addListener(eventType, listener);
  1317. }
  1318. RTC.removeListener = function (eventType, listener) {
  1319. RTCUtils.eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1320. RTCUtils.removeListener(eventType, listener)
  1321. }
  1322. RTC.isRTCReady = function () {
  1323. return RTCUtils.isRTCReady();
  1324. }
  1325. RTC.init = function (options) {
  1326. RTCUtils.init(options || {});
  1327. }
  1328. RTC.getDeviceAvailability = function () {
  1329. return RTCUtils.getDeviceAvailability();
  1330. }
  1331. RTC.prototype.addLocalStream = function (stream) {
  1332. this.localStreams.push(stream);
  1333. stream._setRTC(this);
  1334. if (stream.type == "audio") {
  1335. this.localAudio = stream;
  1336. } else {
  1337. this.localVideo = stream;
  1338. }
  1339. };
  1340. RTC.prototype.removeLocalStream = function (stream) {
  1341. for(var i = 0; i < this.localStreams.length; i++) {
  1342. if(this.localStreams[i].getOriginalStream() === stream) {
  1343. delete this.localStreams[i];
  1344. return;
  1345. }
  1346. }
  1347. };
  1348. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1349. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  1350. this.eventEmitter);
  1351. if(!data.peerjid)
  1352. return;
  1353. var jid = data.peerjid;
  1354. if(!this.remoteStreams[jid]) {
  1355. this.remoteStreams[jid] = {};
  1356. }
  1357. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1358. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1359. return remoteStream;
  1360. };
  1361. RTC.getPCConstraints = function () {
  1362. return RTCUtils.pc_constraints;
  1363. };
  1364. RTC.getUserMediaWithConstraints = function(um, success_callback,
  1365. failure_callback, options)
  1366. {
  1367. return RTCUtils.getUserMediaWithConstraints(this, um, success_callback,
  1368. failure_callback, options);
  1369. };
  1370. RTC.attachMediaStream = function (elSelector, stream) {
  1371. RTCUtils.attachMediaStream(elSelector, stream);
  1372. };
  1373. RTC.getStreamID = function (stream) {
  1374. return RTCUtils.getStreamID(stream);
  1375. };
  1376. RTC.getVideoSrc = function (element) {
  1377. return RTCUtils.getVideoSrc(element);
  1378. };
  1379. RTC.isDeviceListAvailable = function () {
  1380. return RTCUtils.isDeviceListAvailable();
  1381. };
  1382. /**
  1383. * Allows to receive list of available cameras/microphones.
  1384. * @param {function} callback would receive array of devices as an argument
  1385. */
  1386. RTC.enumerateDevices = function (callback) {
  1387. RTCUtils.enumerateDevices(callback);
  1388. };
  1389. RTC.setVideoSrc = function (element, src) {
  1390. RTCUtils.setVideoSrc(element, src);
  1391. };
  1392. /**
  1393. * A method to handle stopping of the stream.
  1394. * One point to handle the differences in various implementations.
  1395. * @param mediaStream MediaStream object to stop.
  1396. */
  1397. RTC.stopMediaStream = function (mediaStream) {
  1398. RTCUtils.stopMediaStream(mediaStream);
  1399. };
  1400. RTC.prototype.getVideoElementName = function () {
  1401. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1402. };
  1403. RTC.prototype.dispose = function() {
  1404. };
  1405. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  1406. var stream;
  1407. if(this.remoteStreams[jid] &&
  1408. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1409. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1410. }
  1411. if(!stream)
  1412. return true;
  1413. if (value != stream.muted) {
  1414. stream.setMute(value);
  1415. return true;
  1416. }
  1417. return false;
  1418. };
  1419. RTC.prototype.switchVideoStreams = function (newStream) {
  1420. this.localVideo.stream = newStream;
  1421. this.localStreams = [];
  1422. //in firefox we have only one stream object
  1423. if (this.localAudio.getOriginalStream() != newStream)
  1424. this.localStreams.push(this.localAudio);
  1425. this.localStreams.push(this.localVideo);
  1426. };
  1427. RTC.prototype.isVideoMuted = function (jid) {
  1428. if (jid === APP.xmpp.myJid()) {
  1429. var localVideo = APP.RTC.localVideo;
  1430. return (!localVideo || localVideo.isMuted());
  1431. } else {
  1432. if (!this.remoteStreams[jid] ||
  1433. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1434. return null;
  1435. }
  1436. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1437. }
  1438. };
  1439. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1440. if (!this.localVideo)
  1441. return;
  1442. if (mute == this.localVideo.isMuted())
  1443. {
  1444. APP.xmpp.sendVideoInfoPresence(mute);
  1445. if (callback)
  1446. callback(mute);
  1447. }
  1448. else
  1449. {
  1450. this.localVideo.setMute(mute);
  1451. this.room.setVideoMute(
  1452. mute,
  1453. callback,
  1454. options);
  1455. }
  1456. };
  1457. module.exports = RTC;
  1458. },{"../../service/RTC/MediaStreamTypes":76,"../../service/RTC/RTCEvents.js":77,"../../service/RTC/StreamEventTypes.js":79,"../../service/desktopsharing/DesktopSharingEventTypes":81,"../desktopsharing/desktopsharing":18,"./DataChannels":9,"./JitsiLocalTrack.js":10,"./JitsiRemoteTrack.js":11,"./JitsiTrack":12,"./RTCBrowserType":14,"./RTCUtils.js":15,"events":41}],14:[function(require,module,exports){
  1459. var currentBrowser;
  1460. var browserVersion;
  1461. var isAndroid;
  1462. var RTCBrowserType = {
  1463. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1464. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1465. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1466. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1467. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1468. getBrowserType: function () {
  1469. return currentBrowser;
  1470. },
  1471. isChrome: function () {
  1472. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1473. },
  1474. isOpera: function () {
  1475. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1476. },
  1477. isFirefox: function () {
  1478. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1479. },
  1480. isIExplorer: function () {
  1481. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1482. },
  1483. isSafari: function () {
  1484. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1485. },
  1486. isTemasysPluginUsed: function () {
  1487. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1488. },
  1489. getFirefoxVersion: function () {
  1490. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1491. },
  1492. getChromeVersion: function () {
  1493. return RTCBrowserType.isChrome() ? browserVersion : null;
  1494. },
  1495. usesPlanB: function() {
  1496. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1497. RTCBrowserType.isTemasysPluginUsed();
  1498. },
  1499. usesUnifiedPlan: function() {
  1500. return RTCBrowserType.isFirefox();
  1501. },
  1502. /**
  1503. * Whether the browser is running on an android device.
  1504. */
  1505. isAndroid: function() {
  1506. return isAndroid;
  1507. }
  1508. // Add version getters for other browsers when needed
  1509. };
  1510. // detectOpera() must be called before detectChrome() !!!
  1511. // otherwise Opera wil be detected as Chrome
  1512. function detectChrome() {
  1513. if (navigator.webkitGetUserMedia) {
  1514. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1515. var userAgent = navigator.userAgent.toLowerCase();
  1516. // We can assume that user agent is chrome, because it's
  1517. // enforced when 'ext' streaming method is set
  1518. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1519. console.log("This appears to be Chrome, ver: " + ver);
  1520. return ver;
  1521. }
  1522. return null;
  1523. }
  1524. function detectOpera() {
  1525. var userAgent = navigator.userAgent;
  1526. if (userAgent.match(/Opera|OPR/)) {
  1527. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1528. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1529. console.info("This appears to be Opera, ver: " + version);
  1530. return version;
  1531. }
  1532. return null;
  1533. }
  1534. function detectFirefox() {
  1535. if (navigator.mozGetUserMedia) {
  1536. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1537. var version = parseInt(
  1538. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1539. console.log('This appears to be Firefox, ver: ' + version);
  1540. return version;
  1541. }
  1542. return null;
  1543. }
  1544. function detectSafari() {
  1545. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1546. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1547. console.info("This appears to be Safari");
  1548. // FIXME detect Safari version when needed
  1549. return 1;
  1550. }
  1551. return null;
  1552. }
  1553. function detectIE() {
  1554. var version;
  1555. var ua = window.navigator.userAgent;
  1556. var msie = ua.indexOf('MSIE ');
  1557. if (msie > 0) {
  1558. // IE 10 or older => return version number
  1559. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1560. }
  1561. var trident = ua.indexOf('Trident/');
  1562. if (!version && trident > 0) {
  1563. // IE 11 => return version number
  1564. var rv = ua.indexOf('rv:');
  1565. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1566. }
  1567. var edge = ua.indexOf('Edge/');
  1568. if (!version && edge > 0) {
  1569. // IE 12 => return version number
  1570. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1571. }
  1572. if (version) {
  1573. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1574. console.info("This appears to be IExplorer, ver: " + version);
  1575. }
  1576. return version;
  1577. }
  1578. function detectBrowser() {
  1579. var version;
  1580. var detectors = [
  1581. detectOpera,
  1582. detectChrome,
  1583. detectFirefox,
  1584. detectIE,
  1585. detectSafari
  1586. ];
  1587. // Try all browser detectors
  1588. for (var i = 0; i < detectors.length; i++) {
  1589. version = detectors[i]();
  1590. if (version)
  1591. return version;
  1592. }
  1593. console.error("Failed to detect browser type");
  1594. return undefined;
  1595. }
  1596. browserVersion = detectBrowser();
  1597. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1598. module.exports = RTCBrowserType;
  1599. },{}],15:[function(require,module,exports){
  1600. (function (__filename){
  1601. /* global config, require, attachMediaStream, getUserMedia */
  1602. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1603. var RTCBrowserType = require("./RTCBrowserType");
  1604. var Resolutions = require("../../service/RTC/Resolutions");
  1605. var RTCEvents = require("../../service/RTC/RTCEvents");
  1606. var AdapterJS = require("./adapter.screenshare");
  1607. var SDPUtil = require("../xmpp/SDPUtil");
  1608. var EventEmitter = require("events");
  1609. var JitsiLocalTrack = require("./JitsiLocalTrack");
  1610. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  1611. var eventEmitter = new EventEmitter();
  1612. var devices = {
  1613. audio: true,
  1614. video: true
  1615. }
  1616. var rtcReady = false;
  1617. function DummyMediaStream(id) {
  1618. this.id = id;
  1619. this.label = id;
  1620. this.stop = function() { };
  1621. this.getAudioTracks = function() { return []; };
  1622. this.getVideoTracks = function() { return []; };
  1623. }
  1624. function getPreviousResolution(resolution) {
  1625. if(!Resolutions[resolution])
  1626. return null;
  1627. var order = Resolutions[resolution].order;
  1628. var res = null;
  1629. var resName = null;
  1630. var tmp, i;
  1631. for(i in Resolutions) {
  1632. tmp = Resolutions[i];
  1633. if (!res || (res.order < tmp.order && tmp.order < order)) {
  1634. resName = i;
  1635. res = tmp;
  1636. }
  1637. }
  1638. return resName;
  1639. }
  1640. function setResolutionConstraints(constraints, resolution) {
  1641. var isAndroid = RTCBrowserType.isAndroid();
  1642. if (Resolutions[resolution]) {
  1643. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1644. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1645. }
  1646. else if (isAndroid) {
  1647. // FIXME can't remember if the purpose of this was to always request
  1648. // low resolution on Android ? if yes it should be moved up front
  1649. constraints.video.mandatory.minWidth = 320;
  1650. constraints.video.mandatory.minHeight = 240;
  1651. constraints.video.mandatory.maxFrameRate = 15;
  1652. }
  1653. if (constraints.video.mandatory.minWidth)
  1654. constraints.video.mandatory.maxWidth =
  1655. constraints.video.mandatory.minWidth;
  1656. if (constraints.video.mandatory.minHeight)
  1657. constraints.video.mandatory.maxHeight =
  1658. constraints.video.mandatory.minHeight;
  1659. }
  1660. /**
  1661. * @param {string[]} um required user media types
  1662. *
  1663. * @param {Object} [options={}] optional parameters
  1664. * @param {string} options.resolution
  1665. * @param {number} options.bandwidth
  1666. * @param {number} options.fps
  1667. * @param {string} options.desktopStream
  1668. * @param {string} options.cameraDeviceId
  1669. * @param {string} options.micDeviceId
  1670. * @param {bool} firefox_fake_device
  1671. */
  1672. function getConstraints(um, options) {
  1673. var constraints = {audio: false, video: false};
  1674. if (um.indexOf('video') >= 0) {
  1675. // same behaviour as true
  1676. constraints.video = { mandatory: {}, optional: [] };
  1677. if (options.cameraDeviceId) {
  1678. constraints.video.optional.push({
  1679. sourceId: options.cameraDeviceId
  1680. });
  1681. }
  1682. constraints.video.optional.push({ googLeakyBucket: true });
  1683. setResolutionConstraints(constraints, options.resolution);
  1684. }
  1685. if (um.indexOf('audio') >= 0) {
  1686. if (!RTCBrowserType.isFirefox()) {
  1687. // same behaviour as true
  1688. constraints.audio = { mandatory: {}, optional: []};
  1689. if (options.micDeviceId) {
  1690. constraints.audio.optional.push({
  1691. sourceId: options.micDeviceId
  1692. });
  1693. }
  1694. // if it is good enough for hangouts...
  1695. constraints.audio.optional.push(
  1696. {googEchoCancellation: true},
  1697. {googAutoGainControl: true},
  1698. {googNoiseSupression: true},
  1699. {googHighpassFilter: true},
  1700. {googNoisesuppression2: true},
  1701. {googEchoCancellation2: true},
  1702. {googAutoGainControl2: true}
  1703. );
  1704. } else {
  1705. if (options.micDeviceId) {
  1706. constraints.audio = {
  1707. mandatory: {},
  1708. optional: [{
  1709. sourceId: options.micDeviceId
  1710. }]};
  1711. } else {
  1712. constraints.audio = true;
  1713. }
  1714. }
  1715. }
  1716. if (um.indexOf('screen') >= 0) {
  1717. if (RTCBrowserType.isChrome()) {
  1718. constraints.video = {
  1719. mandatory: {
  1720. chromeMediaSource: "screen",
  1721. googLeakyBucket: true,
  1722. maxWidth: window.screen.width,
  1723. maxHeight: window.screen.height,
  1724. maxFrameRate: 3
  1725. },
  1726. optional: []
  1727. };
  1728. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1729. constraints.video = {
  1730. optional: [
  1731. {
  1732. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1733. }
  1734. ]
  1735. };
  1736. } else if (RTCBrowserType.isFirefox()) {
  1737. constraints.video = {
  1738. mozMediaSource: "window",
  1739. mediaSource: "window"
  1740. };
  1741. } else {
  1742. logger.error(
  1743. "'screen' WebRTC media source is supported only in Chrome" +
  1744. " and with Temasys plugin");
  1745. }
  1746. }
  1747. if (um.indexOf('desktop') >= 0) {
  1748. constraints.video = {
  1749. mandatory: {
  1750. chromeMediaSource: "desktop",
  1751. chromeMediaSourceId: options.desktopStream,
  1752. googLeakyBucket: true,
  1753. maxWidth: window.screen.width,
  1754. maxHeight: window.screen.height,
  1755. maxFrameRate: 3
  1756. },
  1757. optional: []
  1758. };
  1759. }
  1760. if (options.bandwidth) {
  1761. if (!constraints.video) {
  1762. //same behaviour as true
  1763. constraints.video = {mandatory: {}, optional: []};
  1764. }
  1765. constraints.video.optional.push({bandwidth: options.bandwidth});
  1766. }
  1767. if (options.fps) {
  1768. // for some cameras it might be necessary to request 30fps
  1769. // so they choose 30fps mjpg over 10fps yuy2
  1770. if (!constraints.video) {
  1771. // same behaviour as true;
  1772. constraints.video = {mandatory: {}, optional: []};
  1773. }
  1774. constraints.video.mandatory.minFrameRate = options.fps;
  1775. }
  1776. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  1777. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  1778. // this later can be a problem with some of the tests
  1779. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  1780. {
  1781. constraints.audio = true;
  1782. constraints.fake = true;
  1783. }
  1784. return constraints;
  1785. }
  1786. function setAvailableDevices(um, available) {
  1787. if (um.indexOf("video") != -1) {
  1788. devices.video = available;
  1789. }
  1790. if (um.indexOf("audio") != -1) {
  1791. devices.audio = available;
  1792. }
  1793. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  1794. }
  1795. // In case of IE we continue from 'onReady' callback
  1796. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1797. // once it is initialized.
  1798. function onReady () {
  1799. rtcReady = true;
  1800. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1801. };
  1802. /**
  1803. * Apply function with arguments if function exists.
  1804. * Do nothing if function not provided.
  1805. * @param {function} [fn] function to apply
  1806. * @param {Array} [args=[]] arguments for function
  1807. */
  1808. function maybeApply(fn, args) {
  1809. if (fn) {
  1810. fn.apply(null, args || []);
  1811. }
  1812. }
  1813. var getUserMediaStatus = {
  1814. initialized: false,
  1815. callbacks: []
  1816. };
  1817. /**
  1818. * Wrap `getUserMedia` to allow others to know if it was executed at least
  1819. * once or not. Wrapper function uses `getUserMediaStatus` object.
  1820. * @param {Function} getUserMedia native function
  1821. * @returns {Function} wrapped function
  1822. */
  1823. function wrapGetUserMedia(getUserMedia) {
  1824. return function (constraints, successCallback, errorCallback) {
  1825. getUserMedia(constraints, function (stream) {
  1826. maybeApply(successCallback, [stream]);
  1827. if (!getUserMediaStatus.initialized) {
  1828. getUserMediaStatus.initialized = true;
  1829. getUserMediaStatus.callbacks.forEach(function (callback) {
  1830. callback();
  1831. });
  1832. getUserMediaStatus.callbacks.length = 0;
  1833. }
  1834. }, function (error) {
  1835. maybeApply(errorCallback, [error]);
  1836. });
  1837. };
  1838. }
  1839. /**
  1840. * Create stub device which equals to auto selected device.
  1841. * @param {string} kind if that should be `audio` or `video` device
  1842. * @returns {Object} stub device description in `enumerateDevices` format
  1843. */
  1844. function createAutoDeviceInfo(kind) {
  1845. return {
  1846. facing: null,
  1847. label: 'Auto',
  1848. kind: kind,
  1849. deviceId: '',
  1850. groupId: null
  1851. };
  1852. }
  1853. /**
  1854. * Execute function after getUserMedia was executed at least once.
  1855. * @param {Function} callback function to execute after getUserMedia
  1856. */
  1857. function afterUserMediaInitialized(callback) {
  1858. if (getUserMediaStatus.initialized) {
  1859. callback();
  1860. } else {
  1861. getUserMediaStatus.callbacks.push(callback);
  1862. }
  1863. }
  1864. /**
  1865. * Wrapper function which makes enumerateDevices to wait
  1866. * until someone executes getUserMedia first time.
  1867. * @param {Function} enumerateDevices native function
  1868. * @returns {Funtion} wrapped function
  1869. */
  1870. function wrapEnumerateDevices(enumerateDevices) {
  1871. return function (callback) {
  1872. // enumerate devices only after initial getUserMedia
  1873. afterUserMediaInitialized(function () {
  1874. enumerateDevices().then(function (devices) {
  1875. //add auto devices
  1876. devices.unshift(
  1877. createAutoDeviceInfo('audioinput'),
  1878. createAutoDeviceInfo('videoinput')
  1879. );
  1880. callback(devices);
  1881. }, function (err) {
  1882. console.error('cannot enumerate devices: ', err);
  1883. // return only auto devices
  1884. callback([createAutoDeviceInfo('audioInput'),
  1885. createAutoDeviceInfo('videoinput')]);
  1886. });
  1887. });
  1888. };
  1889. }
  1890. /**
  1891. * Use old MediaStreamTrack to get devices list and
  1892. * convert it to enumerateDevices format.
  1893. * @param {Function} callback function to call when received devices list.
  1894. */
  1895. function enumerateDevicesThroughMediaStreamTrack (callback) {
  1896. MediaStreamTrack.getSources(function (sources) {
  1897. var devices = sources.map(function (source) {
  1898. var kind = (source.kind || '').toLowerCase();
  1899. return {
  1900. facing: source.facing || null,
  1901. label: source.label,
  1902. kind: kind ? kind + 'input': null,
  1903. deviceId: source.id,
  1904. groupId: source.groupId || null
  1905. };
  1906. });
  1907. //add auto devices
  1908. devices.unshift(
  1909. createAutoDeviceInfo('audioinput'),
  1910. createAutoDeviceInfo('videoinput')
  1911. );
  1912. callback(devices);
  1913. });
  1914. }
  1915. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1916. var RTCUtils = {
  1917. init: function (options) {
  1918. var self = this;
  1919. if (RTCBrowserType.isFirefox()) {
  1920. var FFversion = RTCBrowserType.getFirefoxVersion();
  1921. if (FFversion >= 40) {
  1922. this.peerconnection = mozRTCPeerConnection;
  1923. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  1924. this.enumerateDevices = wrapEnumerateDevices(
  1925. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  1926. );
  1927. this.pc_constraints = {};
  1928. this.attachMediaStream = function (element, stream) {
  1929. // srcObject is being standardized and FF will eventually
  1930. // support that unprefixed. FF also supports the
  1931. // "element.src = URL.createObjectURL(...)" combo, but that
  1932. // will be deprecated in favour of srcObject.
  1933. //
  1934. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1935. // https://github.com/webrtc/samples/issues/302
  1936. if (!element[0])
  1937. return;
  1938. element[0].mozSrcObject = stream;
  1939. element[0].play();
  1940. };
  1941. this.getStreamID = function (stream) {
  1942. var id = stream.id;
  1943. if (!id) {
  1944. var tracks = stream.getVideoTracks();
  1945. if (!tracks || tracks.length === 0) {
  1946. tracks = stream.getAudioTracks();
  1947. }
  1948. id = tracks[0].id;
  1949. }
  1950. return SDPUtil.filter_special_chars(id);
  1951. };
  1952. this.getVideoSrc = function (element) {
  1953. if (!element)
  1954. return null;
  1955. return element.mozSrcObject;
  1956. };
  1957. this.setVideoSrc = function (element, src) {
  1958. if (element)
  1959. element.mozSrcObject = src;
  1960. };
  1961. RTCSessionDescription = mozRTCSessionDescription;
  1962. RTCIceCandidate = mozRTCIceCandidate;
  1963. } else {
  1964. logger.error(
  1965. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1966. window.location.href = 'unsupported_browser.html';
  1967. return;
  1968. }
  1969. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1970. this.peerconnection = webkitRTCPeerConnection;
  1971. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1972. if (navigator.mediaDevices) {
  1973. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  1974. this.enumerateDevices = wrapEnumerateDevices(
  1975. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  1976. );
  1977. } else {
  1978. this.getUserMedia = getUserMedia;
  1979. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  1980. }
  1981. this.attachMediaStream = function (element, stream) {
  1982. element.attr('src', webkitURL.createObjectURL(stream));
  1983. };
  1984. this.getStreamID = function (stream) {
  1985. // streams from FF endpoints have the characters '{' and '}'
  1986. // that make jQuery choke.
  1987. return SDPUtil.filter_special_chars(stream.id);
  1988. };
  1989. this.getVideoSrc = function (element) {
  1990. if (!element)
  1991. return null;
  1992. return element.getAttribute("src");
  1993. };
  1994. this.setVideoSrc = function (element, src) {
  1995. if (element)
  1996. element.setAttribute("src", src);
  1997. };
  1998. // DTLS should now be enabled by default but..
  1999. this.pc_constraints = {'optional': [
  2000. {'DtlsSrtpKeyAgreement': 'true'}
  2001. ]};
  2002. if (options.useIPv6) {
  2003. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2004. this.pc_constraints.optional.push({googIPv6: true});
  2005. }
  2006. if (RTCBrowserType.isAndroid()) {
  2007. this.pc_constraints = {}; // disable DTLS on Android
  2008. }
  2009. if (!webkitMediaStream.prototype.getVideoTracks) {
  2010. webkitMediaStream.prototype.getVideoTracks = function () {
  2011. return this.videoTracks;
  2012. };
  2013. }
  2014. if (!webkitMediaStream.prototype.getAudioTracks) {
  2015. webkitMediaStream.prototype.getAudioTracks = function () {
  2016. return this.audioTracks;
  2017. };
  2018. }
  2019. }
  2020. // Detect IE/Safari
  2021. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2022. //AdapterJS.WebRTCPlugin.setLogLevel(
  2023. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2024. AdapterJS.webRTCReady(function (isPlugin) {
  2025. self.peerconnection = RTCPeerConnection;
  2026. self.getUserMedia = window.getUserMedia;
  2027. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2028. self.attachMediaStream = function (elSel, stream) {
  2029. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2030. return;
  2031. }
  2032. attachMediaStream(elSel[0], stream);
  2033. };
  2034. self.getStreamID = function (stream) {
  2035. var id = SDPUtil.filter_special_chars(stream.label);
  2036. return id;
  2037. };
  2038. self.getVideoSrc = function (element) {
  2039. if (!element) {
  2040. logger.warn("Attempt to get video SRC of null element");
  2041. return null;
  2042. }
  2043. var children = element.children;
  2044. for (var i = 0; i !== children.length; ++i) {
  2045. if (children[i].name === 'streamId') {
  2046. return children[i].value;
  2047. }
  2048. }
  2049. //logger.info(element.id + " SRC: " + src);
  2050. return null;
  2051. };
  2052. self.setVideoSrc = function (element, src) {
  2053. //logger.info("Set video src: ", element, src);
  2054. if (!src) {
  2055. logger.warn("Not attaching video stream, 'src' is null");
  2056. return;
  2057. }
  2058. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2059. var stream = AdapterJS.WebRTCPlugin.plugin
  2060. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2061. attachMediaStream(element, stream);
  2062. };
  2063. onReady(isPlugin);
  2064. });
  2065. } else {
  2066. try {
  2067. logger.error('Browser does not appear to be WebRTC-capable');
  2068. } catch (e) {
  2069. }
  2070. return;
  2071. }
  2072. // Call onReady() if Temasys plugin is not used
  2073. if (!RTCBrowserType.isTemasysPluginUsed()) {
  2074. onReady();
  2075. }
  2076. },
  2077. /**
  2078. * @param {string[]} um required user media types
  2079. * @param {function} success_callback
  2080. * @param {Function} failure_callback
  2081. * @param {Object} [options] optional parameters
  2082. * @param {string} options.resolution
  2083. * @param {number} options.bandwidth
  2084. * @param {number} options.fps
  2085. * @param {string} options.desktopStream
  2086. * @param {string} options.cameraDeviceId
  2087. * @param {string} options.micDeviceId
  2088. **/
  2089. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  2090. options = options || {};
  2091. resolution = options.resolution;
  2092. var constraints = getConstraints(
  2093. um, options);
  2094. logger.info("Get media constraints", constraints);
  2095. try {
  2096. this.getUserMedia(constraints,
  2097. function (stream) {
  2098. logger.log('onUserMediaSuccess');
  2099. setAvailableDevices(um, true);
  2100. success_callback(stream);
  2101. },
  2102. function (error) {
  2103. setAvailableDevices(um, false);
  2104. logger.warn('Failed to get access to local media. Error ',
  2105. error, constraints);
  2106. if (failure_callback) {
  2107. failure_callback(error, resolution);
  2108. }
  2109. });
  2110. } catch (e) {
  2111. logger.error('GUM failed: ', e);
  2112. if (failure_callback) {
  2113. failure_callback(e);
  2114. }
  2115. }
  2116. },
  2117. /**
  2118. * Creates the local MediaStreams.
  2119. * @param {Object} [options] optional parameters
  2120. * @param {Array} options.devices the devices that will be requested
  2121. * @param {string} options.resolution resolution constraints
  2122. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2123. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2124. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2125. * @param {string} options.cameraDeviceId
  2126. * @param {string} options.micDeviceId
  2127. * @returns {*} Promise object that will receive the new JitsiTracks
  2128. */
  2129. obtainAudioAndVideoPermissions: function (options) {
  2130. var self = this;
  2131. options = options || {};
  2132. return new Promise(function (resolve, reject) {
  2133. var successCallback = function (stream) {
  2134. var streams = self.successCallback(stream, options.resolution);
  2135. resolve(options.dontCreateJitsiTracks?
  2136. streams: self.createLocalTracks(streams));
  2137. };
  2138. options.devices = options.devices || ['audio', 'video'];
  2139. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  2140. // With FF/IE we can't split the stream into audio and video because FF
  2141. // doesn't support media stream constructors. So, we need to get the
  2142. // audio stream separately from the video stream using two distinct GUM
  2143. // calls. Not very user friendly :-( but we don't have many other
  2144. // options neither.
  2145. //
  2146. // Note that we pack those 2 streams in a single object and pass it to
  2147. // the successCallback method.
  2148. var obtainVideo = function (audioStream) {
  2149. self.getUserMediaWithConstraints(
  2150. ['video'],
  2151. function (videoStream) {
  2152. return successCallback({
  2153. audioStream: audioStream,
  2154. videoStream: videoStream
  2155. });
  2156. },
  2157. function (error, resolution) {
  2158. logger.error(
  2159. 'failed to obtain video stream - stop', error);
  2160. self.errorCallback(error, resolve, options);
  2161. },
  2162. {resolution: options.resolution || '360',
  2163. cameraDeviceId: options.cameraDeviceId});
  2164. };
  2165. var obtainAudio = function () {
  2166. self.getUserMediaWithConstraints(
  2167. ['audio'],
  2168. function (audioStream) {
  2169. (options.devices.indexOf('video') === -1) ||
  2170. obtainVideo(audioStream);
  2171. },
  2172. function (error) {
  2173. logger.error(
  2174. 'failed to obtain audio stream - stop', error);
  2175. self.errorCallback(error, resolve, options);
  2176. },{micDeviceId: options.micDeviceId});
  2177. };
  2178. if((options.devices.indexOf('audio') === -1))
  2179. obtainVideo(null)
  2180. else
  2181. obtainAudio();
  2182. } else {
  2183. this.getUserMediaWithConstraints(
  2184. options.devices,
  2185. function (stream) {
  2186. successCallback(stream);
  2187. },
  2188. function (error, resolution) {
  2189. self.errorCallback(error, resolve, options);
  2190. },
  2191. {resolution: options.resolution || '360',
  2192. cameraDeviceId: options.cameraDeviceId,
  2193. micDeviceId: options.micDeviceId});
  2194. }
  2195. }.bind(this));
  2196. },
  2197. /**
  2198. * Successful callback called from GUM.
  2199. * @param stream the new MediaStream
  2200. * @param resolution the resolution of the video stream.
  2201. * @returns {*}
  2202. */
  2203. successCallback: function (stream, resolution) {
  2204. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  2205. // it's an object with two properties: audioStream, videoStream.
  2206. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  2207. logger.log('got', stream, stream.getAudioTracks().length,
  2208. stream.getVideoTracks().length);
  2209. return this.handleLocalStream(stream, resolution);
  2210. },
  2211. /**
  2212. * Error callback called from GUM. Retries the GUM call with different resolutions.
  2213. * @param error the error
  2214. * @param resolve the resolve funtion that will be called on success.
  2215. * @param {Object} options with the following properties:
  2216. * @param resolution the last resolution used for GUM.
  2217. * @param dontCreateJitsiTracks if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2218. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2219. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2220. */
  2221. errorCallback: function (error, resolve, options) {
  2222. var self = this;
  2223. options = options || {};
  2224. logger.error('failed to obtain audio/video stream - trying audio only', error);
  2225. var resolution = getPreviousResolution(options.resolution);
  2226. if (typeof error == "object" && error.constraintName && error.name
  2227. && (error.name == "ConstraintNotSatisfiedError" ||
  2228. error.name == "OverconstrainedError") &&
  2229. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  2230. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  2231. && resolution) {
  2232. self.getUserMediaWithConstraints(['audio', 'video'],
  2233. function (stream) {
  2234. var streams = self.successCallback(stream, resolution);
  2235. resolve(options.dontCreateJitsiTracks? streams: self.createLocalTracks(streams));
  2236. }, function (error, resolution) {
  2237. return self.errorCallback(error, resolve,
  2238. {resolution: resolution,
  2239. dontCreateJitsiTracks: options.dontCreateJitsiTracks});
  2240. },
  2241. {resolution: options.resolution});
  2242. }
  2243. else {
  2244. self.getUserMediaWithConstraints(
  2245. ['audio'],
  2246. function (stream) {
  2247. var streams = self.successCallback(stream, resolution);
  2248. resolve(options.dontCreateJitsiTracks? streams: self.createLocalTracks(streams));
  2249. },
  2250. function (error) {
  2251. logger.error('failed to obtain audio/video stream - stop',
  2252. error);
  2253. var streams = self.successCallback(null);
  2254. resolve(options.dontCreateJitsiTracks? streams: self.createLocalTracks(streams));
  2255. }
  2256. );
  2257. }
  2258. },
  2259. /**
  2260. * Handles the newly created Media Streams.
  2261. * @param stream the new Media Streams
  2262. * @param resolution the resolution of the video stream.
  2263. * @returns {*[]} Promise object with the new Media Streams.
  2264. */
  2265. handleLocalStream: function (stream, resolution) {
  2266. var audioStream, videoStream;
  2267. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2268. // an object with two properties: audioStream, videoStream.
  2269. if (window.webkitMediaStream) {
  2270. audioStream = new webkitMediaStream();
  2271. videoStream = new webkitMediaStream();
  2272. if (stream) {
  2273. var audioTracks = stream.getAudioTracks();
  2274. for (var i = 0; i < audioTracks.length; i++) {
  2275. audioStream.addTrack(audioTracks[i]);
  2276. }
  2277. var videoTracks = stream.getVideoTracks();
  2278. for (i = 0; i < videoTracks.length; i++) {
  2279. videoStream.addTrack(videoTracks[i]);
  2280. }
  2281. }
  2282. }
  2283. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2284. if (stream && stream.audioStream)
  2285. audioStream = stream.audioStream;
  2286. else
  2287. audioStream = new DummyMediaStream("dummyAudio");
  2288. if (stream && stream.videoStream)
  2289. videoStream = stream.videoStream;
  2290. else
  2291. videoStream = new DummyMediaStream("dummyVideo");
  2292. }
  2293. return [
  2294. {stream: audioStream, type: "audio", videoType: null},
  2295. {stream: videoStream, type: "video", videoType: "camera",
  2296. resolution: resolution}
  2297. ];
  2298. },
  2299. createStream: function (stream, isVideo) {
  2300. var newStream = null;
  2301. if (window.webkitMediaStream) {
  2302. newStream = new webkitMediaStream();
  2303. if (newStream) {
  2304. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  2305. for (var i = 0; i < tracks.length; i++) {
  2306. newStream.addTrack(tracks[i]);
  2307. }
  2308. }
  2309. } else {
  2310. // FIXME: this is duplicated with 'handleLocalStream' !!!
  2311. if (stream) {
  2312. newStream = stream;
  2313. } else {
  2314. newStream =
  2315. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  2316. }
  2317. }
  2318. return newStream;
  2319. },
  2320. addListener: function (eventType, listener) {
  2321. eventEmitter.on(eventType, listener);
  2322. },
  2323. removeListener: function (eventType, listener) {
  2324. eventEmitter.removeListener(eventType, listener);
  2325. },
  2326. getDeviceAvailability: function () {
  2327. return devices;
  2328. },
  2329. isRTCReady: function () {
  2330. return rtcReady;
  2331. },
  2332. createLocalTracks: function (streams) {
  2333. var newStreams = []
  2334. for (var i = 0; i < streams.length; i++) {
  2335. var localStream = new JitsiLocalTrack(null, streams[i].stream,
  2336. eventEmitter, streams[i].videoType, streams[i].resolution);
  2337. newStreams.push(localStream);
  2338. if (streams[i].isMuted === true)
  2339. localStream.setMute(true);
  2340. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  2341. eventEmitter.emit(eventType, localStream);
  2342. }
  2343. return newStreams;
  2344. },
  2345. /**
  2346. * Checks if its possible to enumerate available cameras/micropones.
  2347. * @returns {boolean} true if available, false otherwise.
  2348. */
  2349. isDeviceListAvailable: function () {
  2350. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  2351. if (isEnumerateDevicesAvailable) {
  2352. return true;
  2353. }
  2354. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  2355. },
  2356. /**
  2357. * A method to handle stopping of the stream.
  2358. * One point to handle the differences in various implementations.
  2359. * @param mediaStream MediaStream object to stop.
  2360. */
  2361. stopMediaStream: function (mediaStream) {
  2362. mediaStream.getTracks().forEach(function (track) {
  2363. // stop() not supported with IE
  2364. if (track.stop) {
  2365. track.stop();
  2366. }
  2367. });
  2368. // leave stop for implementation still using it
  2369. if (mediaStream.stop) {
  2370. mediaStream.stop();
  2371. }
  2372. }
  2373. };
  2374. module.exports = RTCUtils;
  2375. }).call(this,"/modules/RTC/RTCUtils.js")
  2376. },{"../../service/RTC/RTCEvents":77,"../../service/RTC/Resolutions":78,"../../service/RTC/StreamEventTypes.js":79,"../xmpp/SDPUtil":30,"./JitsiLocalTrack":10,"./RTCBrowserType":14,"./adapter.screenshare":16,"events":41,"jitsi-meet-logger":45}],16:[function(require,module,exports){
  2377. (function (__filename){
  2378. /*! adapterjs - v0.12.0 - 2015-09-04 */
  2379. var console = require("jitsi-meet-logger").getLogger(__filename);
  2380. // Adapter's interface.
  2381. var AdapterJS = AdapterJS || {};
  2382. // Browserify compatibility
  2383. if(typeof exports !== 'undefined') {
  2384. module.exports = AdapterJS;
  2385. }
  2386. AdapterJS.options = AdapterJS.options || {};
  2387. // uncomment to get virtual webcams
  2388. // AdapterJS.options.getAllCams = true;
  2389. // uncomment to prevent the install prompt when the plugin in not yet installed
  2390. // AdapterJS.options.hidePluginInstallPrompt = true;
  2391. // AdapterJS version
  2392. AdapterJS.VERSION = '0.12.0';
  2393. // This function will be called when the WebRTC API is ready to be used
  2394. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  2395. // the plugin
  2396. // You may Override this function to synchronise the start of your application
  2397. // with the WebRTC API being ready.
  2398. // If you decide not to override use this synchronisation, it may result in
  2399. // an extensive CPU usage on the plugin start (once per tab loaded)
  2400. // Params:
  2401. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  2402. //
  2403. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  2404. // The WebRTC API is ready.
  2405. // Override me and do whatever you want here
  2406. };
  2407. // Sets a callback function to be called when the WebRTC interface is ready.
  2408. // The first argument is the function to callback.\
  2409. // Throws an error if the first argument is not a function
  2410. AdapterJS.webRTCReady = function (callback) {
  2411. if (typeof callback !== 'function') {
  2412. throw new Error('Callback provided is not a function');
  2413. }
  2414. if (true === AdapterJS.onwebrtcreadyDone) {
  2415. // All WebRTC interfaces are ready, just call the callback
  2416. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  2417. } else {
  2418. // will be triggered automatically when your browser/plugin is ready.
  2419. AdapterJS.onwebrtcready = callback;
  2420. }
  2421. };
  2422. // Plugin namespace
  2423. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  2424. // The object to store plugin information
  2425. AdapterJS.WebRTCPlugin.pluginInfo = {
  2426. prefix : 'Tem',
  2427. plugName : 'TemWebRTCPlugin',
  2428. pluginId : 'plugin0',
  2429. type : 'application/x-temwebrtcplugin',
  2430. onload : '__TemWebRTCReady0',
  2431. portalLink : 'http://skylink.io/plugin/',
  2432. downloadLink : null, //set below
  2433. companyName: 'Temasys'
  2434. };
  2435. if(!!navigator.platform.match(/^Mac/i)) {
  2436. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  2437. }
  2438. else if(!!navigator.platform.match(/^Win/i)) {
  2439. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  2440. }
  2441. AdapterJS.WebRTCPlugin.TAGS = {
  2442. NONE : 'none',
  2443. AUDIO : 'audio',
  2444. VIDEO : 'video'
  2445. };
  2446. // Unique identifier of each opened page
  2447. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  2448. // Use this whenever you want to call the plugin.
  2449. AdapterJS.WebRTCPlugin.plugin = null;
  2450. // Set log level for the plugin once it is ready.
  2451. // The different values are
  2452. // This is an asynchronous function that will run when the plugin is ready
  2453. AdapterJS.WebRTCPlugin.setLogLevel = null;
  2454. // Defines webrtc's JS interface according to the plugin's implementation.
  2455. // Define plugin Browsers as WebRTC Interface.
  2456. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  2457. // This function detects whether or not a plugin is installed.
  2458. // Checks if Not IE (firefox, for example), else if it's IE,
  2459. // we're running IE and do something. If not it is not supported.
  2460. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  2461. // Lets adapter.js wait until the the document is ready before injecting the plugin
  2462. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  2463. // Inject the HTML DOM object element into the page.
  2464. AdapterJS.WebRTCPlugin.injectPlugin = null;
  2465. // States of readiness that the plugin goes through when
  2466. // being injected and stated
  2467. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  2468. NONE : 0, // no plugin use
  2469. INITIALIZING : 1, // Detected need for plugin
  2470. INJECTING : 2, // Injecting plugin
  2471. INJECTED: 3, // Plugin element injected but not usable yet
  2472. READY: 4 // Plugin ready to be used
  2473. };
  2474. // Current state of the plugin. You cannot use the plugin before this is
  2475. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  2476. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  2477. // True is AdapterJS.onwebrtcready was already called, false otherwise
  2478. // Used to make sure AdapterJS.onwebrtcready is only called once
  2479. AdapterJS.onwebrtcreadyDone = false;
  2480. // Log levels for the plugin.
  2481. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  2482. /*
  2483. Log outputs are prefixed in some cases.
  2484. INFO: Information reported by the plugin.
  2485. ERROR: Errors originating from within the plugin.
  2486. WEBRTC: Error originating from within the libWebRTC library
  2487. */
  2488. // From the least verbose to the most verbose
  2489. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  2490. NONE : 'NONE',
  2491. ERROR : 'ERROR',
  2492. WARNING : 'WARNING',
  2493. INFO: 'INFO',
  2494. VERBOSE: 'VERBOSE',
  2495. SENSITIVE: 'SENSITIVE'
  2496. };
  2497. // Does a waiting check before proceeding to load the plugin.
  2498. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  2499. // This methid will use an interval to wait for the plugin to be ready.
  2500. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  2501. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  2502. // This function will be called when plugin is ready. It sends necessary
  2503. // details to the plugin.
  2504. // The function will wait for the document to be ready and the set the
  2505. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  2506. // indicating that it can start being requested.
  2507. // This function is not in the IE/Safari condition brackets so that
  2508. // TemPluginLoaded function might be called on Chrome/Firefox.
  2509. // This function is the only private function that is not encapsulated to
  2510. // allow the plugin method to be called.
  2511. __TemWebRTCReady0 = function () {
  2512. if (document.readyState === 'complete') {
  2513. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2514. AdapterJS.maybeThroughWebRTCReady();
  2515. } else {
  2516. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2517. if (document.readyState === 'complete') {
  2518. // TODO: update comments, we wait for the document to be ready
  2519. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2520. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2521. AdapterJS.maybeThroughWebRTCReady();
  2522. }
  2523. }, 100);
  2524. }
  2525. };
  2526. AdapterJS.maybeThroughWebRTCReady = function() {
  2527. if (!AdapterJS.onwebrtcreadyDone) {
  2528. AdapterJS.onwebrtcreadyDone = true;
  2529. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2530. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2531. }
  2532. }
  2533. };
  2534. // Text namespace
  2535. AdapterJS.TEXT = {
  2536. PLUGIN: {
  2537. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2538. 'to work on this browser.',
  2539. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2540. BUTTON: 'Install Now'
  2541. },
  2542. REFRESH: {
  2543. REQUIRE_REFRESH: 'Please refresh page',
  2544. BUTTON: 'Refresh Page'
  2545. }
  2546. };
  2547. // The result of ice connection states.
  2548. // - starting: Ice connection is starting.
  2549. // - checking: Ice connection is checking.
  2550. // - connected Ice connection is connected.
  2551. // - completed Ice connection is connected.
  2552. // - done Ice connection has been completed.
  2553. // - disconnected Ice connection has been disconnected.
  2554. // - failed Ice connection has failed.
  2555. // - closed Ice connection is closed.
  2556. AdapterJS._iceConnectionStates = {
  2557. starting : 'starting',
  2558. checking : 'checking',
  2559. connected : 'connected',
  2560. completed : 'connected',
  2561. done : 'completed',
  2562. disconnected : 'disconnected',
  2563. failed : 'failed',
  2564. closed : 'closed'
  2565. };
  2566. //The IceConnection states that has been fired for each peer.
  2567. AdapterJS._iceConnectionFiredStates = [];
  2568. // Check if WebRTC Interface is defined.
  2569. AdapterJS.isDefined = null;
  2570. // This function helps to retrieve the webrtc detected browser information.
  2571. // This sets:
  2572. // - webrtcDetectedBrowser: The browser agent name.
  2573. // - webrtcDetectedVersion: The browser version.
  2574. // - webrtcDetectedType: The types of webRTC support.
  2575. // - 'moz': Mozilla implementation of webRTC.
  2576. // - 'webkit': WebKit implementation of webRTC.
  2577. // - 'plugin': Using the plugin implementation.
  2578. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2579. var hasMatch, checkMatch = navigator.userAgent.match(
  2580. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2581. if (/trident/i.test(checkMatch[1])) {
  2582. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2583. webrtcDetectedBrowser = 'IE';
  2584. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2585. } else if (checkMatch[1] === 'Chrome') {
  2586. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2587. if (hasMatch !== null) {
  2588. webrtcDetectedBrowser = 'opera';
  2589. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2590. }
  2591. }
  2592. if (navigator.userAgent.indexOf('Safari')) {
  2593. if (typeof InstallTrigger !== 'undefined') {
  2594. webrtcDetectedBrowser = 'firefox';
  2595. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2596. webrtcDetectedBrowser = 'IE';
  2597. } else if (
  2598. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2599. webrtcDetectedBrowser = 'safari';
  2600. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2601. webrtcDetectedBrowser = 'opera';
  2602. } else if (!!window.chrome) {
  2603. webrtcDetectedBrowser = 'chrome';
  2604. }
  2605. }
  2606. if (!webrtcDetectedBrowser) {
  2607. webrtcDetectedVersion = checkMatch[1];
  2608. }
  2609. if (!webrtcDetectedVersion) {
  2610. try {
  2611. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2612. [navigator.appName, navigator.appVersion, '-?'];
  2613. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2614. checkMatch.splice(1, 1, hasMatch[1]);
  2615. }
  2616. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2617. } catch (error) { }
  2618. }
  2619. };
  2620. // To fix configuration as some browsers does not support
  2621. // the 'urls' attribute.
  2622. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2623. if (pcConfig === null) {
  2624. return;
  2625. }
  2626. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2627. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2628. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2629. delete pcConfig.iceServers[i].urls;
  2630. }
  2631. }
  2632. };
  2633. AdapterJS.addEvent = function(elem, evnt, func) {
  2634. if (elem.addEventListener) { // W3C DOM
  2635. elem.addEventListener(evnt, func, false);
  2636. } else if (elem.attachEvent) {// OLD IE DOM
  2637. elem.attachEvent('on'+evnt, func);
  2638. } else { // No much to do
  2639. elem[evnt] = func;
  2640. }
  2641. };
  2642. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2643. // only inject once the page is ready
  2644. if (document.readyState !== 'complete') {
  2645. return;
  2646. }
  2647. var w = window;
  2648. var i = document.createElement('iframe');
  2649. i.style.position = 'fixed';
  2650. i.style.top = '-41px';
  2651. i.style.left = 0;
  2652. i.style.right = 0;
  2653. i.style.width = '100%';
  2654. i.style.height = '40px';
  2655. i.style.backgroundColor = '#ffffe1';
  2656. i.style.border = 'none';
  2657. i.style.borderBottom = '1px solid #888888';
  2658. i.style.zIndex = '9999999';
  2659. if(typeof i.style.webkitTransition === 'string') {
  2660. i.style.webkitTransition = 'all .5s ease-out';
  2661. } else if(typeof i.style.transition === 'string') {
  2662. i.style.transition = 'all .5s ease-out';
  2663. }
  2664. document.body.appendChild(i);
  2665. c = (i.contentWindow) ? i.contentWindow :
  2666. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2667. c.document.open();
  2668. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2669. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2670. 'middle; cursor: default;">' + text + '</span>');
  2671. if(buttonText && buttonLink) {
  2672. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  2673. c.document.close();
  2674. // On click on okay
  2675. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2676. if (!!displayRefreshBar) {
  2677. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2678. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2679. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2680. }
  2681. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2682. e.preventDefault();
  2683. try {
  2684. event.cancelBubble = true;
  2685. } catch(error) { }
  2686. var pluginInstallInterval = setInterval(function(){
  2687. if(! isIE) {
  2688. navigator.plugins.refresh(false);
  2689. }
  2690. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2691. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2692. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2693. function() { // plugin now installed
  2694. clearInterval(pluginInstallInterval);
  2695. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  2696. },
  2697. function() {
  2698. // still no plugin detected, nothing to do
  2699. });
  2700. } , 500);
  2701. });
  2702. // On click on Cancel
  2703. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  2704. w.document.body.removeChild(i);
  2705. });
  2706. } else {
  2707. c.document.close();
  2708. }
  2709. setTimeout(function() {
  2710. if(typeof i.style.webkitTransform === 'string') {
  2711. i.style.webkitTransform = 'translateY(40px)';
  2712. } else if(typeof i.style.transform === 'string') {
  2713. i.style.transform = 'translateY(40px)';
  2714. } else {
  2715. i.style.top = '0px';
  2716. }
  2717. }, 300);
  2718. };
  2719. // -----------------------------------------------------------
  2720. // Detected webrtc implementation. Types are:
  2721. // - 'moz': Mozilla implementation of webRTC.
  2722. // - 'webkit': WebKit implementation of webRTC.
  2723. // - 'plugin': Using the plugin implementation.
  2724. webrtcDetectedType = null;
  2725. // Detected webrtc datachannel support. Types are:
  2726. // - 'SCTP': SCTP datachannel support.
  2727. // - 'RTP': RTP datachannel support.
  2728. webrtcDetectedDCSupport = null;
  2729. // Set the settings for creating DataChannels, MediaStream for
  2730. // Cross-browser compability.
  2731. // - This is only for SCTP based support browsers.
  2732. // the 'urls' attribute.
  2733. checkMediaDataChannelSettings =
  2734. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2735. if (typeof callback !== 'function') {
  2736. return;
  2737. }
  2738. var beOfferer = true;
  2739. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2740. // Nightly version does not require MozDontOfferDataChannel for interop
  2741. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2742. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2743. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2744. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2745. // Resends an updated version of constraints for MozDataChannel to work
  2746. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2747. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2748. try {
  2749. delete constraints.mandatory.MozDontOfferDataChannel;
  2750. } catch (error) {
  2751. console.error('Failed deleting MozDontOfferDataChannel');
  2752. console.error(error);
  2753. }
  2754. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2755. constraints.mandatory.MozDontOfferDataChannel = true;
  2756. }
  2757. if (!isLocalFirefox) {
  2758. // temporary measure to remove Moz* constraints in non Firefox browsers
  2759. for (var prop in constraints.mandatory) {
  2760. if (constraints.mandatory.hasOwnProperty(prop)) {
  2761. if (prop.indexOf('Moz') !== -1) {
  2762. delete constraints.mandatory[prop];
  2763. }
  2764. }
  2765. }
  2766. }
  2767. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2768. // interopability of the media stream
  2769. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2770. beOfferer = false;
  2771. }
  2772. callback(beOfferer, constraints);
  2773. };
  2774. // Handles the differences for all browsers ice connection state output.
  2775. // - Tested outcomes are:
  2776. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2777. // - Chrome (answerer) : 'checking' > 'connected'
  2778. // - Firefox (offerer) : 'checking' > 'connected'
  2779. // - Firefox (answerer): 'checking' > 'connected'
  2780. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2781. if (typeof callback !== 'function') {
  2782. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2783. return;
  2784. }
  2785. peerId = (peerId) ? peerId : 'peer';
  2786. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2787. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2788. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2789. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2790. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2791. }
  2792. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2793. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2794. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2795. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2796. setTimeout(function () {
  2797. AdapterJS._iceConnectionFiredStates[peerId]
  2798. .push(AdapterJS._iceConnectionStates.done);
  2799. callback(AdapterJS._iceConnectionStates.done);
  2800. }, 1000);
  2801. }
  2802. callback(iceConnectionState);
  2803. }
  2804. return;
  2805. };
  2806. // Firefox:
  2807. // - Creates iceServer from the url for Firefox.
  2808. // - Create iceServer with stun url.
  2809. // - Create iceServer with turn url.
  2810. // - Ignore the transport parameter from TURN url for FF version <=27.
  2811. // - Return null for createIceServer if transport=tcp.
  2812. // - FF 27 and above supports transport parameters in TURN url,
  2813. // - So passing in the full url to create iceServer.
  2814. // Chrome:
  2815. // - Creates iceServer from the url for Chrome M33 and earlier.
  2816. // - Create iceServer with stun url.
  2817. // - Chrome M28 & above uses below TURN format.
  2818. // Plugin:
  2819. // - Creates Ice Server for Plugin Browsers
  2820. // - If Stun - Create iceServer with stun url.
  2821. // - Else - Create iceServer with turn url
  2822. // - This is a WebRTC Function
  2823. createIceServer = null;
  2824. // Firefox:
  2825. // - Creates IceServers for Firefox
  2826. // - Use .url for FireFox.
  2827. // - Multiple Urls support
  2828. // Chrome:
  2829. // - Creates iceServers from the urls for Chrome M34 and above.
  2830. // - .urls is supported since Chrome M34.
  2831. // - Multiple Urls support
  2832. // Plugin:
  2833. // - Creates Ice Servers for Plugin Browsers
  2834. // - Multiple Urls support
  2835. // - This is a WebRTC Function
  2836. createIceServers = null;
  2837. //------------------------------------------------------------
  2838. //The RTCPeerConnection object.
  2839. RTCPeerConnection = null;
  2840. // Creates RTCSessionDescription object for Plugin Browsers
  2841. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2842. RTCSessionDescription : null;
  2843. // Creates RTCIceCandidate object for Plugin Browsers
  2844. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2845. RTCIceCandidate : null;
  2846. // Get UserMedia (only difference is the prefix).
  2847. // Code from Adam Barth.
  2848. getUserMedia = null;
  2849. // Attach a media stream to an element.
  2850. attachMediaStream = null;
  2851. // Re-attach a media stream to an element.
  2852. reattachMediaStream = null;
  2853. // Detected browser agent name. Types are:
  2854. // - 'firefox': Firefox browser.
  2855. // - 'chrome': Chrome browser.
  2856. // - 'opera': Opera browser.
  2857. // - 'safari': Safari browser.
  2858. // - 'IE' - Internet Explorer browser.
  2859. webrtcDetectedBrowser = null;
  2860. // Detected browser version.
  2861. webrtcDetectedVersion = null;
  2862. // Check for browser types and react accordingly
  2863. if (navigator.mozGetUserMedia) {
  2864. webrtcDetectedBrowser = 'firefox';
  2865. webrtcDetectedVersion = parseInt(navigator
  2866. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2867. webrtcDetectedType = 'moz';
  2868. webrtcDetectedDCSupport = 'SCTP';
  2869. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2870. AdapterJS.maybeFixConfiguration(pcConfig);
  2871. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2872. };
  2873. // The RTCSessionDescription object.
  2874. RTCSessionDescription = mozRTCSessionDescription;
  2875. window.RTCSessionDescription = RTCSessionDescription;
  2876. // The RTCIceCandidate object.
  2877. RTCIceCandidate = mozRTCIceCandidate;
  2878. window.RTCIceCandidate = RTCIceCandidate;
  2879. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2880. navigator.getUserMedia = window.getUserMedia;
  2881. // Shim for MediaStreamTrack.getSources.
  2882. MediaStreamTrack.getSources = function(successCb) {
  2883. setTimeout(function() {
  2884. var infos = [
  2885. { kind: 'audio', id: 'default', label:'', facing:'' },
  2886. { kind: 'video', id: 'default', label:'', facing:'' }
  2887. ];
  2888. successCb(infos);
  2889. }, 0);
  2890. };
  2891. createIceServer = function (url, username, password) {
  2892. var iceServer = null;
  2893. var url_parts = url.split(':');
  2894. if (url_parts[0].indexOf('stun') === 0) {
  2895. iceServer = { url : url };
  2896. } else if (url_parts[0].indexOf('turn') === 0) {
  2897. if (webrtcDetectedVersion < 27) {
  2898. var turn_url_parts = url.split('?');
  2899. if (turn_url_parts.length === 1 ||
  2900. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2901. iceServer = {
  2902. url : turn_url_parts[0],
  2903. credential : password,
  2904. username : username
  2905. };
  2906. }
  2907. } else {
  2908. iceServer = {
  2909. url : url,
  2910. credential : password,
  2911. username : username
  2912. };
  2913. }
  2914. }
  2915. return iceServer;
  2916. };
  2917. createIceServers = function (urls, username, password) {
  2918. var iceServers = [];
  2919. for (i = 0; i < urls.length; i++) {
  2920. var iceServer = createIceServer(urls[i], username, password);
  2921. if (iceServer !== null) {
  2922. iceServers.push(iceServer);
  2923. }
  2924. }
  2925. return iceServers;
  2926. };
  2927. attachMediaStream = function (element, stream) {
  2928. element.mozSrcObject = stream;
  2929. if (stream !== null)
  2930. element.play();
  2931. return element;
  2932. };
  2933. reattachMediaStream = function (to, from) {
  2934. to.mozSrcObject = from.mozSrcObject;
  2935. to.play();
  2936. return to;
  2937. };
  2938. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2939. if (!callback) {
  2940. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2941. ': 1 argument required, but only 0 present.');
  2942. }
  2943. return callback([]);
  2944. };
  2945. // Fake get{Video,Audio}Tracks
  2946. if (!MediaStream.prototype.getVideoTracks) {
  2947. MediaStream.prototype.getVideoTracks = function () {
  2948. return [];
  2949. };
  2950. }
  2951. if (!MediaStream.prototype.getAudioTracks) {
  2952. MediaStream.prototype.getAudioTracks = function () {
  2953. return [];
  2954. };
  2955. }
  2956. AdapterJS.maybeThroughWebRTCReady();
  2957. } else if (navigator.webkitGetUserMedia) {
  2958. webrtcDetectedBrowser = 'chrome';
  2959. webrtcDetectedType = 'webkit';
  2960. webrtcDetectedVersion = parseInt(navigator
  2961. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2962. // check if browser is opera 20+
  2963. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2964. if (checkIfOpera !== null) {
  2965. webrtcDetectedBrowser = 'opera';
  2966. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2967. }
  2968. // check browser datachannel support
  2969. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2970. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2971. webrtcDetectedDCSupport = 'SCTP';
  2972. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2973. webrtcDetectedVersion > 24) {
  2974. webrtcDetectedDCSupport = 'RTP';
  2975. } else {
  2976. webrtcDetectedDCSupport = '';
  2977. }
  2978. createIceServer = function (url, username, password) {
  2979. var iceServer = null;
  2980. var url_parts = url.split(':');
  2981. if (url_parts[0].indexOf('stun') === 0) {
  2982. iceServer = { 'url' : url };
  2983. } else if (url_parts[0].indexOf('turn') === 0) {
  2984. iceServer = {
  2985. 'url' : url,
  2986. 'credential' : password,
  2987. 'username' : username
  2988. };
  2989. }
  2990. return iceServer;
  2991. };
  2992. createIceServers = function (urls, username, password) {
  2993. var iceServers = [];
  2994. if (webrtcDetectedVersion >= 34) {
  2995. iceServers = {
  2996. 'urls' : urls,
  2997. 'credential' : password,
  2998. 'username' : username
  2999. };
  3000. } else {
  3001. for (i = 0; i < urls.length; i++) {
  3002. var iceServer = createIceServer(urls[i], username, password);
  3003. if (iceServer !== null) {
  3004. iceServers.push(iceServer);
  3005. }
  3006. }
  3007. }
  3008. return iceServers;
  3009. };
  3010. RTCPeerConnection = function (pcConfig, pcConstraints) {
  3011. if (webrtcDetectedVersion < 34) {
  3012. AdapterJS.maybeFixConfiguration(pcConfig);
  3013. }
  3014. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3015. };
  3016. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3017. navigator.getUserMedia = window.getUserMedia;
  3018. attachMediaStream = function (element, stream) {
  3019. if (typeof element.srcObject !== 'undefined') {
  3020. element.srcObject = stream;
  3021. } else if (typeof element.mozSrcObject !== 'undefined') {
  3022. element.mozSrcObject = stream;
  3023. } else if (typeof element.src !== 'undefined') {
  3024. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  3025. } else {
  3026. console.log('Error attaching stream to element.');
  3027. }
  3028. return element;
  3029. };
  3030. reattachMediaStream = function (to, from) {
  3031. to.src = from.src;
  3032. return to;
  3033. };
  3034. AdapterJS.maybeThroughWebRTCReady();
  3035. } else if (navigator.mediaDevices && navigator.userAgent.match(
  3036. /Edge\/(\d+).(\d+)$/)) {
  3037. webrtcDetectedBrowser = 'edge';
  3038. webrtcDetectedVersion =
  3039. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  3040. // the minimum version still supported by adapter.
  3041. webrtcMinimumVersion = 12;
  3042. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  3043. attachMediaStream = function(element, stream) {
  3044. element.srcObject = stream;
  3045. return element;
  3046. };
  3047. reattachMediaStream = function(to, from) {
  3048. to.srcObject = from.srcObject;
  3049. return to;
  3050. };
  3051. AdapterJS.maybeThroughWebRTCReady();
  3052. } else { // TRY TO USE PLUGIN
  3053. // IE 9 is not offering an implementation of console.log until you open a console
  3054. if (typeof console !== 'object' || typeof console.log !== 'function') {
  3055. /* jshint -W020 */
  3056. console = {} || console;
  3057. // Implemented based on console specs from MDN
  3058. // You may override these functions
  3059. console.log = function (arg) {};
  3060. console.info = function (arg) {};
  3061. console.error = function (arg) {};
  3062. console.dir = function (arg) {};
  3063. console.exception = function (arg) {};
  3064. console.trace = function (arg) {};
  3065. console.warn = function (arg) {};
  3066. console.count = function (arg) {};
  3067. console.debug = function (arg) {};
  3068. console.count = function (arg) {};
  3069. console.time = function (arg) {};
  3070. console.timeEnd = function (arg) {};
  3071. console.group = function (arg) {};
  3072. console.groupCollapsed = function (arg) {};
  3073. console.groupEnd = function (arg) {};
  3074. /* jshint +W020 */
  3075. }
  3076. webrtcDetectedType = 'plugin';
  3077. webrtcDetectedDCSupport = 'plugin';
  3078. AdapterJS.parseWebrtcDetectedBrowser();
  3079. isIE = webrtcDetectedBrowser === 'IE';
  3080. /* jshint -W035 */
  3081. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  3082. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3083. /* empty because it needs to prevent the function from running. */
  3084. }
  3085. };
  3086. /* jshint +W035 */
  3087. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  3088. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3089. // Call immediately if possible
  3090. // Once the plugin is set, the code will always take this path
  3091. callback();
  3092. } else {
  3093. // otherwise start a 100ms interval
  3094. var checkPluginReadyState = setInterval(function () {
  3095. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3096. clearInterval(checkPluginReadyState);
  3097. callback();
  3098. }
  3099. }, 100);
  3100. }
  3101. };
  3102. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  3103. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3104. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  3105. });
  3106. };
  3107. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  3108. // only inject once the page is ready
  3109. if (document.readyState !== 'complete') {
  3110. return;
  3111. }
  3112. // Prevent multiple injections
  3113. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  3114. return;
  3115. }
  3116. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  3117. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  3118. var frag = document.createDocumentFragment();
  3119. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  3120. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  3121. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  3122. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  3123. '<param name="pluginId" value="' +
  3124. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  3125. '<param name="windowless" value="false" /> ' +
  3126. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3127. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  3128. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  3129. // uncomment to be able to use virtual cams
  3130. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3131. '</object>';
  3132. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  3133. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  3134. }
  3135. document.body.appendChild(frag);
  3136. // Need to re-fetch the plugin
  3137. AdapterJS.WebRTCPlugin.plugin =
  3138. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  3139. } else {
  3140. // Load Plugin
  3141. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  3142. AdapterJS.WebRTCPlugin.plugin.id =
  3143. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  3144. // IE will only start the plugin if it's ACTUALLY visible
  3145. if (isIE) {
  3146. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  3147. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  3148. } else { // The size of the plugin on Safari should be 0x0px
  3149. // so that the autorisation prompt is at the top
  3150. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  3151. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  3152. }
  3153. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  3154. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  3155. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  3156. '<param name="pluginId" value="' +
  3157. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  3158. '<param name="windowless" value="false" /> ' +
  3159. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  3160. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  3161. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  3162. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  3163. }
  3164. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  3165. };
  3166. AdapterJS.WebRTCPlugin.isPluginInstalled =
  3167. function (comName, plugName, installedCb, notInstalledCb) {
  3168. if (!isIE) {
  3169. var pluginArray = navigator.plugins;
  3170. for (var i = 0; i < pluginArray.length; i++) {
  3171. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  3172. installedCb();
  3173. return;
  3174. }
  3175. }
  3176. notInstalledCb();
  3177. } else {
  3178. try {
  3179. var axo = new ActiveXObject(comName + '.' + plugName);
  3180. } catch (e) {
  3181. notInstalledCb();
  3182. return;
  3183. }
  3184. installedCb();
  3185. }
  3186. };
  3187. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  3188. if (AdapterJS.WebRTCPlugin.pluginState ===
  3189. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  3190. console.error("AdapterJS - WebRTC interface has already been defined");
  3191. return;
  3192. }
  3193. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  3194. AdapterJS.isDefined = function (variable) {
  3195. return variable !== null && variable !== undefined;
  3196. };
  3197. createIceServer = function (url, username, password) {
  3198. var iceServer = null;
  3199. var url_parts = url.split(':');
  3200. if (url_parts[0].indexOf('stun') === 0) {
  3201. iceServer = {
  3202. 'url' : url,
  3203. 'hasCredentials' : false
  3204. };
  3205. } else if (url_parts[0].indexOf('turn') === 0) {
  3206. iceServer = {
  3207. 'url' : url,
  3208. 'hasCredentials' : true,
  3209. 'credential' : password,
  3210. 'username' : username
  3211. };
  3212. }
  3213. return iceServer;
  3214. };
  3215. createIceServers = function (urls, username, password) {
  3216. var iceServers = [];
  3217. for (var i = 0; i < urls.length; ++i) {
  3218. iceServers.push(createIceServer(urls[i], username, password));
  3219. }
  3220. return iceServers;
  3221. };
  3222. RTCSessionDescription = function (info) {
  3223. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3224. return AdapterJS.WebRTCPlugin.plugin.
  3225. ConstructSessionDescription(info.type, info.sdp);
  3226. };
  3227. RTCPeerConnection = function (servers, constraints) {
  3228. var iceServers = null;
  3229. if (servers) {
  3230. iceServers = servers.iceServers;
  3231. for (var i = 0; i < iceServers.length; i++) {
  3232. if (iceServers[i].urls && !iceServers[i].url) {
  3233. iceServers[i].url = iceServers[i].urls;
  3234. }
  3235. iceServers[i].hasCredentials = AdapterJS.
  3236. isDefined(iceServers[i].username) &&
  3237. AdapterJS.isDefined(iceServers[i].credential);
  3238. }
  3239. }
  3240. var mandatory = (constraints && constraints.mandatory) ?
  3241. constraints.mandatory : null;
  3242. var optional = (constraints && constraints.optional) ?
  3243. constraints.optional : null;
  3244. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3245. return AdapterJS.WebRTCPlugin.plugin.
  3246. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  3247. iceServers, mandatory, optional);
  3248. };
  3249. MediaStreamTrack = {};
  3250. MediaStreamTrack.getSources = function (callback) {
  3251. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3252. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  3253. });
  3254. };
  3255. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  3256. constraints.audio = constraints.audio || false;
  3257. constraints.video = constraints.video || false;
  3258. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  3259. AdapterJS.WebRTCPlugin.plugin.
  3260. getUserMedia(constraints, successCallback, failureCallback);
  3261. });
  3262. };
  3263. window.navigator.getUserMedia = window.getUserMedia;
  3264. attachMediaStream = function (element, stream) {
  3265. if (!element || !element.parentNode) {
  3266. return;
  3267. }
  3268. var streamId
  3269. if (stream === null) {
  3270. streamId = '';
  3271. }
  3272. else {
  3273. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  3274. streamId = stream.id;
  3275. }
  3276. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  3277. var nodeName = element.nodeName.toLowerCase();
  3278. if (nodeName !== 'object') { // not a plugin <object> tag yet
  3279. var tag;
  3280. switch(nodeName) {
  3281. case 'audio':
  3282. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  3283. break;
  3284. case 'video':
  3285. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  3286. break;
  3287. default:
  3288. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  3289. }
  3290. var frag = document.createDocumentFragment();
  3291. var temp = document.createElement('div');
  3292. var classHTML = '';
  3293. if (element.className) {
  3294. classHTML = 'class="' + element.className + '" ';
  3295. } else if (element.attributes && element.attributes['class']) {
  3296. classHTML = 'class="' + element.attributes['class'].value + '" ';
  3297. }
  3298. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  3299. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  3300. '<param name="pluginId" value="' + elementId + '" /> ' +
  3301. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  3302. '<param name="windowless" value="true" /> ' +
  3303. '<param name="streamId" value="' + streamId + '" /> ' +
  3304. '<param name="tag" value="' + tag + '" /> ' +
  3305. '</object>';
  3306. while (temp.firstChild) {
  3307. frag.appendChild(temp.firstChild);
  3308. }
  3309. var height = '';
  3310. var width = '';
  3311. if (element.getBoundingClientRect) {
  3312. var rectObject = element.getBoundingClientRect();
  3313. width = rectObject.width + 'px';
  3314. height = rectObject.height + 'px';
  3315. }
  3316. else if (element.width) {
  3317. width = element.width;
  3318. height = element.height;
  3319. } else {
  3320. // TODO: What scenario could bring us here?
  3321. }
  3322. element.parentNode.insertBefore(frag, element);
  3323. frag = document.getElementById(elementId);
  3324. frag.width = width;
  3325. frag.height = height;
  3326. element.parentNode.removeChild(element);
  3327. } else { // already an <object> tag, just change the stream id
  3328. var children = element.children;
  3329. for (var i = 0; i !== children.length; ++i) {
  3330. if (children[i].name === 'streamId') {
  3331. children[i].value = streamId;
  3332. break;
  3333. }
  3334. }
  3335. element.setStreamId(streamId);
  3336. }
  3337. var newElement = document.getElementById(elementId);
  3338. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  3339. newElement.onplay = (element.onplay) ? element.onplay : function (arg) {};
  3340. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  3341. if (isIE) { // on IE the event needs to be plugged manually
  3342. newElement.attachEvent('onplaying', newElement.onplaying);
  3343. newElement.attachEvent('onplay', newElement.onplay);
  3344. newElement._TemOnClick = function (id) {
  3345. var arg = {
  3346. srcElement : document.getElementById(id)
  3347. };
  3348. newElement.onclick(arg);
  3349. };
  3350. }
  3351. return newElement;
  3352. };
  3353. reattachMediaStream = function (to, from) {
  3354. var stream = null;
  3355. var children = from.children;
  3356. for (var i = 0; i !== children.length; ++i) {
  3357. if (children[i].name === 'streamId') {
  3358. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3359. stream = AdapterJS.WebRTCPlugin.plugin
  3360. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  3361. break;
  3362. }
  3363. }
  3364. if (stream !== null) {
  3365. return attachMediaStream(to, stream);
  3366. } else {
  3367. console.log('Could not find the stream associated with this element');
  3368. }
  3369. };
  3370. RTCIceCandidate = function (candidate) {
  3371. if (!candidate.sdpMid) {
  3372. candidate.sdpMid = '';
  3373. }
  3374. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3375. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  3376. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  3377. );
  3378. };
  3379. // inject plugin
  3380. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  3381. AdapterJS.WebRTCPlugin.injectPlugin();
  3382. };
  3383. // This function will be called if the plugin is needed (browser different
  3384. // from Chrome or Firefox), but the plugin is not installed.
  3385. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  3386. function() {
  3387. AdapterJS.addEvent(document,
  3388. 'readystatechange',
  3389. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  3390. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  3391. };
  3392. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  3393. if (AdapterJS.options.hidePluginInstallPrompt) {
  3394. return;
  3395. }
  3396. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  3397. if(downloadLink) { // if download link
  3398. var popupString;
  3399. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  3400. popupString = 'This website requires you to install the ' +
  3401. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  3402. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  3403. ' WebRTC Plugin</a>' +
  3404. ' to work on this browser.';
  3405. } else { // no portal link, just print a generic explanation
  3406. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  3407. }
  3408. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  3409. } else { // no download link, just print a generic explanation
  3410. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  3411. }
  3412. };
  3413. // Try to detect the plugin and act accordingly
  3414. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3415. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3416. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3417. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  3418. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  3419. }
  3420. }).call(this,"/modules/RTC/adapter.screenshare.js")
  3421. },{"jitsi-meet-logger":45}],17:[function(require,module,exports){
  3422. /* global config, APP, chrome, $, alert */
  3423. /* jshint -W003 */
  3424. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3425. var AdapterJS = require("../RTC/adapter.screenshare");
  3426. var DesktopSharingEventTypes
  3427. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3428. /**
  3429. * Indicates whether the Chrome desktop sharing extension is installed.
  3430. * @type {boolean}
  3431. */
  3432. var chromeExtInstalled = false;
  3433. /**
  3434. * Indicates whether an update of the Chrome desktop sharing extension is
  3435. * required.
  3436. * @type {boolean}
  3437. */
  3438. var chromeExtUpdateRequired = false;
  3439. /**
  3440. * Whether the jidesha extension for firefox is installed for the domain on
  3441. * which we are running. Null designates an unknown value.
  3442. * @type {null}
  3443. */
  3444. var firefoxExtInstalled = null;
  3445. /**
  3446. * If set to true, detection of an installed firefox extension will be started
  3447. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3448. * user tries to enable screen sharing).
  3449. */
  3450. var reDetectFirefoxExtension = false;
  3451. /**
  3452. * Handles obtaining a stream from a screen capture on different browsers.
  3453. */
  3454. function ScreenObtainer(){
  3455. }
  3456. /**
  3457. * The EventEmitter to use to emit events.
  3458. * @type {null}
  3459. */
  3460. ScreenObtainer.prototype.eventEmitter = null;
  3461. /**
  3462. * Initializes the function used to obtain a screen capture (this.obtainStream).
  3463. *
  3464. * If the browser is Chrome, it uses the value of
  3465. * 'config.desktopSharingChromeMethod' (or 'config.desktopSharing') to * decide
  3466. * whether to use the a Chrome extension (if the value is 'ext'), use the
  3467. * "screen" media source (if the value is 'webrtc'), or disable screen capture
  3468. * (if the value is other).
  3469. * Note that for the "screen" media source to work the
  3470. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3471. */
  3472. ScreenObtainer.prototype.init = function(eventEmitter) {
  3473. this.eventEmitter = eventEmitter;
  3474. var obtainDesktopStream = null;
  3475. if (RTCBrowserType.isFirefox())
  3476. initFirefoxExtensionDetection();
  3477. // TODO remove this, config.desktopSharing is deprecated.
  3478. var chromeMethod =
  3479. (config.desktopSharingChromeMethod || config.desktopSharing);
  3480. if (RTCBrowserType.isTemasysPluginUsed()) {
  3481. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3482. console.info("Screensharing not supported by this plugin version");
  3483. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3484. console.info(
  3485. "Screensharing not available with Temasys plugin on this site");
  3486. } else {
  3487. obtainDesktopStream = obtainWebRTCScreen;
  3488. console.info("Using Temasys plugin for desktop sharing");
  3489. }
  3490. } else if (RTCBrowserType.isChrome()) {
  3491. if (chromeMethod == "ext") {
  3492. if (RTCBrowserType.getChromeVersion() >= 34) {
  3493. obtainDesktopStream = obtainScreenFromExtension;
  3494. console.info("Using Chrome extension for desktop sharing");
  3495. initChromeExtension();
  3496. } else {
  3497. console.info("Chrome extension not supported until ver 34");
  3498. }
  3499. } else if (chromeMethod == "webrtc") {
  3500. obtainDesktopStream = obtainWebRTCScreen;
  3501. console.info("Using Chrome WebRTC for desktop sharing");
  3502. }
  3503. } else if (RTCBrowserType.isFirefox()) {
  3504. if (config.desktopSharingFirefoxDisabled) {
  3505. obtainDesktopStream = null;
  3506. } else if (window.location.protocol === "http:"){
  3507. console.log("Screen sharing is not supported over HTTP. Use of " +
  3508. "HTTPS is required.");
  3509. obtainDesktopStream = null;
  3510. } else {
  3511. obtainDesktopStream = this.obtainScreenOnFirefox;
  3512. }
  3513. }
  3514. if (!obtainDesktopStream) {
  3515. console.info("Desktop sharing disabled");
  3516. }
  3517. ScreenObtainer.prototype.obtainStream = obtainDesktopStream;
  3518. };
  3519. ScreenObtainer.prototype.obtainStream = null;
  3520. /**
  3521. * Checks whether obtaining a screen capture is supported in the current
  3522. * environment.
  3523. * @returns {boolean}
  3524. */
  3525. ScreenObtainer.prototype.isSupported = function() {
  3526. return !!this.obtainStream;
  3527. };
  3528. /**
  3529. * Obtains a desktop stream using getUserMedia.
  3530. * For this to work on Chrome, the
  3531. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3532. *
  3533. * On firefox, the document's domain must be white-listed in the
  3534. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3535. * 'about:config'.
  3536. */
  3537. function obtainWebRTCScreen(streamCallback, failCallback) {
  3538. APP.RTC.getUserMediaWithConstraints(
  3539. ['screen'],
  3540. streamCallback,
  3541. failCallback
  3542. );
  3543. }
  3544. /**
  3545. * Constructs inline install URL for Chrome desktop streaming extension.
  3546. * The 'chromeExtensionId' must be defined in config.js.
  3547. * @returns {string}
  3548. */
  3549. function getWebStoreInstallUrl()
  3550. {
  3551. //TODO remove chromeExtensionId (deprecated)
  3552. return "https://chrome.google.com/webstore/detail/" +
  3553. (config.desktopSharingChromeExtId || config.chromeExtensionId);
  3554. }
  3555. /**
  3556. * Checks whether an update of the Chrome extension is required.
  3557. * @param minVersion minimal required version
  3558. * @param extVersion current extension version
  3559. * @returns {boolean}
  3560. */
  3561. function isUpdateRequired(minVersion, extVersion) {
  3562. try {
  3563. var s1 = minVersion.split('.');
  3564. var s2 = extVersion.split('.');
  3565. var len = Math.max(s1.length, s2.length);
  3566. for (var i = 0; i < len; i++) {
  3567. var n1 = 0,
  3568. n2 = 0;
  3569. if (i < s1.length)
  3570. n1 = parseInt(s1[i]);
  3571. if (i < s2.length)
  3572. n2 = parseInt(s2[i]);
  3573. if (isNaN(n1) || isNaN(n2)) {
  3574. return true;
  3575. } else if (n1 !== n2) {
  3576. return n1 > n2;
  3577. }
  3578. }
  3579. // will happen if both versions have identical numbers in
  3580. // their components (even if one of them is longer, has more components)
  3581. return false;
  3582. }
  3583. catch (e) {
  3584. console.error("Failed to parse extension version", e);
  3585. APP.UI.messageHandler.showError("dialog.error",
  3586. "dialog.detectext");
  3587. return true;
  3588. }
  3589. }
  3590. function checkChromeExtInstalled(callback) {
  3591. if (!chrome || !chrome.runtime) {
  3592. // No API, so no extension for sure
  3593. callback(false, false);
  3594. return;
  3595. }
  3596. chrome.runtime.sendMessage(
  3597. //TODO: remove chromeExtensionId (deprecated)
  3598. (config.desktopSharingChromeExtId || config.chromeExtensionId),
  3599. { getVersion: true },
  3600. function (response) {
  3601. if (!response || !response.version) {
  3602. // Communication failure - assume that no endpoint exists
  3603. console.warn(
  3604. "Extension not installed?: ", chrome.runtime.lastError);
  3605. callback(false, false);
  3606. return;
  3607. }
  3608. // Check installed extension version
  3609. var extVersion = response.version;
  3610. console.log('Extension version is: ' + extVersion);
  3611. //TODO: remove minChromeExtVersion (deprecated)
  3612. var updateRequired
  3613. = isUpdateRequired(
  3614. (config.desktopSharingChromeMinExtVersion ||
  3615. config.minChromeExtVersion),
  3616. extVersion);
  3617. callback(!updateRequired, updateRequired);
  3618. }
  3619. );
  3620. }
  3621. function doGetStreamFromExtension(streamCallback, failCallback) {
  3622. // Sends 'getStream' msg to the extension.
  3623. // Extension id must be defined in the config.
  3624. chrome.runtime.sendMessage(
  3625. //TODO: remove chromeExtensionId (deprecated)
  3626. (config.desktopSharingChromeExtId || config.chromeExtensionId),
  3627. {
  3628. getStream: true,
  3629. //TODO: remove desktopSharingSources (deprecated).
  3630. sources: (config.desktopSharingChromeSources ||
  3631. config.desktopSharingSources)
  3632. },
  3633. function (response) {
  3634. if (!response) {
  3635. failCallback(chrome.runtime.lastError);
  3636. return;
  3637. }
  3638. console.log("Response from extension: " + response);
  3639. if (response.streamId) {
  3640. APP.RTC.getUserMediaWithConstraints(
  3641. ['desktop'],
  3642. function (stream) {
  3643. streamCallback(stream);
  3644. },
  3645. failCallback,
  3646. null, null, null,
  3647. response.streamId);
  3648. } else {
  3649. failCallback("Extension failed to get the stream");
  3650. }
  3651. }
  3652. );
  3653. }
  3654. /**
  3655. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  3656. * stream for returned stream token.
  3657. */
  3658. function obtainScreenFromExtension(streamCallback, failCallback) {
  3659. if (chromeExtInstalled) {
  3660. doGetStreamFromExtension(streamCallback, failCallback);
  3661. } else {
  3662. if (chromeExtUpdateRequired) {
  3663. alert(
  3664. 'Jitsi Desktop Streamer requires update. ' +
  3665. 'Changes will take effect after next Chrome restart.');
  3666. }
  3667. chrome.webstore.install(
  3668. getWebStoreInstallUrl(),
  3669. function (arg) {
  3670. console.log("Extension installed successfully", arg);
  3671. chromeExtInstalled = true;
  3672. // We need to give a moment for the endpoint to become available
  3673. window.setTimeout(function () {
  3674. doGetStreamFromExtension(streamCallback, failCallback);
  3675. }, 500);
  3676. },
  3677. function (arg) {
  3678. console.log("Failed to install the extension", arg);
  3679. failCallback(arg);
  3680. APP.UI.messageHandler.showError("dialog.error",
  3681. "dialog.failtoinstall");
  3682. }
  3683. );
  3684. }
  3685. }
  3686. /**
  3687. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3688. * config.js to support inline installs. Host site must be selected as main
  3689. * website of published extension.
  3690. */
  3691. function initInlineInstalls()
  3692. {
  3693. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  3694. }
  3695. function initChromeExtension() {
  3696. // Initialize Chrome extension inline installs
  3697. initInlineInstalls();
  3698. // Check if extension is installed
  3699. checkChromeExtInstalled(function (installed, updateRequired) {
  3700. chromeExtInstalled = installed;
  3701. chromeExtUpdateRequired = updateRequired;
  3702. console.info(
  3703. "Chrome extension installed: " + chromeExtInstalled +
  3704. " updateRequired: " + chromeExtUpdateRequired);
  3705. });
  3706. }
  3707. /**
  3708. * Obtains a screen capture stream on Firefox.
  3709. * @param callback
  3710. * @param errorCallback
  3711. */
  3712. ScreenObtainer.prototype.obtainScreenOnFirefox =
  3713. function (callback, errorCallback) {
  3714. var self = this;
  3715. var extensionRequired = false;
  3716. if (config.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3717. (config.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3718. RTCBrowserType.getFirefoxVersion() <=
  3719. config.desktopSharingFirefoxMaxVersionExtRequired)) {
  3720. extensionRequired = true;
  3721. console.log("Jidesha extension required on firefox version " +
  3722. RTCBrowserType.getFirefoxVersion());
  3723. }
  3724. if (!extensionRequired || firefoxExtInstalled === true) {
  3725. obtainWebRTCScreen(callback, errorCallback);
  3726. return;
  3727. }
  3728. if (reDetectFirefoxExtension) {
  3729. reDetectFirefoxExtension = false;
  3730. initFirefoxExtensionDetection();
  3731. }
  3732. // Give it some (more) time to initialize, and assume lack of extension if
  3733. // it hasn't.
  3734. if (firefoxExtInstalled === null) {
  3735. window.setTimeout(
  3736. function() {
  3737. if (firefoxExtInstalled === null)
  3738. firefoxExtInstalled = false;
  3739. self.obtainScreenOnFirefox(callback, errorCallback);
  3740. },
  3741. 300
  3742. );
  3743. console.log("Waiting for detection of jidesha on firefox to finish.");
  3744. return;
  3745. }
  3746. // We need an extension and it isn't installed.
  3747. // Make sure we check for the extension when the user clicks again.
  3748. firefoxExtInstalled = null;
  3749. reDetectFirefoxExtension = true;
  3750. // Prompt the user to install the extension
  3751. this.eventEmitter.emit(DesktopSharingEventTypes.FIREFOX_EXTENSION_NEEDED,
  3752. config.desktopSharingFirefoxExtensionURL);
  3753. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3754. // stuck in 'switching' mode.
  3755. errorCallback('Firefox extension required.');
  3756. };
  3757. /**
  3758. * Starts the detection of an installed jidesha extension for firefox.
  3759. */
  3760. function initFirefoxExtensionDetection() {
  3761. if (config.desktopSharingFirefoxDisabled) {
  3762. return;
  3763. }
  3764. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3765. return;
  3766. if (!config.desktopSharingFirefoxExtId) {
  3767. firefoxExtInstalled = false;
  3768. return;
  3769. }
  3770. var img = document.createElement('img');
  3771. img.onload = function(){
  3772. console.log("Detected firefox screen sharing extension.");
  3773. firefoxExtInstalled = true;
  3774. };
  3775. img.onerror = function(){
  3776. console.log("Detected lack of firefox screen sharing extension.");
  3777. firefoxExtInstalled = false;
  3778. };
  3779. // The jidesha extension exposes an empty image file under the url:
  3780. // "chrome://EXT_ID/content/DOMAIN.png"
  3781. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3782. // DOMAIN is a domain whitelisted by the extension.
  3783. var src = "chrome://" +
  3784. (config.desktopSharingFirefoxExtId.replace('@', '.')) +
  3785. "/content/" + document.location.hostname + ".png";
  3786. img.setAttribute('src', src);
  3787. }
  3788. module.exports = ScreenObtainer;
  3789. },{"../../service/desktopsharing/DesktopSharingEventTypes":81,"../RTC/RTCBrowserType":14,"../RTC/adapter.screenshare":16}],18:[function(require,module,exports){
  3790. /* global APP, config */
  3791. var EventEmitter = require("events");
  3792. var DesktopSharingEventTypes
  3793. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3794. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3795. var RTCEvents = require("../../service/RTC/RTCEvents");
  3796. var ScreenObtainer = require("./ScreenObtainer");
  3797. /**
  3798. * Indicates that desktop stream is currently in use (for toggle purpose).
  3799. * @type {boolean}
  3800. */
  3801. var isUsingScreenStream = false;
  3802. /**
  3803. * Indicates that switch stream operation is in progress and prevent from
  3804. * triggering new events.
  3805. * @type {boolean}
  3806. */
  3807. var switchInProgress = false;
  3808. /**
  3809. * Used to obtain the screen sharing stream from the browser.
  3810. */
  3811. var screenObtainer = new ScreenObtainer();
  3812. var eventEmitter = new EventEmitter();
  3813. function streamSwitchDone() {
  3814. switchInProgress = false;
  3815. eventEmitter.emit(
  3816. DesktopSharingEventTypes.SWITCHING_DONE,
  3817. isUsingScreenStream);
  3818. }
  3819. function newStreamCreated(stream) {
  3820. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  3821. stream, isUsingScreenStream, streamSwitchDone);
  3822. }
  3823. function getVideoStreamFailed(error) {
  3824. console.error("Failed to obtain the stream to switch to", error);
  3825. switchInProgress = false;
  3826. isUsingScreenStream = false;
  3827. newStreamCreated(null);
  3828. }
  3829. function getDesktopStreamFailed(error) {
  3830. console.error("Failed to obtain the stream to switch to", error);
  3831. switchInProgress = false;
  3832. }
  3833. function onEndedHandler(stream) {
  3834. if (!switchInProgress && isUsingScreenStream) {
  3835. APP.desktopsharing.toggleScreenSharing();
  3836. }
  3837. APP.RTC.removeMediaStreamInactiveHandler(stream, onEndedHandler);
  3838. }
  3839. module.exports = {
  3840. isUsingScreenStream: function () {
  3841. return isUsingScreenStream;
  3842. },
  3843. /**
  3844. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  3845. * and enabled.
  3846. */
  3847. isDesktopSharingEnabled: function () {
  3848. return screenObtainer.isSupported();
  3849. },
  3850. init: function () {
  3851. // Called when RTC finishes initialization
  3852. APP.RTC.addListener(RTCEvents.RTC_READY,
  3853. function() {
  3854. screenObtainer.init(eventEmitter);
  3855. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  3856. });
  3857. },
  3858. addListener: function (type, listener) {
  3859. eventEmitter.on(type, listener);
  3860. },
  3861. removeListener: function (type, listener) {
  3862. eventEmitter.removeListener(type, listener);
  3863. },
  3864. /*
  3865. * Toggles screen sharing.
  3866. */
  3867. toggleScreenSharing: function () {
  3868. if (switchInProgress) {
  3869. console.warn("Switch in progress.");
  3870. return;
  3871. } else if (!screenObtainer.isSupported()) {
  3872. console.warn("Cannot toggle screen sharing: not supported.");
  3873. return;
  3874. }
  3875. switchInProgress = true;
  3876. if (!isUsingScreenStream) {
  3877. // Switch to desktop stream
  3878. screenObtainer.obtainStream(
  3879. function (stream) {
  3880. // We now use screen stream
  3881. isUsingScreenStream = true;
  3882. // Hook 'ended' event to restore camera
  3883. // when screen stream stops
  3884. APP.RTC.addMediaStreamInactiveHandler(
  3885. stream, onEndedHandler);
  3886. newStreamCreated(stream);
  3887. },
  3888. getDesktopStreamFailed);
  3889. } else {
  3890. // Disable screen stream
  3891. APP.RTC.getUserMediaWithConstraints(
  3892. ['video'],
  3893. function (stream) {
  3894. // We are now using camera stream
  3895. isUsingScreenStream = false;
  3896. newStreamCreated(stream);
  3897. },
  3898. getVideoStreamFailed,
  3899. config.resolution || '360'
  3900. );
  3901. }
  3902. },
  3903. /*
  3904. * Exports the event emitter to allow use by ScreenObtainer. Not for outside
  3905. * use.
  3906. */
  3907. eventEmitter: eventEmitter
  3908. };
  3909. },{"../../service/RTC/RTCEvents":77,"../../service/desktopsharing/DesktopSharingEventTypes":81,"../RTC/RTCBrowserType":14,"./ScreenObtainer":17,"events":41}],19:[function(require,module,exports){
  3910. (function (__filename){
  3911. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3912. function supportsLocalStorage() {
  3913. try {
  3914. return 'localStorage' in window && window.localStorage !== null;
  3915. } catch (e) {
  3916. logger.log("localstorage is not supported");
  3917. return false;
  3918. }
  3919. }
  3920. function generateUniqueId() {
  3921. function _p8() {
  3922. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3923. }
  3924. return _p8() + _p8() + _p8() + _p8();
  3925. }
  3926. function Settings(conferenceID) {
  3927. this.email = '';
  3928. this.displayName = '';
  3929. this.userId;
  3930. this.language = null;
  3931. this.confSettings = null;
  3932. this.conferenceID = conferenceID;
  3933. if (supportsLocalStorage()) {
  3934. if(!window.localStorage.getItem(conferenceID))
  3935. this.confSettings = {};
  3936. else
  3937. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3938. if(!this.confSettings.jitsiMeetId) {
  3939. this.confSettings.jitsiMeetId = generateUniqueId();
  3940. logger.log("generated id",
  3941. this.confSettings.jitsiMeetId);
  3942. this.save();
  3943. }
  3944. this.userId = this.confSettings.jitsiMeetId || '';
  3945. this.email = this.confSettings.email || '';
  3946. this.displayName = this.confSettings.displayname || '';
  3947. this.language = this.confSettings.language;
  3948. } else {
  3949. logger.log("local storage is not supported");
  3950. this.userId = generateUniqueId();
  3951. }
  3952. }
  3953. Settings.prototype.save = function () {
  3954. if(!supportsLocalStorage())
  3955. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3956. }
  3957. Settings.prototype.setDisplayName = function (newDisplayName) {
  3958. this.displayName = newDisplayName;
  3959. if(this.confSettings != null)
  3960. this.confSettings.displayname = displayName;
  3961. this.save();
  3962. return this.displayName;
  3963. },
  3964. Settings.prototype.setEmail = function (newEmail) {
  3965. this.email = newEmail;
  3966. if(this.confSettings != null)
  3967. this.confSettings.email = newEmail;
  3968. this.save();
  3969. return this.email;
  3970. },
  3971. Settings.prototype.getSettings = function () {
  3972. return {
  3973. email: this.email,
  3974. displayName: this.displayName,
  3975. uid: this.userId,
  3976. language: this.language
  3977. };
  3978. },
  3979. Settings.prototype.setLanguage = function (lang) {
  3980. this.language = lang;
  3981. if(this.confSettings != null)
  3982. this.confSettings.language = lang;
  3983. this.save();
  3984. }
  3985. module.exports = Settings;
  3986. }).call(this,"/modules/settings/Settings.js")
  3987. },{"jitsi-meet-logger":45}],20:[function(require,module,exports){
  3988. /* global config */
  3989. /**
  3990. * Provides statistics for the local stream.
  3991. */
  3992. var RTCBrowserType = require('../RTC/RTCBrowserType');
  3993. var StatisticsEvents = require('../../service/statistics/Events');
  3994. var LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  3995. /**
  3996. * Size of the webaudio analyzer buffer.
  3997. * @type {number}
  3998. */
  3999. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4000. /**
  4001. * Value of the webaudio analyzer smoothing time parameter.
  4002. * @type {number}
  4003. */
  4004. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4005. /**
  4006. * Converts time domain data array to audio level.
  4007. * @param samples the time domain data array.
  4008. * @returns {number} the audio level
  4009. */
  4010. function timeDomainDataToAudioLevel(samples) {
  4011. var maxVolume = 0;
  4012. var length = samples.length;
  4013. for (var i = 0; i < length; i++) {
  4014. if (maxVolume < samples[i])
  4015. maxVolume = samples[i];
  4016. }
  4017. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  4018. }
  4019. /**
  4020. * Animates audio level change
  4021. * @param newLevel the new audio level
  4022. * @param lastLevel the last audio level
  4023. * @returns {Number} the audio level to be set
  4024. */
  4025. function animateLevel(newLevel, lastLevel) {
  4026. var value = 0;
  4027. var diff = lastLevel - newLevel;
  4028. if(diff > 0.2) {
  4029. value = lastLevel - 0.2;
  4030. }
  4031. else if(diff < -0.4) {
  4032. value = lastLevel + 0.4;
  4033. }
  4034. else {
  4035. value = newLevel;
  4036. }
  4037. return parseFloat(value.toFixed(3));
  4038. }
  4039. /**
  4040. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  4041. *
  4042. * @param stream the local stream
  4043. * @param interval stats refresh interval given in ms.
  4044. * @constructor
  4045. */
  4046. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  4047. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4048. this.stream = stream;
  4049. this.intervalId = null;
  4050. this.intervalMilis = interval;
  4051. this.eventEmitter = eventEmitter;
  4052. this.audioLevel = 0;
  4053. this.statisticsService = statisticsService;
  4054. }
  4055. /**
  4056. * Starts the collecting the statistics.
  4057. */
  4058. LocalStatsCollector.prototype.start = function () {
  4059. if (!window.AudioContext ||
  4060. RTCBrowserType.isTemasysPluginUsed())
  4061. return;
  4062. var context = new AudioContext();
  4063. var analyser = context.createAnalyser();
  4064. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  4065. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  4066. var source = context.createMediaStreamSource(this.stream);
  4067. source.connect(analyser);
  4068. var self = this;
  4069. this.intervalId = setInterval(
  4070. function () {
  4071. var array = new Uint8Array(analyser.frequencyBinCount);
  4072. analyser.getByteTimeDomainData(array);
  4073. var audioLevel = timeDomainDataToAudioLevel(array);
  4074. if (audioLevel != self.audioLevel) {
  4075. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  4076. self.eventEmitter.emit(
  4077. StatisticsEvents.AUDIO_LEVEL,
  4078. self.statisticsService.LOCAL_JID,
  4079. self.audioLevel);
  4080. }
  4081. },
  4082. this.intervalMilis
  4083. );
  4084. };
  4085. /**
  4086. * Stops collecting the statistics.
  4087. */
  4088. LocalStatsCollector.prototype.stop = function () {
  4089. if (this.intervalId) {
  4090. clearInterval(this.intervalId);
  4091. this.intervalId = null;
  4092. }
  4093. };
  4094. module.exports = LocalStatsCollector;
  4095. },{"../../service/statistics/Events":82,"../../service/statistics/constants":83,"../RTC/RTCBrowserType":14}],21:[function(require,module,exports){
  4096. (function (__filename){
  4097. /* global require, ssrc2jid */
  4098. /* jshint -W117 */
  4099. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4100. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4101. var StatisticsEvents = require("../../service/statistics/Events");
  4102. /* Whether we support the browser we are running into for logging statistics */
  4103. var browserSupported = RTCBrowserType.isChrome() ||
  4104. RTCBrowserType.isOpera();
  4105. var keyMap = {};
  4106. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  4107. "ssrc": "ssrc",
  4108. "packetsReceived": "packetsReceived",
  4109. "packetsLost": "packetsLost",
  4110. "packetsSent": "packetsSent",
  4111. "bytesReceived": "bytesReceived",
  4112. "bytesSent": "bytesSent"
  4113. };
  4114. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  4115. "receiveBandwidth": "googAvailableReceiveBandwidth",
  4116. "sendBandwidth": "googAvailableSendBandwidth",
  4117. "remoteAddress": "googRemoteAddress",
  4118. "transportType": "googTransportType",
  4119. "localAddress": "googLocalAddress",
  4120. "activeConnection": "googActiveConnection",
  4121. "ssrc": "ssrc",
  4122. "packetsReceived": "packetsReceived",
  4123. "packetsSent": "packetsSent",
  4124. "packetsLost": "packetsLost",
  4125. "bytesReceived": "bytesReceived",
  4126. "bytesSent": "bytesSent",
  4127. "googFrameHeightReceived": "googFrameHeightReceived",
  4128. "googFrameWidthReceived": "googFrameWidthReceived",
  4129. "googFrameHeightSent": "googFrameHeightSent",
  4130. "googFrameWidthSent": "googFrameWidthSent",
  4131. "audioInputLevel": "audioInputLevel",
  4132. "audioOutputLevel": "audioOutputLevel"
  4133. };
  4134. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  4135. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  4136. /**
  4137. * Calculates packet lost percent using the number of lost packets and the
  4138. * number of all packet.
  4139. * @param lostPackets the number of lost packets
  4140. * @param totalPackets the number of all packets.
  4141. * @returns {number} packet loss percent
  4142. */
  4143. function calculatePacketLoss(lostPackets, totalPackets) {
  4144. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  4145. return 0;
  4146. return Math.round((lostPackets/totalPackets)*100);
  4147. }
  4148. function getStatValue(item, name) {
  4149. var browserType = RTCBrowserType.getBrowserType();
  4150. if (!keyMap[browserType][name])
  4151. throw "The property isn't supported!";
  4152. var key = keyMap[browserType][name];
  4153. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  4154. item.stat(key) : item[key];
  4155. }
  4156. function formatAudioLevel(audioLevel) {
  4157. return Math.min(Math.max(audioLevel, 0), 1);
  4158. }
  4159. /**
  4160. * Checks whether a certain record should be included in the logged statistics.
  4161. */
  4162. function acceptStat(reportId, reportType, statName) {
  4163. if (reportType == "googCandidatePair" && statName == "googChannelId")
  4164. return false;
  4165. if (reportType == "ssrc") {
  4166. if (statName == "googTrackId" ||
  4167. statName == "transportId" ||
  4168. statName == "ssrc")
  4169. return false;
  4170. }
  4171. return true;
  4172. }
  4173. /**
  4174. * Checks whether a certain record should be included in the logged statistics.
  4175. */
  4176. function acceptReport(id, type) {
  4177. if (id.substring(0, 15) == "googCertificate" ||
  4178. id.substring(0, 9) == "googTrack" ||
  4179. id.substring(0, 20) == "googLibjingleSession")
  4180. return false;
  4181. if (type == "googComponent")
  4182. return false;
  4183. return true;
  4184. }
  4185. /**
  4186. * Peer statistics data holder.
  4187. * @constructor
  4188. */
  4189. function PeerStats()
  4190. {
  4191. this.ssrc2Loss = {};
  4192. this.ssrc2AudioLevel = {};
  4193. this.ssrc2bitrate = {};
  4194. this.ssrc2resolution = {};
  4195. }
  4196. /**
  4197. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  4198. * represented by this instance.
  4199. * @param lossRate new packet loss rate value to be set.
  4200. */
  4201. PeerStats.prototype.setSsrcLoss = function (lossRate)
  4202. {
  4203. this.ssrc2Loss = lossRate;
  4204. };
  4205. /**
  4206. * Sets resolution that belong to the ssrc
  4207. * represented by this instance.
  4208. * @param resolution new resolution value to be set.
  4209. */
  4210. PeerStats.prototype.setSsrcResolution = function (resolution)
  4211. {
  4212. if(resolution === null && this.ssrc2resolution[ssrc])
  4213. {
  4214. delete this.ssrc2resolution[ssrc];
  4215. }
  4216. else if(resolution !== null)
  4217. this.ssrc2resolution[ssrc] = resolution;
  4218. };
  4219. /**
  4220. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  4221. * represented by this instance.
  4222. * @param ssrc audio or video RTP stream SSRC.
  4223. * @param bitrate new bitrate value to be set.
  4224. */
  4225. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  4226. {
  4227. if(this.ssrc2bitrate[ssrc])
  4228. {
  4229. this.ssrc2bitrate[ssrc].download += bitrate.download;
  4230. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  4231. }
  4232. else {
  4233. this.ssrc2bitrate[ssrc] = bitrate;
  4234. }
  4235. };
  4236. /**
  4237. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  4238. * the stream which belongs to the peer represented by this instance.
  4239. * @param ssrc RTP stream SSRC for which current audio level value will be
  4240. * updated.
  4241. * @param audioLevel the new audio level value to be set. Value is truncated to
  4242. * fit the range from 0 to 1.
  4243. */
  4244. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  4245. {
  4246. // Range limit 0 - 1
  4247. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  4248. };
  4249. function ConferenceStats() {
  4250. /**
  4251. * The bandwidth
  4252. * @type {{}}
  4253. */
  4254. this.bandwidth = {};
  4255. /**
  4256. * The bit rate
  4257. * @type {{}}
  4258. */
  4259. this.bitrate = {};
  4260. /**
  4261. * The packet loss rate
  4262. * @type {{}}
  4263. */
  4264. this.packetLoss = null;
  4265. /**
  4266. * Array with the transport information.
  4267. * @type {Array}
  4268. */
  4269. this.transport = [];
  4270. }
  4271. /**
  4272. * <tt>StatsCollector</tt> registers for stats updates of given
  4273. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  4274. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  4275. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  4276. * instance as an event source.
  4277. *
  4278. * @param peerconnection webRTC peer connection object.
  4279. * @param interval stats refresh interval given in ms.
  4280. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  4281. * called on stats update.
  4282. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  4283. * @constructor
  4284. */
  4285. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  4286. {
  4287. this.peerconnection = peerconnection;
  4288. this.baselineAudioLevelsReport = null;
  4289. this.currentAudioLevelsReport = null;
  4290. this.currentStatsReport = null;
  4291. this.baselineStatsReport = null;
  4292. this.audioLevelsIntervalId = null;
  4293. this.eventEmitter = eventEmitter;
  4294. this.config = config || {};
  4295. this.conferenceStats = new ConferenceStats();
  4296. /**
  4297. * Gather PeerConnection stats once every this many milliseconds.
  4298. */
  4299. this.GATHER_INTERVAL = 15000;
  4300. /**
  4301. * Log stats via the focus once every this many milliseconds.
  4302. */
  4303. this.LOG_INTERVAL = 60000;
  4304. /**
  4305. * Gather stats and store them in this.statsToBeLogged.
  4306. */
  4307. this.gatherStatsIntervalId = null;
  4308. /**
  4309. * Send the stats already saved in this.statsToBeLogged to be logged via
  4310. * the focus.
  4311. */
  4312. this.logStatsIntervalId = null;
  4313. /**
  4314. * Stores the statistics which will be send to the focus to be logged.
  4315. */
  4316. this.statsToBeLogged =
  4317. {
  4318. timestamps: [],
  4319. stats: {}
  4320. };
  4321. // Updates stats interval
  4322. this.audioLevelsIntervalMilis = audioLevelsInterval;
  4323. this.statsIntervalId = null;
  4324. this.statsIntervalMilis = statsInterval;
  4325. // Map of ssrcs to PeerStats
  4326. this.ssrc2stats = {};
  4327. }
  4328. module.exports = StatsCollector;
  4329. /**
  4330. * Stops stats updates.
  4331. */
  4332. StatsCollector.prototype.stop = function () {
  4333. if (this.audioLevelsIntervalId) {
  4334. clearInterval(this.audioLevelsIntervalId);
  4335. this.audioLevelsIntervalId = null;
  4336. }
  4337. if (this.statsIntervalId)
  4338. {
  4339. clearInterval(this.statsIntervalId);
  4340. this.statsIntervalId = null;
  4341. }
  4342. if(this.logStatsIntervalId)
  4343. {
  4344. clearInterval(this.logStatsIntervalId);
  4345. this.logStatsIntervalId = null;
  4346. }
  4347. if(this.gatherStatsIntervalId)
  4348. {
  4349. clearInterval(this.gatherStatsIntervalId);
  4350. this.gatherStatsIntervalId = null;
  4351. }
  4352. };
  4353. /**
  4354. * Callback passed to <tt>getStats</tt> method.
  4355. * @param error an error that occurred on <tt>getStats</tt> call.
  4356. */
  4357. StatsCollector.prototype.errorCallback = function (error)
  4358. {
  4359. logger.error("Get stats error", error);
  4360. this.stop();
  4361. };
  4362. /**
  4363. * Starts stats updates.
  4364. */
  4365. StatsCollector.prototype.start = function ()
  4366. {
  4367. var self = this;
  4368. this.audioLevelsIntervalId = setInterval(
  4369. function () {
  4370. // Interval updates
  4371. self.peerconnection.getStats(
  4372. function (report) {
  4373. var results = null;
  4374. if (!report || !report.result ||
  4375. typeof report.result != 'function') {
  4376. results = report;
  4377. }
  4378. else {
  4379. results = report.result();
  4380. }
  4381. //logger.error("Got interval report", results);
  4382. self.currentAudioLevelsReport = results;
  4383. self.processAudioLevelReport();
  4384. self.baselineAudioLevelsReport =
  4385. self.currentAudioLevelsReport;
  4386. },
  4387. self.errorCallback
  4388. );
  4389. },
  4390. self.audioLevelsIntervalMilis
  4391. );
  4392. // if (!this.config.disableStats && browserSupported) {
  4393. // this.statsIntervalId = setInterval(
  4394. // function () {
  4395. // // Interval updates
  4396. // self.peerconnection.getStats(
  4397. // function (report) {
  4398. // var results = null;
  4399. // if (!report || !report.result ||
  4400. // typeof report.result != 'function') {
  4401. // //firefox
  4402. // results = report;
  4403. // }
  4404. // else {
  4405. // //chrome
  4406. // results = report.result();
  4407. // }
  4408. // //logger.error("Got interval report", results);
  4409. // self.currentStatsReport = results;
  4410. // try {
  4411. // self.processStatsReport();
  4412. // }
  4413. // catch (e) {
  4414. // logger.error("Unsupported key:" + e, e);
  4415. // }
  4416. //
  4417. // self.baselineStatsReport = self.currentStatsReport;
  4418. // },
  4419. // self.errorCallback
  4420. // );
  4421. // },
  4422. // self.statsIntervalMilis
  4423. // );
  4424. // }
  4425. //
  4426. // if (this.config.logStats && browserSupported) {
  4427. // this.gatherStatsIntervalId = setInterval(
  4428. // function () {
  4429. // self.peerconnection.getStats(
  4430. // function (report) {
  4431. // self.addStatsToBeLogged(report.result());
  4432. // },
  4433. // function () {
  4434. // }
  4435. // );
  4436. // },
  4437. // this.GATHER_INTERVAL
  4438. // );
  4439. //
  4440. // this.logStatsIntervalId = setInterval(
  4441. // function() { self.logStats(); },
  4442. // this.LOG_INTERVAL);
  4443. // }
  4444. };
  4445. /**
  4446. * Converts the stats to the format used for logging, and saves the data in
  4447. * this.statsToBeLogged.
  4448. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  4449. */
  4450. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  4451. var self = this;
  4452. var num_records = this.statsToBeLogged.timestamps.length;
  4453. this.statsToBeLogged.timestamps.push(new Date().getTime());
  4454. reports.map(function (report) {
  4455. if (!acceptReport(report.id, report.type))
  4456. return;
  4457. var stat = self.statsToBeLogged.stats[report.id];
  4458. if (!stat) {
  4459. stat = self.statsToBeLogged.stats[report.id] = {};
  4460. }
  4461. stat.type = report.type;
  4462. report.names().map(function (name) {
  4463. if (!acceptStat(report.id, report.type, name))
  4464. return;
  4465. var values = stat[name];
  4466. if (!values) {
  4467. values = stat[name] = [];
  4468. }
  4469. while (values.length < num_records) {
  4470. values.push(null);
  4471. }
  4472. values.push(report.stat(name));
  4473. });
  4474. });
  4475. };
  4476. //FIXME:
  4477. //StatsCollector.prototype.logStats = function () {
  4478. //
  4479. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  4480. // return;
  4481. // // Reset the stats
  4482. // this.statsToBeLogged.stats = {};
  4483. // this.statsToBeLogged.timestamps = [];
  4484. //};
  4485. /**
  4486. * Stats processing logic.
  4487. */
  4488. StatsCollector.prototype.processStatsReport = function () {
  4489. if (!this.baselineStatsReport) {
  4490. return;
  4491. }
  4492. for (var idx in this.currentStatsReport) {
  4493. var now = this.currentStatsReport[idx];
  4494. try {
  4495. if (getStatValue(now, 'receiveBandwidth') ||
  4496. getStatValue(now, 'sendBandwidth')) {
  4497. this.conferenceStats.bandwidth = {
  4498. "download": Math.round(
  4499. (getStatValue(now, 'receiveBandwidth')) / 1000),
  4500. "upload": Math.round(
  4501. (getStatValue(now, 'sendBandwidth')) / 1000)
  4502. };
  4503. }
  4504. }
  4505. catch(e){/*not supported*/}
  4506. if(now.type == 'googCandidatePair')
  4507. {
  4508. var ip, type, localIP, active;
  4509. try {
  4510. ip = getStatValue(now, 'remoteAddress');
  4511. type = getStatValue(now, "transportType");
  4512. localIP = getStatValue(now, "localAddress");
  4513. active = getStatValue(now, "activeConnection");
  4514. }
  4515. catch(e){/*not supported*/}
  4516. if(!ip || !type || !localIP || active != "true")
  4517. continue;
  4518. var addressSaved = false;
  4519. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  4520. {
  4521. if(this.conferenceStats.transport[i].ip == ip &&
  4522. this.conferenceStats.transport[i].type == type &&
  4523. this.conferenceStats.transport[i].localip == localIP)
  4524. {
  4525. addressSaved = true;
  4526. }
  4527. }
  4528. if(addressSaved)
  4529. continue;
  4530. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  4531. continue;
  4532. }
  4533. if(now.type == "candidatepair")
  4534. {
  4535. if(now.state == "succeeded")
  4536. continue;
  4537. var local = this.currentStatsReport[now.localCandidateId];
  4538. var remote = this.currentStatsReport[now.remoteCandidateId];
  4539. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  4540. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  4541. }
  4542. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  4543. now.type != "inboundrtp") {
  4544. continue;
  4545. }
  4546. var before = this.baselineStatsReport[idx];
  4547. if (!before) {
  4548. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4549. continue;
  4550. }
  4551. var ssrc = getStatValue(now, 'ssrc');
  4552. if(!ssrc)
  4553. continue;
  4554. var ssrcStats = this.ssrc2stats[ssrc];
  4555. if (!ssrcStats) {
  4556. ssrcStats = new PeerStats();
  4557. this.ssrc2stats[ssrc] = ssrcStats;
  4558. }
  4559. var isDownloadStream = true;
  4560. var key = 'packetsReceived';
  4561. var packetsNow = getStatValue(now, key);
  4562. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4563. isDownloadStream = false;
  4564. key = 'packetsSent';
  4565. packetsNow = getStatValue(now, key);
  4566. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  4567. console.warn("No packetsReceived nor packetsSent stat found");
  4568. continue;
  4569. }
  4570. }
  4571. if (!packetsNow || packetsNow < 0)
  4572. packetsNow = 0;
  4573. var packetsBefore = getStatValue(before, key);
  4574. if (!packetsBefore || packetsBefore < 0)
  4575. packetsBefore = 0;
  4576. var packetRate = packetsNow - packetsBefore;
  4577. if (!packetRate || packetRate < 0)
  4578. packetRate = 0;
  4579. var currentLoss = getStatValue(now, 'packetsLost');
  4580. if (!currentLoss || currentLoss < 0)
  4581. currentLoss = 0;
  4582. var previousLoss = getStatValue(before, 'packetsLost');
  4583. if (!previousLoss || previousLoss < 0)
  4584. previousLoss = 0;
  4585. var lossRate = currentLoss - previousLoss;
  4586. if (!lossRate || lossRate < 0)
  4587. lossRate = 0;
  4588. var packetsTotal = (packetRate + lossRate);
  4589. ssrcStats.setSsrcLoss(ssrc,
  4590. {"packetsTotal": packetsTotal,
  4591. "packetsLost": lossRate,
  4592. "isDownloadStream": isDownloadStream});
  4593. var bytesReceived = 0, bytesSent = 0;
  4594. if(getStatValue(now, "bytesReceived")) {
  4595. bytesReceived = getStatValue(now, "bytesReceived") -
  4596. getStatValue(before, "bytesReceived");
  4597. }
  4598. if (getStatValue(now, "bytesSent")) {
  4599. bytesSent = getStatValue(now, "bytesSent") -
  4600. getStatValue(before, "bytesSent");
  4601. }
  4602. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  4603. if (bytesReceived <= 0 || time <= 0) {
  4604. bytesReceived = 0;
  4605. } else {
  4606. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  4607. }
  4608. if (bytesSent <= 0 || time <= 0) {
  4609. bytesSent = 0;
  4610. } else {
  4611. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  4612. }
  4613. ssrcStats.setSsrcBitrate(ssrc, {
  4614. "download": bytesReceived,
  4615. "upload": bytesSent});
  4616. var resolution = {height: null, width: null};
  4617. try {
  4618. if (getStatValue(now, "googFrameHeightReceived") &&
  4619. getStatValue(now, "googFrameWidthReceived")) {
  4620. resolution.height =
  4621. getStatValue(now, "googFrameHeightReceived");
  4622. resolution.width = getStatValue(now, "googFrameWidthReceived");
  4623. }
  4624. else if (getStatValue(now, "googFrameHeightSent") &&
  4625. getStatValue(now, "googFrameWidthSent")) {
  4626. resolution.height = getStatValue(now, "googFrameHeightSent");
  4627. resolution.width = getStatValue(now, "googFrameWidthSent");
  4628. }
  4629. }
  4630. catch(e){/*not supported*/}
  4631. if (resolution.height && resolution.width) {
  4632. ssrcStats.setSsrcResolution(ssrc, resolution);
  4633. } else {
  4634. ssrcStats.setSsrcResolution(ssrc, null);
  4635. }
  4636. }
  4637. var self = this;
  4638. // Jid stats
  4639. var totalPackets = {download: 0, upload: 0};
  4640. var lostPackets = {download: 0, upload: 0};
  4641. var bitrateDownload = 0;
  4642. var bitrateUpload = 0;
  4643. var resolutions = {};
  4644. Object.keys(this.ssrc2stats).forEach(
  4645. function (jid) {
  4646. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  4647. function (ssrc) {
  4648. var type = "upload";
  4649. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  4650. type = "download";
  4651. totalPackets[type] +=
  4652. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  4653. lostPackets[type] +=
  4654. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  4655. }
  4656. );
  4657. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  4658. function (ssrc) {
  4659. bitrateDownload +=
  4660. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  4661. bitrateUpload +=
  4662. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  4663. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  4664. }
  4665. );
  4666. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  4667. }
  4668. );
  4669. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  4670. this.conferenceStats.packetLoss = {
  4671. total:
  4672. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  4673. totalPackets.download + totalPackets.upload),
  4674. download:
  4675. calculatePacketLoss(lostPackets.download, totalPackets.download),
  4676. upload:
  4677. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  4678. };
  4679. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  4680. {
  4681. "bitrate": this.conferenceStats.bitrate,
  4682. "packetLoss": this.conferenceStats.packetLoss,
  4683. "bandwidth": this.conferenceStats.bandwidth,
  4684. "resolution": resolutions,
  4685. "transport": this.conferenceStats.transport
  4686. });
  4687. this.conferenceStats.transport = [];
  4688. };
  4689. /**
  4690. * Stats processing logic.
  4691. */
  4692. StatsCollector.prototype.processAudioLevelReport = function () {
  4693. if (!this.baselineAudioLevelsReport) {
  4694. return;
  4695. }
  4696. for (var idx in this.currentAudioLevelsReport) {
  4697. var now = this.currentAudioLevelsReport[idx];
  4698. //if we don't have "packetsReceived" this is local stream
  4699. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  4700. continue;
  4701. }
  4702. var before = this.baselineAudioLevelsReport[idx];
  4703. if (!before) {
  4704. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  4705. continue;
  4706. }
  4707. var ssrc = getStatValue(now, 'ssrc');
  4708. if (!ssrc) {
  4709. if((Date.now() - now.timestamp) < 3000)
  4710. logger.warn("No ssrc: ");
  4711. continue;
  4712. }
  4713. var ssrcStats = this.ssrc2stats[ssrc];
  4714. if (!ssrcStats) {
  4715. ssrcStats = new PeerStats();
  4716. this.ssrc2stats[ssrc] = ssrcStats;
  4717. }
  4718. // Audio level
  4719. var audioLevel = null;
  4720. try {
  4721. audioLevel = getStatValue(now, 'audioInputLevel');
  4722. if (!audioLevel)
  4723. audioLevel = getStatValue(now, 'audioOutputLevel');
  4724. }
  4725. catch(e) {/*not supported*/
  4726. logger.warn("Audio Levels are not available in the statistics.");
  4727. clearInterval(this.audioLevelsIntervalId);
  4728. return;
  4729. }
  4730. if (audioLevel) {
  4731. // TODO: can't find specs about what this value really is,
  4732. // but it seems to vary between 0 and around 32k.
  4733. audioLevel = audioLevel / 32767;
  4734. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  4735. this.eventEmitter.emit(
  4736. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  4737. }
  4738. }
  4739. };
  4740. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  4741. },{"../../service/statistics/Events":82,"../RTC/RTCBrowserType":14,"jitsi-meet-logger":45}],22:[function(require,module,exports){
  4742. /* global require, APP */
  4743. var LocalStats = require("./LocalStatsCollector.js");
  4744. var RTPStats = require("./RTPStatsCollector.js");
  4745. var EventEmitter = require("events");
  4746. var StatisticsEvents = require("../../service/statistics/Events");
  4747. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  4748. //var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4749. //var CallStats = require("./CallStats");
  4750. //var RTCEvents = require("../../service/RTC/RTCEvents");
  4751. //
  4752. //function onDisposeConference(onUnload) {
  4753. // CallStats.sendTerminateEvent();
  4754. // stopRemote();
  4755. // if(onUnload) {
  4756. // stopLocal();
  4757. // eventEmitter.removeAllListeners();
  4758. // }
  4759. //}
  4760. function Statistics() {
  4761. this.localStats = null;
  4762. this.rtpStats = null;
  4763. this.eventEmitter = new EventEmitter();
  4764. }
  4765. Statistics.prototype.startRemoteStats = function (peerconnection) {
  4766. if (this.rtpStats) {
  4767. this.rtpStats.stop();
  4768. }
  4769. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  4770. this.rtpStats.start();
  4771. }
  4772. Statistics.prototype.startLocalStats = function (stream) {
  4773. if(stream.getType() !== "audio")
  4774. return;
  4775. this.localStats = new LocalStats(stream.getOriginalStream(), 200, this,
  4776. this.eventEmitter);
  4777. this.localStats.start();
  4778. }
  4779. Statistics.prototype.addAudioLevelListener = function(listener)
  4780. {
  4781. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  4782. }
  4783. Statistics.prototype.removeAudioLevelListener = function(listener)
  4784. {
  4785. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  4786. }
  4787. Statistics.prototype.dispose = function () {
  4788. this.stopLocal();
  4789. this.stopRemote();
  4790. if(this.eventEmitter)
  4791. {
  4792. this.eventEmitter.removeAllListeners();
  4793. }
  4794. }
  4795. Statistics.prototype.stopLocal = function () {
  4796. if (this.localStats) {
  4797. this.localStats.stop();
  4798. this.localStats = null;
  4799. }
  4800. }
  4801. Statistics.prototype.stopRemote = function () {
  4802. if (this.rtpStats) {
  4803. this.rtpStats.stop();
  4804. this.eventEmitter.emit(StatisticsEvents.STOP);
  4805. this.rtpStats = null;
  4806. }
  4807. }
  4808. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  4809. //
  4810. //var statistics = {
  4811. // /**
  4812. // * Indicates that this audio level is for local jid.
  4813. // * @type {string}
  4814. // */
  4815. // LOCAL_JID: 'local',
  4816. //
  4817. // addConnectionStatsListener: function(listener)
  4818. // {
  4819. // eventEmitter.on("statistics.connectionstats", listener);
  4820. // },
  4821. //
  4822. // removeConnectionStatsListener: function(listener)
  4823. // {
  4824. // eventEmitter.removeListener("statistics.connectionstats", listener);
  4825. // },
  4826. //
  4827. //
  4828. // addRemoteStatsStopListener: function(listener)
  4829. // {
  4830. // eventEmitter.on("statistics.stop", listener);
  4831. // },
  4832. //
  4833. // removeRemoteStatsStopListener: function(listener)
  4834. // {
  4835. // eventEmitter.removeListener("statistics.stop", listener);
  4836. // },
  4837. //
  4838. //
  4839. // stopRemoteStatistics: function()
  4840. // {
  4841. // stopRemote();
  4842. // },
  4843. //
  4844. //// Already implemented with the constructor
  4845. // start: function () {
  4846. // APP.RTC.addStreamListener(onStreamCreated,
  4847. // StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  4848. // APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  4849. // //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  4850. // APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  4851. // startRemoteStats(event.peerconnection);
  4852. //// CallStats.init(event);
  4853. // });
  4854. //// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  4855. //// CallStats.init(session);
  4856. //// });
  4857. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4858. //// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  4859. //// CallStats.sendMuteEvent(mute, "audio");
  4860. //// });
  4861. //// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  4862. //// CallStats.sendSetupFailedEvent();
  4863. //// });
  4864. // //FIXME: that event is changed to TRACK_MUTE_CHANGED
  4865. //// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  4866. //// CallStats.sendMuteEvent(mute, "video");
  4867. //// });
  4868. // }
  4869. //};
  4870. module.exports = Statistics;
  4871. },{"../../service/statistics/Events":82,"../../service/statistics/constants":83,"./LocalStatsCollector.js":20,"./RTPStatsCollector.js":21,"events":41}],23:[function(require,module,exports){
  4872. /**
  4873. /**
  4874. * @const
  4875. */
  4876. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  4877. /**
  4878. * Hexadecimal digits.
  4879. * @const
  4880. */
  4881. var HEX_DIGITS = '0123456789abcdef';
  4882. /**
  4883. * Generates random int within the range [min, max]
  4884. * @param min the minimum value for the generated number
  4885. * @param max the maximum value for the generated number
  4886. * @returns random int number
  4887. */
  4888. function randomInt(min, max) {
  4889. return Math.floor(Math.random() * (max - min + 1)) + min;
  4890. }
  4891. /**
  4892. * Get random element from array or string.
  4893. * @param {Array|string} arr source
  4894. * @returns array element or string character
  4895. */
  4896. function randomElement(arr) {
  4897. return arr[randomInt(0, arr.length - 1)];
  4898. }
  4899. /**
  4900. * Generate random alphanumeric string.
  4901. * @param {number} length expected string length
  4902. * @returns {string} random string of specified length
  4903. */
  4904. function randomAlphanumStr(length) {
  4905. var result = '';
  4906. for (var i = 0; i < length; i += 1) {
  4907. result += randomElement(ALPHANUM);
  4908. }
  4909. return result;
  4910. }
  4911. /**
  4912. * Exported interface.
  4913. */
  4914. var RandomUtil = {
  4915. /**
  4916. * Returns a random hex digit.
  4917. * @returns {*}
  4918. */
  4919. randomHexDigit: function() {
  4920. return randomElement(HEX_DIGITS);
  4921. },
  4922. /**
  4923. * Returns a random string of hex digits with length 'len'.
  4924. * @param len the length.
  4925. */
  4926. randomHexString: function (len) {
  4927. var ret = '';
  4928. while (len--) {
  4929. ret += this.randomHexDigit();
  4930. }
  4931. return ret;
  4932. },
  4933. randomElement: randomElement,
  4934. randomAlphanumStr: randomAlphanumStr
  4935. };
  4936. module.exports = RandomUtil;
  4937. },{}],24:[function(require,module,exports){
  4938. (function (__filename){
  4939. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4940. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4941. var Moderator = require("./moderator");
  4942. var EventEmitter = require("events");
  4943. var parser = {
  4944. packet2JSON: function (packet, nodes) {
  4945. var self = this;
  4946. $(packet).children().each(function (index) {
  4947. var tagName = $(this).prop("tagName");
  4948. var node = {}
  4949. node["tagName"] = tagName;
  4950. node.attributes = {};
  4951. $($(this)[0].attributes).each(function( index, attr ) {
  4952. node.attributes[ attr.name ] = attr.value;
  4953. } );
  4954. var text = Strophe.getText($(this)[0]);
  4955. if(text)
  4956. node.value = text;
  4957. node.children = [];
  4958. nodes.push(node);
  4959. self.packet2JSON($(this), node.children);
  4960. })
  4961. },
  4962. JSON2packet: function (nodes, packet) {
  4963. for(var i = 0; i < nodes.length; i++)
  4964. {
  4965. var node = nodes[i];
  4966. if(!node || node === null){
  4967. continue;
  4968. }
  4969. packet.c(node.tagName, node.attributes);
  4970. if(node.value)
  4971. packet.t(node.value);
  4972. if(node.children)
  4973. this.JSON2packet(node.children, packet);
  4974. packet.up();
  4975. }
  4976. // packet.up();
  4977. }
  4978. };
  4979. /**
  4980. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  4981. * @param pres the presence JSON
  4982. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  4983. */
  4984. function filterNodeFromPresenceJSON(pres, nodeName){
  4985. var res = [];
  4986. for(var i = 0; i < pres.length; i++)
  4987. if(pres[i].tagName === nodeName)
  4988. res.push(pres[i]);
  4989. return res;
  4990. }
  4991. function ChatRoom(connection, jid, password, XMPP, options) {
  4992. this.eventEmitter = new EventEmitter();
  4993. this.xmpp = XMPP;
  4994. this.connection = connection;
  4995. this.roomjid = Strophe.getBareJidFromJid(jid);
  4996. this.myroomjid = jid;
  4997. this.password = password;
  4998. logger.info("Joined MUC as " + this.myroomjid);
  4999. this.members = {};
  5000. this.presMap = {};
  5001. this.presHandlers = {};
  5002. this.joined = false;
  5003. this.role = null;
  5004. this.focusMucJid = null;
  5005. this.bridgeIsDown = false;
  5006. this.options = options || {};
  5007. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  5008. this.initPresenceMap();
  5009. this.session = null;
  5010. var self = this;
  5011. this.lastPresences = {};
  5012. }
  5013. ChatRoom.prototype.initPresenceMap = function () {
  5014. this.presMap['to'] = this.myroomjid;
  5015. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  5016. this.presMap["nodes"] = [];
  5017. this.presMap["nodes"].push( {
  5018. "tagName": "user-agent",
  5019. "value": navigator.userAgent,
  5020. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  5021. });
  5022. };
  5023. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  5024. this.presMap["nodes"].push( {
  5025. "tagName": "devices",
  5026. "children": [
  5027. {
  5028. "tagName": "audio",
  5029. "value": devices.audio,
  5030. },
  5031. {
  5032. "tagName": "video",
  5033. "value": devices.video,
  5034. }
  5035. ]
  5036. });
  5037. }
  5038. ChatRoom.prototype.join = function (password, tokenPassword) {
  5039. if(password)
  5040. this.password = password;
  5041. var self = this;
  5042. this.moderator.allocateConferenceFocus(function()
  5043. {
  5044. self.sendPresence(tokenPassword);
  5045. }.bind(this));
  5046. };
  5047. ChatRoom.prototype.sendPresence = function (tokenPassword) {
  5048. if (!this.presMap['to']) {
  5049. // Too early to send presence - not initialized
  5050. return;
  5051. }
  5052. var pres = $pres({to: this.presMap['to'] });
  5053. pres.c('x', {xmlns: this.presMap['xns']});
  5054. if (this.password) {
  5055. pres.c('password').t(this.password).up();
  5056. }
  5057. pres.up();
  5058. // Send XEP-0115 'c' stanza that contains our capabilities info
  5059. if (this.connection.caps) {
  5060. this.connection.caps.node = this.xmpp.options.clientNode;
  5061. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  5062. }
  5063. if (tokenPassword) {
  5064. pres.c('token', { xmlns: 'http://jitsi.org/jitmeet/auth-token'})
  5065. .t(tokenPassword).up();
  5066. }
  5067. parser.JSON2packet(this.presMap.nodes, pres);
  5068. this.connection.send(pres);
  5069. };
  5070. ChatRoom.prototype.doLeave = function () {
  5071. logger.log("do leave", this.myroomjid);
  5072. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  5073. this.presMap.length = 0;
  5074. this.connection.send(pres);
  5075. };
  5076. ChatRoom.prototype.createNonAnonymousRoom = function () {
  5077. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  5078. var getForm = $iq({type: 'get', to: this.roomjid})
  5079. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  5080. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5081. var self = this;
  5082. this.connection.sendIQ(getForm, function (form) {
  5083. if (!$(form).find(
  5084. '>query>x[xmlns="jabber:x:data"]' +
  5085. '>field[var="muc#roomconfig_whois"]').length) {
  5086. logger.error('non-anonymous rooms not supported');
  5087. return;
  5088. }
  5089. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  5090. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5091. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5092. formSubmit.c('field', {'var': 'FORM_TYPE'})
  5093. .c('value')
  5094. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5095. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  5096. .c('value').t('anyone').up().up();
  5097. self.connection.sendIQ(formSubmit);
  5098. }, function (error) {
  5099. logger.error("Error getting room configuration form");
  5100. });
  5101. };
  5102. ChatRoom.prototype.onPresence = function (pres) {
  5103. var from = pres.getAttribute('from');
  5104. // Parse roles.
  5105. var member = {};
  5106. member.show = $(pres).find('>show').text();
  5107. member.status = $(pres).find('>status').text();
  5108. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  5109. member.affiliation = tmp.attr('affiliation');
  5110. member.role = tmp.attr('role');
  5111. // Focus recognition
  5112. member.jid = tmp.attr('jid');
  5113. member.isFocus = false;
  5114. if (member.jid
  5115. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  5116. member.isFocus = true;
  5117. }
  5118. $(pres).find(">x").remove();
  5119. var nodes = [];
  5120. parser.packet2JSON(pres, nodes);
  5121. this.lastPresences[from] = nodes;
  5122. for(var i = 0; i < nodes.length; i++)
  5123. {
  5124. var node = nodes[i];
  5125. switch(node.tagName)
  5126. {
  5127. case "nick":
  5128. member.nick = node.value;
  5129. if(!member.isFocus) {
  5130. var displayName = !this.xmpp.options.displayJids
  5131. ? member.nick : Strophe.getResourceFromJid(from);
  5132. if (displayName && displayName.length > 0) {
  5133. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  5134. }
  5135. logger.info("Display name: " + displayName, pres);
  5136. }
  5137. break;
  5138. case "userId":
  5139. member.id = node.value;
  5140. break;
  5141. case "email":
  5142. member.email = node.value;
  5143. break;
  5144. case "bridgeIsDown":
  5145. if(!this.bridgeIsDown) {
  5146. this.bridgeIsDown = true;
  5147. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  5148. }
  5149. break;
  5150. default :
  5151. this.processNode(node, from);
  5152. }
  5153. }
  5154. if (from == this.myroomjid) {
  5155. if (member.affiliation == 'owner')
  5156. if (this.role !== member.role) {
  5157. this.role = member.role;
  5158. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  5159. member, this.isModerator());
  5160. }
  5161. if (!this.joined) {
  5162. this.joined = true;
  5163. console.log("(TIME) MUC joined:\t", window.performance.now());
  5164. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  5165. }
  5166. } else if (this.members[from] === undefined) {
  5167. // new participant
  5168. this.members[from] = member;
  5169. logger.log('entered', from, member);
  5170. if (member.isFocus) {
  5171. this.focusMucJid = from;
  5172. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  5173. }
  5174. else {
  5175. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  5176. }
  5177. } else {
  5178. // Presence update for existing participant
  5179. // Watch role change:
  5180. if (this.members[from].role != member.role) {
  5181. this.members[from].role = member.role;
  5182. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  5183. member.role, member.nick);
  5184. }
  5185. // store the new display name
  5186. if(member.displayName)
  5187. this.members[from].displayName = member.displayName;
  5188. }
  5189. if(!member.isFocus)
  5190. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  5191. // Trigger status message update
  5192. if (member.status) {
  5193. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  5194. }
  5195. };
  5196. ChatRoom.prototype.processNode = function (node, from) {
  5197. if(this.presHandlers[node.tagName])
  5198. this.presHandlers[node.tagName](node, from);
  5199. };
  5200. ChatRoom.prototype.sendMessage = function (body, nickname) {
  5201. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5202. msg.c('body', body).up();
  5203. if (nickname) {
  5204. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  5205. }
  5206. this.connection.send(msg);
  5207. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  5208. };
  5209. ChatRoom.prototype.setSubject = function (subject) {
  5210. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  5211. msg.c('subject', subject);
  5212. this.connection.send(msg);
  5213. logger.log("topic changed to " + subject);
  5214. };
  5215. ChatRoom.prototype.onParticipantLeft = function (jid) {
  5216. delete this.lastPresences[jid];
  5217. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  5218. this.moderator.onMucMemberLeft(jid);
  5219. };
  5220. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  5221. // room destroyed ?
  5222. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5223. '>destroy').length) {
  5224. var reason;
  5225. var reasonSelect = $(pres).find(
  5226. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  5227. '>destroy>reason');
  5228. if (reasonSelect.length) {
  5229. reason = reasonSelect.text();
  5230. }
  5231. this.xmpp.disposeConference(false);
  5232. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  5233. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  5234. return true;
  5235. }
  5236. // Status code 110 indicates that this notification is "self-presence".
  5237. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  5238. delete this.members[from];
  5239. this.onParticipantLeft(from);
  5240. }
  5241. // If the status code is 110 this means we're leaving and we would like
  5242. // to remove everyone else from our view, so we trigger the event.
  5243. else if (Object.keys(this.members).length > 1) {
  5244. for (var i in this.members) {
  5245. var member = this.members[i];
  5246. delete this.members[i];
  5247. this.onParticipantLeft(member);
  5248. }
  5249. }
  5250. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  5251. if (this.myroomjid === from) {
  5252. this.xmpp.disposeConference(false);
  5253. this.eventEmitter.emit(XMPPEvents.KICKED);
  5254. }
  5255. }
  5256. };
  5257. ChatRoom.prototype.onMessage = function (msg, from) {
  5258. var nick =
  5259. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  5260. .text() ||
  5261. Strophe.getResourceFromJid(from);
  5262. var txt = $(msg).find('>body').text();
  5263. var type = msg.getAttribute("type");
  5264. if (type == "error") {
  5265. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  5266. $(msg).find('>text').text(), txt);
  5267. return true;
  5268. }
  5269. var subject = $(msg).find('>subject');
  5270. if (subject.length) {
  5271. var subjectText = subject.text();
  5272. if (subjectText || subjectText == "") {
  5273. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  5274. logger.log("Subject is changed to " + subjectText);
  5275. }
  5276. }
  5277. // xep-0203 delay
  5278. var stamp = $(msg).find('>delay').attr('stamp');
  5279. if (!stamp) {
  5280. // or xep-0091 delay, UTC timestamp
  5281. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  5282. if (stamp) {
  5283. // the format is CCYYMMDDThh:mm:ss
  5284. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  5285. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  5286. }
  5287. }
  5288. if (txt) {
  5289. logger.log('chat', nick, txt);
  5290. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  5291. from, nick, txt, this.myroomjid, stamp);
  5292. }
  5293. }
  5294. ChatRoom.prototype.onPresenceError = function (pres, from) {
  5295. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5296. logger.log('on password required', from);
  5297. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  5298. } else if ($(pres).find(
  5299. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  5300. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  5301. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  5302. // enter the room by replying with 'not-authorized'. This would
  5303. // result in reconnection from authorized domain.
  5304. // We're either missing Jicofo/Prosody config for anonymous
  5305. // domains or something is wrong.
  5306. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  5307. } else {
  5308. logger.warn('onPresError ', pres);
  5309. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5310. }
  5311. } else {
  5312. logger.warn('onPresError ', pres);
  5313. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  5314. }
  5315. };
  5316. ChatRoom.prototype.kick = function (jid) {
  5317. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  5318. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  5319. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  5320. .c('reason').t('You have been kicked.').up().up().up();
  5321. this.connection.sendIQ(
  5322. kickIQ,
  5323. function (result) {
  5324. logger.log('Kick participant with jid: ', jid, result);
  5325. },
  5326. function (error) {
  5327. logger.log('Kick participant error: ', error);
  5328. });
  5329. };
  5330. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  5331. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  5332. var ob = this;
  5333. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  5334. function (res) {
  5335. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  5336. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  5337. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  5338. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  5339. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  5340. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  5341. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  5342. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  5343. ob.connection.sendIQ(formsubmit,
  5344. onSuccess,
  5345. onError);
  5346. } else {
  5347. onNotSupported();
  5348. }
  5349. }, onError);
  5350. };
  5351. ChatRoom.prototype.addToPresence = function (key, values) {
  5352. values.tagName = key;
  5353. this.presMap["nodes"].push(values);
  5354. };
  5355. ChatRoom.prototype.removeFromPresence = function (key) {
  5356. for(var i = 0; i < this.presMap.nodes.length; i++)
  5357. {
  5358. if(key === this.presMap.nodes[i].tagName)
  5359. this.presMap.nodes.splice(i, 1);
  5360. }
  5361. };
  5362. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  5363. this.presHandlers[name] = handler;
  5364. }
  5365. ChatRoom.prototype.removePresenceListener = function (name) {
  5366. delete this.presHandlers[name];
  5367. }
  5368. ChatRoom.prototype.isModerator = function (jid) {
  5369. return this.role === 'moderator';
  5370. };
  5371. ChatRoom.prototype.getMemberRole = function (peerJid) {
  5372. if (this.members[peerJid]) {
  5373. return this.members[peerJid].role;
  5374. }
  5375. return null;
  5376. };
  5377. ChatRoom.prototype.setJingleSession = function(session){
  5378. this.session = session;
  5379. this.session.room = this;
  5380. };
  5381. ChatRoom.prototype.removeStream = function (stream) {
  5382. if(!this.session)
  5383. return;
  5384. this.session.peerconnection.removeStream(stream)
  5385. }
  5386. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  5387. if(this.session) {
  5388. // FIXME: will block switchInProgress on true value in case of exception
  5389. this.session.switchStreams(stream, oldStream, callback, isAudio);
  5390. } else {
  5391. // We are done immediately
  5392. logger.warn("No conference handler or conference not started yet");
  5393. callback();
  5394. }
  5395. };
  5396. ChatRoom.prototype.addStream = function (stream, callback) {
  5397. if(this.session) {
  5398. // FIXME: will block switchInProgress on true value in case of exception
  5399. this.session.addStream(stream, callback);
  5400. } else {
  5401. // We are done immediately
  5402. logger.warn("No conference handler or conference not started yet");
  5403. callback();
  5404. }
  5405. }
  5406. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  5407. var self = this;
  5408. var localCallback = function (mute) {
  5409. self.sendVideoInfoPresence(mute);
  5410. if(callback)
  5411. callback(mute)
  5412. };
  5413. if(this.session)
  5414. {
  5415. this.session.setVideoMute(
  5416. mute, localCallback, options);
  5417. }
  5418. else {
  5419. localCallback(mute);
  5420. }
  5421. };
  5422. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  5423. //This will be for remote streams only
  5424. // if (this.forceMuted && !mute) {
  5425. // logger.info("Asking focus for unmute");
  5426. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  5427. // // FIXME: wait for result before resetting muted status
  5428. // this.forceMuted = false;
  5429. // }
  5430. return this.sendAudioInfoPresence(mute, callback);
  5431. };
  5432. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  5433. this.removeFromPresence("audiomuted");
  5434. this.addToPresence("audiomuted",
  5435. {attributes:
  5436. {"audions": "http://jitsi.org/jitmeet/audio"},
  5437. value: mute.toString()});
  5438. }
  5439. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  5440. this.addAudioInfoToPresence(mute);
  5441. if(this.connection) {
  5442. this.sendPresence();
  5443. }
  5444. if(callback)
  5445. callback();
  5446. };
  5447. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  5448. this.removeFromPresence("videomuted");
  5449. this.addToPresence("videomuted",
  5450. {attributes:
  5451. {"videons": "http://jitsi.org/jitmeet/video"},
  5452. value: mute.toString()});
  5453. }
  5454. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  5455. this.addVideoInfoToPresence(mute);
  5456. if(!this.connection)
  5457. return;
  5458. this.sendPresence();
  5459. };
  5460. ChatRoom.prototype.addListener = function(type, listener) {
  5461. this.eventEmitter.on(type, listener);
  5462. };
  5463. ChatRoom.prototype.removeListener = function (type, listener) {
  5464. this.eventEmitter.removeListener(type, listener);
  5465. };
  5466. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  5467. if(this.lastPresences[data.peerjid])
  5468. {
  5469. var pres = this.lastPresences[data.peerjid];
  5470. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  5471. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  5472. data.videomuted = ((videomuted.length > 0
  5473. && videomuted[0]
  5474. && videomuted[0]["value"] === "true")? true : false);
  5475. data.audiomuted = ((audiomuted.length > 0
  5476. && audiomuted[0]
  5477. && audiomuted[0]["value"] === "true")? true : false);
  5478. }
  5479. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  5480. }
  5481. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  5482. if (!this.session)
  5483. return null;
  5484. return this.session.getSsrcOwner(ssrc);
  5485. };
  5486. module.exports = ChatRoom;
  5487. }).call(this,"/modules/xmpp/ChatRoom.js")
  5488. },{"../../service/xmpp/XMPPEvents":84,"./moderator":32,"events":41,"jitsi-meet-logger":45}],25:[function(require,module,exports){
  5489. (function (__filename){
  5490. /*
  5491. * JingleSession provides an API to manage a single Jingle session. We will
  5492. * have different implementations depending on the underlying interface used
  5493. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  5494. */
  5495. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5496. function JingleSession(me, sid, connection, service, eventEmitter) {
  5497. /**
  5498. * Our JID.
  5499. */
  5500. this.me = me;
  5501. /**
  5502. * The Jingle session identifier.
  5503. */
  5504. this.sid = sid;
  5505. /**
  5506. * The XMPP connection.
  5507. */
  5508. this.connection = connection;
  5509. /**
  5510. * The XMPP service.
  5511. */
  5512. this.service = service;
  5513. /**
  5514. * The event emitter.
  5515. */
  5516. this.eventEmitter = eventEmitter;
  5517. /**
  5518. * Whether to use dripping or not. Dripping is sending trickle candidates
  5519. * not one-by-one.
  5520. * Note: currently we do not support 'false'.
  5521. */
  5522. this.usedrip = true;
  5523. /**
  5524. * When dripping is used, stores ICE candidates which are to be sent.
  5525. */
  5526. this.drip_container = [];
  5527. // Media constraints. Is this WebRTC only?
  5528. this.media_constraints = null;
  5529. // ICE servers config (RTCConfiguration?).
  5530. this.ice_config = {};
  5531. // The chat room instance associated with the session.
  5532. this.room = null;
  5533. }
  5534. /**
  5535. * Prepares this object to initiate a session.
  5536. * @param peerjid the JID of the remote peer.
  5537. * @param isInitiator whether we will be the Jingle initiator.
  5538. * @param media_constraints
  5539. * @param ice_config
  5540. */
  5541. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  5542. media_constraints, ice_config) {
  5543. this.media_constraints = media_constraints;
  5544. this.ice_config = ice_config;
  5545. if (this.state !== null) {
  5546. logger.error('attempt to initiate on session ' + this.sid +
  5547. 'in state ' + this.state);
  5548. return;
  5549. }
  5550. this.state = 'pending';
  5551. this.initiator = isInitiator ? this.me : peerjid;
  5552. this.responder = !isInitiator ? this.me : peerjid;
  5553. this.peerjid = peerjid;
  5554. this.doInitialize();
  5555. };
  5556. /**
  5557. * Finishes initialization.
  5558. */
  5559. JingleSession.prototype.doInitialize = function() {};
  5560. /**
  5561. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  5562. * Note: currently only used on transport-info
  5563. */
  5564. JingleSession.prototype.addIceCandidates = function(contents) {};
  5565. /**
  5566. * Handles an 'add-source' event.
  5567. *
  5568. * @param contents an array of Jingle 'content' elements.
  5569. */
  5570. JingleSession.prototype.addSources = function(contents) {};
  5571. /**
  5572. * Handles a 'remove-source' event.
  5573. *
  5574. * @param contents an array of Jingle 'content' elements.
  5575. */
  5576. JingleSession.prototype.removeSources = function(contents) {};
  5577. /**
  5578. * Terminates this Jingle session (stops sending media and closes the streams?)
  5579. */
  5580. JingleSession.prototype.terminate = function() {};
  5581. /**
  5582. * Sends a Jingle session-terminate message to the peer and terminates the
  5583. * session.
  5584. * @param reason
  5585. * @param text
  5586. */
  5587. JingleSession.prototype.sendTerminate = function(reason, text) {};
  5588. /**
  5589. * Handles an offer from the remote peer (prepares to accept a session).
  5590. * @param jingle the 'jingle' XML element.
  5591. */
  5592. JingleSession.prototype.setOffer = function(jingle) {};
  5593. /**
  5594. * Handles an answer from the remote peer (prepares to accept a session).
  5595. * @param jingle the 'jingle' XML element.
  5596. */
  5597. JingleSession.prototype.setAnswer = function(jingle) {};
  5598. module.exports = JingleSession;
  5599. }).call(this,"/modules/xmpp/JingleSession.js")
  5600. },{"jitsi-meet-logger":45}],26:[function(require,module,exports){
  5601. (function (__filename){
  5602. /* jshint -W117 */
  5603. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5604. var JingleSession = require("./JingleSession");
  5605. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5606. var SDPDiffer = require("./SDPDiffer");
  5607. var SDPUtil = require("./SDPUtil");
  5608. var SDP = require("./SDP");
  5609. var async = require("async");
  5610. var transform = require("sdp-transform");
  5611. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5612. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5613. var SSRCReplacement = require("./LocalSSRCReplacement");
  5614. var RTC = require("../RTC/RTC");
  5615. // Jingle stuff
  5616. function JingleSessionPC(me, sid, connection, service) {
  5617. JingleSession.call(this, me, sid, connection, service);
  5618. this.initiator = null;
  5619. this.responder = null;
  5620. this.peerjid = null;
  5621. this.state = null;
  5622. this.localSDP = null;
  5623. this.remoteSDP = null;
  5624. this.relayedStreams = [];
  5625. this.usetrickle = true;
  5626. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  5627. this.hadstuncandidate = false;
  5628. this.hadturncandidate = false;
  5629. this.lasticecandidate = false;
  5630. this.statsinterval = null;
  5631. this.reason = null;
  5632. this.addssrc = [];
  5633. this.removessrc = [];
  5634. this.pendingop = null;
  5635. this.switchstreams = false;
  5636. this.addingStreams = false;
  5637. this.wait = true;
  5638. this.localStreamsSSRC = null;
  5639. this.ssrcOwners = {};
  5640. this.ssrcVideoTypes = {};
  5641. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  5642. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  5643. /**
  5644. * The indicator which determines whether the (local) video has been muted
  5645. * in response to a user command in contrast to an automatic decision made
  5646. * by the application logic.
  5647. */
  5648. this.videoMuteByUser = false;
  5649. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  5650. // We start with the queue paused. We resume it when the signaling state is
  5651. // stable and the ice connection state is connected.
  5652. this.modifySourcesQueue.pause();
  5653. }
  5654. //XXX this is badly broken...
  5655. JingleSessionPC.prototype = JingleSession.prototype;
  5656. JingleSessionPC.prototype.constructor = JingleSessionPC;
  5657. JingleSessionPC.prototype.setOffer = function(offer) {
  5658. this.setRemoteDescription(offer, 'offer');
  5659. };
  5660. JingleSessionPC.prototype.setAnswer = function(answer) {
  5661. this.setRemoteDescription(answer, 'answer');
  5662. };
  5663. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  5664. var signalingState = this.peerconnection.signalingState;
  5665. var iceConnectionState = this.peerconnection.iceConnectionState;
  5666. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  5667. this.modifySourcesQueue.resume();
  5668. } else {
  5669. this.modifySourcesQueue.pause();
  5670. }
  5671. };
  5672. JingleSessionPC.prototype.doInitialize = function () {
  5673. var self = this;
  5674. this.hadstuncandidate = false;
  5675. this.hadturncandidate = false;
  5676. this.lasticecandidate = false;
  5677. // True if reconnect is in progress
  5678. this.isreconnect = false;
  5679. // Set to true if the connection was ever stable
  5680. this.wasstable = false;
  5681. this.peerconnection = new TraceablePeerConnection(
  5682. this.connection.jingle.ice_config,
  5683. RTC.getPCConstraints(),
  5684. this);
  5685. this.peerconnection.onicecandidate = function (event) {
  5686. var protocol;
  5687. if (event && event.candidate) {
  5688. protocol = (typeof event.candidate.protocol === 'string')
  5689. ? event.candidate.protocol.toLowerCase() : '';
  5690. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  5691. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  5692. return;
  5693. }
  5694. }
  5695. self.sendIceCandidate(event.candidate);
  5696. };
  5697. this.peerconnection.onaddstream = function (event) {
  5698. if (event.stream.id !== 'default') {
  5699. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  5700. self.remoteStreamAdded(event);
  5701. } else {
  5702. // This is a recvonly stream. Clients that implement Unified Plan,
  5703. // such as Firefox use recvonly "streams/channels/tracks" for
  5704. // receiving remote stream/tracks, as opposed to Plan B where there
  5705. // are only 3 channels: audio, video and data.
  5706. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  5707. }
  5708. };
  5709. this.peerconnection.onremovestream = function (event) {
  5710. // Remove the stream from remoteStreams
  5711. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  5712. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  5713. };
  5714. this.peerconnection.onsignalingstatechange = function (event) {
  5715. if (!(self && self.peerconnection)) return;
  5716. if (self.peerconnection.signalingState === 'stable') {
  5717. self.wasstable = true;
  5718. }
  5719. self.updateModifySourcesQueue();
  5720. };
  5721. /**
  5722. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  5723. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  5724. * RTCPeerConnection.iceConnectionState changes.
  5725. *
  5726. * @param event the event containing information about the change
  5727. */
  5728. this.peerconnection.oniceconnectionstatechange = function (event) {
  5729. if (!(self && self.peerconnection)) return;
  5730. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  5731. ":\t", window.performance.now());
  5732. self.updateModifySourcesQueue();
  5733. switch (self.peerconnection.iceConnectionState) {
  5734. case 'connected':
  5735. // Informs interested parties that the connection has been restored.
  5736. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  5737. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  5738. self.isreconnect = false;
  5739. break;
  5740. case 'disconnected':
  5741. self.isreconnect = true;
  5742. // Informs interested parties that the connection has been interrupted.
  5743. if (self.wasstable)
  5744. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  5745. break;
  5746. case 'failed':
  5747. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5748. break;
  5749. }
  5750. onIceConnectionStateChange(self.sid, self);
  5751. };
  5752. this.peerconnection.onnegotiationneeded = function (event) {
  5753. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  5754. };
  5755. this.relayedStreams.forEach(function(stream) {
  5756. self.peerconnection.addStream(stream);
  5757. });
  5758. };
  5759. function onIceConnectionStateChange(sid, session) {
  5760. switch (session.peerconnection.iceConnectionState) {
  5761. case 'checking':
  5762. session.timeChecking = (new Date()).getTime();
  5763. session.firstconnect = true;
  5764. break;
  5765. case 'completed': // on caller side
  5766. case 'connected':
  5767. if (session.firstconnect) {
  5768. session.firstconnect = false;
  5769. var metadata = {};
  5770. metadata.setupTime
  5771. = (new Date()).getTime() - session.timeChecking;
  5772. session.peerconnection.getStats(function (res) {
  5773. if(res && res.result) {
  5774. res.result().forEach(function (report) {
  5775. if (report.type == 'googCandidatePair' &&
  5776. report.stat('googActiveConnection') == 'true') {
  5777. metadata.localCandidateType
  5778. = report.stat('googLocalCandidateType');
  5779. metadata.remoteCandidateType
  5780. = report.stat('googRemoteCandidateType');
  5781. // log pair as well so we can get nice pie
  5782. // charts
  5783. metadata.candidatePair
  5784. = report.stat('googLocalCandidateType') +
  5785. ';' +
  5786. report.stat('googRemoteCandidateType');
  5787. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  5788. {
  5789. metadata.ipv6 = true;
  5790. }
  5791. }
  5792. });
  5793. }
  5794. });
  5795. }
  5796. break;
  5797. }
  5798. }
  5799. JingleSessionPC.prototype.accept = function () {
  5800. this.state = 'active';
  5801. var pranswer = this.peerconnection.localDescription;
  5802. if (!pranswer || pranswer.type != 'pranswer') {
  5803. return;
  5804. }
  5805. logger.log('going from pranswer to answer');
  5806. if (this.usetrickle) {
  5807. // remove candidates already sent from session-accept
  5808. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  5809. for (var i = 0; i < lines.length; i++) {
  5810. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  5811. }
  5812. }
  5813. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  5814. // FIXME: change any inactive to sendrecv or whatever they were originally
  5815. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  5816. }
  5817. var prsdp = new SDP(pranswer.sdp);
  5818. if (self.webrtcIceTcpDisable) {
  5819. prsdp.removeTcpCandidates = true;
  5820. }
  5821. if (self.webrtcIceUdpDisable) {
  5822. prsdp.removeUdpCandidates = true;
  5823. }
  5824. var accept = $iq({to: this.peerjid,
  5825. type: 'set'})
  5826. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5827. action: 'session-accept',
  5828. initiator: this.initiator,
  5829. responder: this.responder,
  5830. sid: this.sid });
  5831. // FIXME why do we generate session-accept in 3 different places ?
  5832. prsdp.toJingle(
  5833. accept,
  5834. this.initiator == this.me ? 'initiator' : 'responder',
  5835. this.localStreamsSSRC);
  5836. var sdp = this.peerconnection.localDescription.sdp;
  5837. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  5838. // FIXME: change any inactive to sendrecv or whatever they were originally
  5839. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  5840. }
  5841. var self = this;
  5842. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  5843. function () {
  5844. //logger.log('setLocalDescription success');
  5845. self.setLocalDescription();
  5846. SSRCReplacement.processSessionInit(accept);
  5847. self.connection.sendIQ(accept,
  5848. function () {
  5849. var ack = {};
  5850. ack.source = 'answer';
  5851. $(document).trigger('ack.jingle', [self.sid, ack]);
  5852. },
  5853. function (stanza) {
  5854. var error = ($(stanza).find('error').length) ? {
  5855. code: $(stanza).find('error').attr('code'),
  5856. reason: $(stanza).find('error :first')[0].tagName
  5857. }:{};
  5858. error.source = 'answer';
  5859. JingleSessionPC.onJingleError(self.sid, error);
  5860. },
  5861. 10000);
  5862. },
  5863. function (e) {
  5864. logger.error('setLocalDescription failed', e);
  5865. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5866. }
  5867. );
  5868. };
  5869. JingleSessionPC.prototype.terminate = function (reason) {
  5870. this.state = 'ended';
  5871. this.reason = reason;
  5872. this.peerconnection.close();
  5873. if (this.statsinterval !== null) {
  5874. window.clearInterval(this.statsinterval);
  5875. this.statsinterval = null;
  5876. }
  5877. };
  5878. JingleSessionPC.prototype.active = function () {
  5879. return this.state == 'active';
  5880. };
  5881. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  5882. var self = this;
  5883. if (candidate && !this.lasticecandidate) {
  5884. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  5885. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  5886. if (!(ice && jcand)) {
  5887. logger.error('failed to get ice && jcand');
  5888. return;
  5889. }
  5890. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5891. if (jcand.type === 'srflx') {
  5892. this.hadstuncandidate = true;
  5893. } else if (jcand.type === 'relay') {
  5894. this.hadturncandidate = true;
  5895. }
  5896. if (this.usetrickle) {
  5897. if (this.usedrip) {
  5898. if (this.drip_container.length === 0) {
  5899. // start 20ms callout
  5900. window.setTimeout(function () {
  5901. if (self.drip_container.length === 0) return;
  5902. self.sendIceCandidates(self.drip_container);
  5903. self.drip_container = [];
  5904. }, 20);
  5905. }
  5906. this.drip_container.push(candidate);
  5907. return;
  5908. } else {
  5909. self.sendIceCandidate([candidate]);
  5910. }
  5911. }
  5912. } else {
  5913. //logger.log('sendIceCandidate: last candidate.');
  5914. if (!this.usetrickle) {
  5915. //logger.log('should send full offer now...');
  5916. //FIXME why do we generate session-accept in 3 different places ?
  5917. var init = $iq({to: this.peerjid,
  5918. type: 'set'})
  5919. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5920. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  5921. initiator: this.initiator,
  5922. sid: this.sid});
  5923. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  5924. if (self.webrtcIceTcpDisable) {
  5925. this.localSDP.removeTcpCandidates = true;
  5926. }
  5927. if (self.webrtcIceUdpDisable) {
  5928. this.localSDP.removeUdpCandidates = true;
  5929. }
  5930. var sendJingle = function (ssrc) {
  5931. if(!ssrc)
  5932. ssrc = {};
  5933. self.localSDP.toJingle(
  5934. init,
  5935. self.initiator == self.me ? 'initiator' : 'responder',
  5936. ssrc);
  5937. SSRCReplacement.processSessionInit(init);
  5938. self.connection.sendIQ(init,
  5939. function () {
  5940. //logger.log('session initiate ack');
  5941. var ack = {};
  5942. ack.source = 'offer';
  5943. $(document).trigger('ack.jingle', [self.sid, ack]);
  5944. },
  5945. function (stanza) {
  5946. self.state = 'error';
  5947. self.peerconnection.close();
  5948. var error = ($(stanza).find('error').length) ? {
  5949. code: $(stanza).find('error').attr('code'),
  5950. reason: $(stanza).find('error :first')[0].tagName,
  5951. }:{};
  5952. error.source = 'offer';
  5953. JingleSessionPC.onJingleError(self.sid, error);
  5954. },
  5955. 10000);
  5956. };
  5957. sendJingle();
  5958. }
  5959. this.lasticecandidate = true;
  5960. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  5961. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  5962. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  5963. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  5964. }
  5965. }
  5966. };
  5967. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  5968. logger.log('sendIceCandidates', candidates);
  5969. var cand = $iq({to: this.peerjid, type: 'set'})
  5970. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5971. action: 'transport-info',
  5972. initiator: this.initiator,
  5973. sid: this.sid});
  5974. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  5975. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  5976. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  5977. if (cands.length > 0) {
  5978. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  5979. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5980. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  5981. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  5982. }).c('transport', ice);
  5983. for (var i = 0; i < cands.length; i++) {
  5984. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  5985. }
  5986. // add fingerprint
  5987. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  5988. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  5989. tmp.required = true;
  5990. cand.c(
  5991. 'fingerprint',
  5992. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  5993. .t(tmp.fingerprint);
  5994. delete tmp.fingerprint;
  5995. cand.attrs(tmp);
  5996. cand.up();
  5997. }
  5998. cand.up(); // transport
  5999. cand.up(); // content
  6000. }
  6001. }
  6002. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  6003. //logger.log('was this the last candidate', this.lasticecandidate);
  6004. this.connection.sendIQ(cand,
  6005. function () {
  6006. var ack = {};
  6007. ack.source = 'transportinfo';
  6008. $(document).trigger('ack.jingle', [this.sid, ack]);
  6009. },
  6010. function (stanza) {
  6011. var error = ($(stanza).find('error').length) ? {
  6012. code: $(stanza).find('error').attr('code'),
  6013. reason: $(stanza).find('error :first')[0].tagName,
  6014. }:{};
  6015. error.source = 'transportinfo';
  6016. JingleSessionPC.onJingleError(this.sid, error);
  6017. },
  6018. 10000);
  6019. };
  6020. JingleSessionPC.prototype.sendOffer = function () {
  6021. //logger.log('sendOffer...');
  6022. var self = this;
  6023. this.peerconnection.createOffer(function (sdp) {
  6024. self.createdOffer(sdp);
  6025. },
  6026. function (e) {
  6027. logger.error('createOffer failed', e);
  6028. },
  6029. this.media_constraints
  6030. );
  6031. };
  6032. // FIXME createdOffer is never used in jitsi-meet
  6033. JingleSessionPC.prototype.createdOffer = function (sdp) {
  6034. //logger.log('createdOffer', sdp);
  6035. var self = this;
  6036. this.localSDP = new SDP(sdp.sdp);
  6037. //this.localSDP.mangle();
  6038. var sendJingle = function () {
  6039. var init = $iq({to: this.peerjid,
  6040. type: 'set'})
  6041. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6042. action: 'session-initiate',
  6043. initiator: this.initiator,
  6044. sid: this.sid});
  6045. self.localSDP.toJingle(
  6046. init,
  6047. this.initiator == this.me ? 'initiator' : 'responder',
  6048. this.localStreamsSSRC);
  6049. SSRCReplacement.processSessionInit(init);
  6050. self.connection.sendIQ(init,
  6051. function () {
  6052. var ack = {};
  6053. ack.source = 'offer';
  6054. $(document).trigger('ack.jingle', [self.sid, ack]);
  6055. },
  6056. function (stanza) {
  6057. self.state = 'error';
  6058. self.peerconnection.close();
  6059. var error = ($(stanza).find('error').length) ? {
  6060. code: $(stanza).find('error').attr('code'),
  6061. reason: $(stanza).find('error :first')[0].tagName,
  6062. }:{};
  6063. error.source = 'offer';
  6064. JingleSessionPC.onJingleError(self.sid, error);
  6065. },
  6066. 10000);
  6067. }
  6068. sdp.sdp = this.localSDP.raw;
  6069. this.peerconnection.setLocalDescription(sdp,
  6070. function () {
  6071. if(self.usetrickle)
  6072. {
  6073. sendJingle();
  6074. }
  6075. self.setLocalDescription();
  6076. //logger.log('setLocalDescription success');
  6077. },
  6078. function (e) {
  6079. logger.error('setLocalDescription failed', e);
  6080. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6081. }
  6082. );
  6083. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6084. for (var i = 0; i < cands.length; i++) {
  6085. var cand = SDPUtil.parse_icecandidate(cands[i]);
  6086. if (cand.type == 'srflx') {
  6087. this.hadstuncandidate = true;
  6088. } else if (cand.type == 'relay') {
  6089. this.hadturncandidate = true;
  6090. }
  6091. }
  6092. };
  6093. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  6094. var self = this;
  6095. $(contents).each(function (idx, content) {
  6096. var name = $(content).attr('name');
  6097. var mediaType = this.getAttribute('name');
  6098. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6099. ssrcs.each(function () {
  6100. var ssrc = this.getAttribute('ssrc');
  6101. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  6102. function () {
  6103. var owner = this.getAttribute('owner');
  6104. self.ssrcOwners[ssrc] = owner;
  6105. }
  6106. );
  6107. });
  6108. });
  6109. };
  6110. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  6111. return this.ssrcOwners[ssrc];
  6112. };
  6113. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  6114. //logger.log('setting remote description... ', desctype);
  6115. this.remoteSDP = new SDP('');
  6116. if (self.webrtcIceTcpDisable) {
  6117. this.remoteSDP.removeTcpCandidates = true;
  6118. }
  6119. if (self.webrtcIceUdpDisable) {
  6120. this.remoteSDP.removeUdpCandidates = true;
  6121. }
  6122. this.remoteSDP.fromJingle(elem);
  6123. this.readSsrcInfo($(elem).find(">content"));
  6124. if (this.peerconnection.remoteDescription) {
  6125. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  6126. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  6127. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  6128. for (var i = 0; i < pranswer.media.length; i++) {
  6129. // make sure we have ice ufrag and pwd
  6130. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  6131. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  6132. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  6133. } else {
  6134. logger.warn('no ice ufrag?');
  6135. }
  6136. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  6137. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  6138. } else {
  6139. logger.warn('no ice pwd?');
  6140. }
  6141. }
  6142. // copy over candidates
  6143. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  6144. for (var j = 0; j < lines.length; j++) {
  6145. this.remoteSDP.media[i] += lines[j] + '\r\n';
  6146. }
  6147. }
  6148. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6149. }
  6150. }
  6151. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  6152. this.peerconnection.setRemoteDescription(remotedesc,
  6153. function () {
  6154. //logger.log('setRemoteDescription success');
  6155. },
  6156. function (e) {
  6157. logger.error('setRemoteDescription error', e);
  6158. JingleSessionPC.onJingleFatalError(self, e);
  6159. }
  6160. );
  6161. };
  6162. /**
  6163. * Adds remote ICE candidates to this Jingle session.
  6164. * @param elem An array of Jingle "content" elements?
  6165. */
  6166. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  6167. var self = this;
  6168. if (this.peerconnection.signalingState == 'closed') {
  6169. return;
  6170. }
  6171. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  6172. logger.log('trickle ice candidate arriving before session accept...');
  6173. // create a PRANSWER for setRemoteDescription
  6174. if (!this.remoteSDP) {
  6175. var cobbled = 'v=0\r\n' +
  6176. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6177. 's=-\r\n' +
  6178. 't=0 0\r\n';
  6179. // first, take some things from the local description
  6180. for (var i = 0; i < this.localSDP.media.length; i++) {
  6181. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  6182. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  6183. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  6184. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  6185. }
  6186. cobbled += 'a=inactive\r\n';
  6187. }
  6188. this.remoteSDP = new SDP(cobbled);
  6189. }
  6190. // then add things like ice and dtls from remote candidate
  6191. elem.each(function () {
  6192. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  6193. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6194. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6195. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  6196. var tmp = $(this).find('transport');
  6197. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  6198. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  6199. tmp = $(this).find('transport>fingerprint');
  6200. if (tmp.length) {
  6201. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  6202. } else {
  6203. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  6204. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  6205. }
  6206. break;
  6207. }
  6208. }
  6209. }
  6210. });
  6211. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  6212. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  6213. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  6214. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  6215. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  6216. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  6217. }).length == this.remoteSDP.media.length;
  6218. if (iscomplete) {
  6219. logger.log('setting pranswer');
  6220. try {
  6221. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  6222. function() {
  6223. },
  6224. function(e) {
  6225. logger.log('setRemoteDescription pranswer failed', e.toString());
  6226. });
  6227. } catch (e) {
  6228. logger.error('setting pranswer failed', e);
  6229. }
  6230. } else {
  6231. //logger.log('not yet setting pranswer');
  6232. }
  6233. }
  6234. // operate on each content element
  6235. elem.each(function () {
  6236. // would love to deactivate this, but firefox still requires it
  6237. var idx = -1;
  6238. var i;
  6239. for (i = 0; i < self.remoteSDP.media.length; i++) {
  6240. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6241. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6242. idx = i;
  6243. break;
  6244. }
  6245. }
  6246. if (idx == -1) { // fall back to localdescription
  6247. for (i = 0; i < self.localSDP.media.length; i++) {
  6248. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  6249. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  6250. idx = i;
  6251. break;
  6252. }
  6253. }
  6254. }
  6255. var name = $(this).attr('name');
  6256. // TODO: check ice-pwd and ice-ufrag?
  6257. $(this).find('transport>candidate').each(function () {
  6258. var line, candidate;
  6259. var protocol = this.getAttribute('protocol');
  6260. protocol =
  6261. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  6262. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  6263. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  6264. return;
  6265. }
  6266. line = SDPUtil.candidateFromJingle(this);
  6267. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  6268. sdpMid: name,
  6269. candidate: line});
  6270. try {
  6271. self.peerconnection.addIceCandidate(candidate);
  6272. } catch (e) {
  6273. logger.error('addIceCandidate failed', e.toString(), line);
  6274. }
  6275. });
  6276. });
  6277. };
  6278. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  6279. //logger.log('createAnswer', provisional);
  6280. var self = this;
  6281. this.peerconnection.createAnswer(
  6282. function (sdp) {
  6283. self.createdAnswer(sdp, provisional);
  6284. },
  6285. function (e) {
  6286. logger.error('createAnswer failed', e);
  6287. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6288. },
  6289. this.media_constraints
  6290. );
  6291. };
  6292. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  6293. //logger.log('createAnswer callback');
  6294. var self = this;
  6295. this.localSDP = new SDP(sdp.sdp);
  6296. //this.localSDP.mangle();
  6297. this.usepranswer = provisional === true;
  6298. if (this.usetrickle) {
  6299. if (this.usepranswer) {
  6300. sdp.type = 'pranswer';
  6301. for (var i = 0; i < this.localSDP.media.length; i++) {
  6302. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  6303. }
  6304. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  6305. }
  6306. }
  6307. var self = this;
  6308. var sendJingle = function (ssrcs) {
  6309. // FIXME why do we generate session-accept in 3 different places ?
  6310. var accept = $iq({to: self.peerjid,
  6311. type: 'set'})
  6312. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6313. action: 'session-accept',
  6314. initiator: self.initiator,
  6315. responder: self.responder,
  6316. sid: self.sid });
  6317. if (self.webrtcIceTcpDisable) {
  6318. self.localSDP.removeTcpCandidates = true;
  6319. }
  6320. if (self.webrtcIceUdpDisable) {
  6321. self.localSDP.removeUdpCandidates = true;
  6322. }
  6323. self.localSDP.toJingle(
  6324. accept,
  6325. self.initiator == self.me ? 'initiator' : 'responder',
  6326. ssrcs);
  6327. SSRCReplacement.processSessionInit(accept);
  6328. self.connection.sendIQ(accept,
  6329. function () {
  6330. var ack = {};
  6331. ack.source = 'answer';
  6332. $(document).trigger('ack.jingle', [self.sid, ack]);
  6333. },
  6334. function (stanza) {
  6335. var error = ($(stanza).find('error').length) ? {
  6336. code: $(stanza).find('error').attr('code'),
  6337. reason: $(stanza).find('error :first')[0].tagName,
  6338. }:{};
  6339. error.source = 'answer';
  6340. JingleSessionPC.onJingleError(self.sid, error);
  6341. },
  6342. 10000);
  6343. }
  6344. sdp.sdp = this.localSDP.raw;
  6345. this.peerconnection.setLocalDescription(sdp,
  6346. function () {
  6347. //logger.log('setLocalDescription success');
  6348. if (self.usetrickle && !self.usepranswer) {
  6349. sendJingle();
  6350. }
  6351. self.setLocalDescription();
  6352. },
  6353. function (e) {
  6354. logger.error('setLocalDescription failed', e);
  6355. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6356. }
  6357. );
  6358. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  6359. for (var j = 0; j < cands.length; j++) {
  6360. var cand = SDPUtil.parse_icecandidate(cands[j]);
  6361. if (cand.type == 'srflx') {
  6362. this.hadstuncandidate = true;
  6363. } else if (cand.type == 'relay') {
  6364. this.hadturncandidate = true;
  6365. }
  6366. }
  6367. };
  6368. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  6369. var self = this,
  6370. term = $iq({to: this.peerjid,
  6371. type: 'set'})
  6372. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6373. action: 'session-terminate',
  6374. initiator: this.initiator,
  6375. sid: this.sid})
  6376. .c('reason')
  6377. .c(reason || 'success');
  6378. if (text) {
  6379. term.up().c('text').t(text);
  6380. }
  6381. this.connection.sendIQ(term,
  6382. function () {
  6383. self.peerconnection.close();
  6384. self.peerconnection = null;
  6385. self.terminate();
  6386. var ack = {};
  6387. ack.source = 'terminate';
  6388. $(document).trigger('ack.jingle', [self.sid, ack]);
  6389. },
  6390. function (stanza) {
  6391. var error = ($(stanza).find('error').length) ? {
  6392. code: $(stanza).find('error').attr('code'),
  6393. reason: $(stanza).find('error :first')[0].tagName,
  6394. }:{};
  6395. $(document).trigger('ack.jingle', [self.sid, error]);
  6396. },
  6397. 10000);
  6398. if (this.statsinterval !== null) {
  6399. window.clearInterval(this.statsinterval);
  6400. this.statsinterval = null;
  6401. }
  6402. };
  6403. /**
  6404. * Handles a Jingle source-add message for this Jingle session.
  6405. * @param elem An array of Jingle "content" elements.
  6406. */
  6407. JingleSessionPC.prototype.addSource = function (elem) {
  6408. var self = this;
  6409. // FIXME: dirty waiting
  6410. if (!this.peerconnection.localDescription)
  6411. {
  6412. logger.warn("addSource - localDescription not ready yet")
  6413. setTimeout(function()
  6414. {
  6415. self.addSource(elem);
  6416. },
  6417. 200
  6418. );
  6419. return;
  6420. }
  6421. logger.log('addssrc', new Date().getTime());
  6422. logger.log('ice', this.peerconnection.iceConnectionState);
  6423. this.readSsrcInfo(elem);
  6424. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6425. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6426. $(elem).each(function (idx, content) {
  6427. var name = $(content).attr('name');
  6428. var lines = '';
  6429. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6430. var semantics = this.getAttribute('semantics');
  6431. var ssrcs = $(this).find('>source').map(function () {
  6432. return this.getAttribute('ssrc');
  6433. }).get();
  6434. if (ssrcs.length) {
  6435. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6436. }
  6437. });
  6438. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6439. tmp.each(function () {
  6440. var ssrc = $(this).attr('ssrc');
  6441. if(mySdp.containsSSRC(ssrc)){
  6442. /**
  6443. * This happens when multiple participants change their streams at the same time and
  6444. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  6445. * addssrc are scheduled for update IQ. See
  6446. */
  6447. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  6448. return;
  6449. }
  6450. if (sdp.containsSSRC(ssrc)) {
  6451. logger.warn("Source-add request for existing SSRC: " + ssrc);
  6452. return;
  6453. }
  6454. $(this).find('>parameter').each(function () {
  6455. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6456. if ($(this).attr('value') && $(this).attr('value').length)
  6457. lines += ':' + $(this).attr('value');
  6458. lines += '\r\n';
  6459. });
  6460. });
  6461. sdp.media.forEach(function(media, idx) {
  6462. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6463. return;
  6464. sdp.media[idx] += lines;
  6465. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  6466. self.addssrc[idx] += lines;
  6467. });
  6468. sdp.raw = sdp.session + sdp.media.join('');
  6469. });
  6470. this.modifySourcesQueue.push(function() {
  6471. // When a source is added and if this is FF, a new channel is allocated
  6472. // for receiving the added source. We need to diffuse the SSRC of this
  6473. // new recvonly channel to the rest of the peers.
  6474. logger.log('modify sources done');
  6475. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6476. logger.log("SDPs", mySdp, newSdp);
  6477. self.notifyMySSRCUpdate(mySdp, newSdp);
  6478. });
  6479. };
  6480. /**
  6481. * Handles a Jingle source-remove message for this Jingle session.
  6482. * @param elem An array of Jingle "content" elements.
  6483. */
  6484. JingleSessionPC.prototype.removeSource = function (elem) {
  6485. var self = this;
  6486. // FIXME: dirty waiting
  6487. if (!this.peerconnection.localDescription) {
  6488. logger.warn("removeSource - localDescription not ready yet");
  6489. setTimeout(function() {
  6490. self.removeSource(elem);
  6491. },
  6492. 200
  6493. );
  6494. return;
  6495. }
  6496. logger.log('removessrc', new Date().getTime());
  6497. logger.log('ice', this.peerconnection.iceConnectionState);
  6498. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6499. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  6500. $(elem).each(function (idx, content) {
  6501. var name = $(content).attr('name');
  6502. var lines = '';
  6503. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6504. var semantics = this.getAttribute('semantics');
  6505. var ssrcs = $(this).find('>source').map(function () {
  6506. return this.getAttribute('ssrc');
  6507. }).get();
  6508. if (ssrcs.length) {
  6509. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6510. }
  6511. });
  6512. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  6513. tmp.each(function () {
  6514. var ssrc = $(this).attr('ssrc');
  6515. // This should never happen, but can be useful for bug detection
  6516. if(mySdp.containsSSRC(ssrc)){
  6517. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  6518. return;
  6519. }
  6520. $(this).find('>parameter').each(function () {
  6521. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  6522. if ($(this).attr('value') && $(this).attr('value').length)
  6523. lines += ':' + $(this).attr('value');
  6524. lines += '\r\n';
  6525. });
  6526. });
  6527. sdp.media.forEach(function(media, idx) {
  6528. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  6529. return;
  6530. sdp.media[idx] += lines;
  6531. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  6532. self.removessrc[idx] += lines;
  6533. });
  6534. sdp.raw = sdp.session + sdp.media.join('');
  6535. });
  6536. this.modifySourcesQueue.push(function() {
  6537. // When a source is removed and if this is FF, the recvonly channel that
  6538. // receives the remote stream is deactivated . We need to diffuse the
  6539. // recvonly SSRC removal to the rest of the peers.
  6540. logger.log('modify sources done');
  6541. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6542. logger.log("SDPs", mySdp, newSdp);
  6543. self.notifyMySSRCUpdate(mySdp, newSdp);
  6544. });
  6545. };
  6546. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  6547. var self = this;
  6548. if (this.peerconnection.signalingState == 'closed') return;
  6549. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  6550. || this.switchstreams || this.addingStreams)){
  6551. // There is nothing to do since scheduled job might have been executed by another succeeding call
  6552. this.setLocalDescription();
  6553. if(successCallback){
  6554. successCallback();
  6555. }
  6556. queueCallback();
  6557. return;
  6558. }
  6559. // Reset switch streams flags
  6560. this.switchstreams = false;
  6561. this.addingStreams = false;
  6562. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  6563. // add sources
  6564. this.addssrc.forEach(function(lines, idx) {
  6565. sdp.media[idx] += lines;
  6566. });
  6567. this.addssrc = [];
  6568. // remove sources
  6569. this.removessrc.forEach(function(lines, idx) {
  6570. lines = lines.split('\r\n');
  6571. lines.pop(); // remove empty last element;
  6572. lines.forEach(function(line) {
  6573. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  6574. });
  6575. });
  6576. this.removessrc = [];
  6577. sdp.raw = sdp.session + sdp.media.join('');
  6578. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  6579. function() {
  6580. if(self.signalingState == 'closed') {
  6581. logger.error("createAnswer attempt on closed state");
  6582. queueCallback("createAnswer attempt on closed state");
  6583. return;
  6584. }
  6585. self.peerconnection.createAnswer(
  6586. function(modifiedAnswer) {
  6587. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  6588. if (self.pendingop !== null) {
  6589. var sdp = new SDP(modifiedAnswer.sdp);
  6590. if (sdp.media.length > 1) {
  6591. switch(self.pendingop) {
  6592. case 'mute':
  6593. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  6594. break;
  6595. case 'unmute':
  6596. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  6597. break;
  6598. }
  6599. sdp.raw = sdp.session + sdp.media.join('');
  6600. modifiedAnswer.sdp = sdp.raw;
  6601. }
  6602. self.pendingop = null;
  6603. }
  6604. // FIXME: pushing down an answer while ice connection state
  6605. // is still checking is bad...
  6606. //logger.log(self.peerconnection.iceConnectionState);
  6607. // trying to work around another chrome bug
  6608. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  6609. self.peerconnection.setLocalDescription(modifiedAnswer,
  6610. function() {
  6611. //logger.log('modified setLocalDescription ok');
  6612. self.setLocalDescription();
  6613. if(successCallback){
  6614. successCallback();
  6615. }
  6616. queueCallback();
  6617. },
  6618. function(error) {
  6619. logger.error('modified setLocalDescription failed', error);
  6620. queueCallback(error);
  6621. }
  6622. );
  6623. },
  6624. function(error) {
  6625. logger.error('modified answer failed', error);
  6626. queueCallback(error);
  6627. }
  6628. );
  6629. },
  6630. function(error) {
  6631. logger.error('modify failed', error);
  6632. queueCallback(error);
  6633. }
  6634. );
  6635. };
  6636. /**
  6637. * Switches video streams.
  6638. * @param newStream new stream that will be used as video of this session.
  6639. * @param oldStream old video stream of this session.
  6640. * @param successCallback callback executed after successful stream switch.
  6641. * @param isAudio whether the streams are audio (if true) or video (if false).
  6642. */
  6643. JingleSessionPC.prototype.switchStreams =
  6644. function (newStream, oldStream, successCallback, isAudio) {
  6645. var self = this;
  6646. var sender, newTrack;
  6647. var senderKind = isAudio ? 'audio' : 'video';
  6648. // Remember SDP to figure out added/removed SSRCs
  6649. var oldSdp = null;
  6650. if (self.peerconnection) {
  6651. if (self.peerconnection.localDescription) {
  6652. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6653. }
  6654. if (RTCBrowserType.getBrowserType() ===
  6655. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  6656. // On Firefox we don't replace MediaStreams as this messes up the
  6657. // m-lines (which can't be removed in Plan Unified) and brings a lot
  6658. // of complications. Instead, we use the RTPSender and replace just
  6659. // the track.
  6660. // Find the right sender (for audio or video)
  6661. self.peerconnection.peerconnection.getSenders().some(function (s) {
  6662. if (s.track && s.track.kind === senderKind) {
  6663. sender = s;
  6664. return true;
  6665. }
  6666. });
  6667. if (sender) {
  6668. // We assume that our streams have a single track, either audio
  6669. // or video.
  6670. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  6671. newStream.getVideoTracks()[0];
  6672. sender.replaceTrack(newTrack)
  6673. .then(function() {
  6674. console.log("Replaced a track, isAudio=" + isAudio);
  6675. })
  6676. .catch(function(err) {
  6677. console.log("Failed to replace a track: " + err);
  6678. });
  6679. } else {
  6680. console.log("Cannot switch tracks: no RTPSender.");
  6681. }
  6682. } else {
  6683. self.peerconnection.removeStream(oldStream, true);
  6684. if (newStream) {
  6685. self.peerconnection.addStream(newStream);
  6686. }
  6687. }
  6688. }
  6689. // Conference is not active
  6690. if (!oldSdp) {
  6691. successCallback();
  6692. return;
  6693. }
  6694. self.switchstreams = true;
  6695. self.modifySourcesQueue.push(function() {
  6696. logger.log('modify sources done');
  6697. successCallback();
  6698. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6699. logger.log("SDPs", oldSdp, newSdp);
  6700. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6701. });
  6702. };
  6703. /**
  6704. * Adds streams.
  6705. * @param stream new stream that will be added.
  6706. * @param success_callback callback executed after successful stream addition.
  6707. */
  6708. JingleSessionPC.prototype.addStream = function (stream, callback) {
  6709. var self = this;
  6710. // Remember SDP to figure out added/removed SSRCs
  6711. var oldSdp = null;
  6712. if(this.peerconnection) {
  6713. if(this.peerconnection.localDescription) {
  6714. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  6715. }
  6716. if(stream)
  6717. this.peerconnection.addStream(stream);
  6718. }
  6719. // Conference is not active
  6720. if(!oldSdp || !this.peerconnection) {
  6721. callback();
  6722. return;
  6723. }
  6724. this.addingStreams = true;
  6725. this.modifySourcesQueue.push(function() {
  6726. logger.log('modify sources done');
  6727. callback();
  6728. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6729. logger.log("SDPs", oldSdp, newSdp);
  6730. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6731. });
  6732. }
  6733. /**
  6734. * Figures out added/removed ssrcs and send update IQs.
  6735. * @param old_sdp SDP object for old description.
  6736. * @param new_sdp SDP object for new description.
  6737. */
  6738. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  6739. if (!(this.peerconnection.signalingState == 'stable' &&
  6740. this.peerconnection.iceConnectionState == 'connected')){
  6741. logger.log("Too early to send updates");
  6742. return;
  6743. }
  6744. // send source-remove IQ.
  6745. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  6746. var remove = $iq({to: this.peerjid, type: 'set'})
  6747. .c('jingle', {
  6748. xmlns: 'urn:xmpp:jingle:1',
  6749. action: 'source-remove',
  6750. initiator: this.initiator,
  6751. sid: this.sid
  6752. }
  6753. );
  6754. var removed = sdpDiffer.toJingle(remove);
  6755. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  6756. // it in the current form
  6757. if (removed)
  6758. remove = SSRCReplacement.processSourceRemove(remove);
  6759. if (removed && remove) {
  6760. logger.info("Sending source-remove", remove);
  6761. this.connection.sendIQ(remove,
  6762. function (res) {
  6763. logger.info('got remove result', res);
  6764. },
  6765. function (err) {
  6766. logger.error('got remove error', err);
  6767. }
  6768. );
  6769. } else {
  6770. logger.log('removal not necessary');
  6771. }
  6772. // send source-add IQ.
  6773. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  6774. var add = $iq({to: this.peerjid, type: 'set'})
  6775. .c('jingle', {
  6776. xmlns: 'urn:xmpp:jingle:1',
  6777. action: 'source-add',
  6778. initiator: this.initiator,
  6779. sid: this.sid
  6780. }
  6781. );
  6782. var added = sdpDiffer.toJingle(add);
  6783. // Let 'source-add' IQ through the hack and see if we're allowed to send
  6784. // it in the current form
  6785. if (added)
  6786. add = SSRCReplacement.processSourceAdd(add);
  6787. if (added && add) {
  6788. logger.info("Sending source-add", add);
  6789. this.connection.sendIQ(add,
  6790. function (res) {
  6791. logger.info('got add result', res);
  6792. },
  6793. function (err) {
  6794. logger.error('got add error', err);
  6795. }
  6796. );
  6797. } else {
  6798. logger.log('addition not necessary');
  6799. }
  6800. };
  6801. /**
  6802. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  6803. *
  6804. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  6805. * tracks; otherwise, <tt>false</tt>
  6806. * @param callback a function to be invoked with <tt>mute</tt> after all video
  6807. * tracks have been enabled/disabled. The function may, optionally, return
  6808. * another function which is to be invoked after the whole mute/unmute operation
  6809. * has completed successfully.
  6810. * @param options an object which specifies optional arguments such as the
  6811. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  6812. * specifies whether the method was initiated in response to a user command (in
  6813. * contrast to an automatic decision made by the application logic)
  6814. */
  6815. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  6816. var byUser;
  6817. if (options) {
  6818. byUser = options.byUser;
  6819. if (typeof byUser === 'undefined') {
  6820. byUser = true;
  6821. }
  6822. } else {
  6823. byUser = true;
  6824. }
  6825. // The user's command to mute the (local) video takes precedence over any
  6826. // automatic decision made by the application logic.
  6827. if (byUser) {
  6828. this.videoMuteByUser = mute;
  6829. } else if (this.videoMuteByUser) {
  6830. return;
  6831. }
  6832. this.hardMuteVideo(mute);
  6833. var self = this;
  6834. var oldSdp = null;
  6835. if(self.peerconnection) {
  6836. if(self.peerconnection.localDescription) {
  6837. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  6838. }
  6839. }
  6840. this.modifySourcesQueue.push(function() {
  6841. logger.log('modify sources done');
  6842. callback(mute);
  6843. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  6844. logger.log("SDPs", oldSdp, newSdp);
  6845. self.notifyMySSRCUpdate(oldSdp, newSdp);
  6846. });
  6847. };
  6848. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  6849. this.pendingop = muted ? 'mute' : 'unmute';
  6850. };
  6851. JingleSessionPC.prototype.sendMute = function (muted, content) {
  6852. var info = $iq({to: this.peerjid,
  6853. type: 'set'})
  6854. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6855. action: 'session-info',
  6856. initiator: this.initiator,
  6857. sid: this.sid });
  6858. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6859. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  6860. if (content) {
  6861. info.attrs({'name': content});
  6862. }
  6863. this.connection.send(info);
  6864. };
  6865. JingleSessionPC.prototype.sendRinging = function () {
  6866. var info = $iq({to: this.peerjid,
  6867. type: 'set'})
  6868. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  6869. action: 'session-info',
  6870. initiator: this.initiator,
  6871. sid: this.sid });
  6872. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  6873. this.connection.send(info);
  6874. };
  6875. JingleSessionPC.prototype.getStats = function (interval) {
  6876. var self = this;
  6877. var recv = {audio: 0, video: 0};
  6878. var lost = {audio: 0, video: 0};
  6879. var lastrecv = {audio: 0, video: 0};
  6880. var lastlost = {audio: 0, video: 0};
  6881. var loss = {audio: 0, video: 0};
  6882. var delta = {audio: 0, video: 0};
  6883. this.statsinterval = window.setInterval(function () {
  6884. if (self && self.peerconnection && self.peerconnection.getStats) {
  6885. self.peerconnection.getStats(function (stats) {
  6886. var results = stats.result();
  6887. // TODO: there are so much statistics you can get from this..
  6888. for (var i = 0; i < results.length; ++i) {
  6889. if (results[i].type == 'ssrc') {
  6890. var packetsrecv = results[i].stat('packetsReceived');
  6891. var packetslost = results[i].stat('packetsLost');
  6892. if (packetsrecv && packetslost) {
  6893. packetsrecv = parseInt(packetsrecv, 10);
  6894. packetslost = parseInt(packetslost, 10);
  6895. if (results[i].stat('googFrameRateReceived')) {
  6896. lastlost.video = lost.video;
  6897. lastrecv.video = recv.video;
  6898. recv.video = packetsrecv;
  6899. lost.video = packetslost;
  6900. } else {
  6901. lastlost.audio = lost.audio;
  6902. lastrecv.audio = recv.audio;
  6903. recv.audio = packetsrecv;
  6904. lost.audio = packetslost;
  6905. }
  6906. }
  6907. }
  6908. }
  6909. delta.audio = recv.audio - lastrecv.audio;
  6910. delta.video = recv.video - lastrecv.video;
  6911. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  6912. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  6913. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  6914. });
  6915. }
  6916. }, interval || 3000);
  6917. return this.statsinterval;
  6918. };
  6919. JingleSessionPC.onJingleError = function (session, error)
  6920. {
  6921. logger.error("Jingle error", error);
  6922. }
  6923. JingleSessionPC.onJingleFatalError = function (session, error)
  6924. {
  6925. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  6926. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  6927. }
  6928. JingleSessionPC.prototype.setLocalDescription = function () {
  6929. var self = this;
  6930. var newssrcs = [];
  6931. if(!this.peerconnection.localDescription)
  6932. return;
  6933. var session = transform.parse(this.peerconnection.localDescription.sdp);
  6934. var i;
  6935. session.media.forEach(function (media) {
  6936. if (media.ssrcs && media.ssrcs.length > 0) {
  6937. // TODO(gp) maybe exclude FID streams?
  6938. media.ssrcs.forEach(function (ssrc) {
  6939. if (ssrc.attribute !== 'cname') {
  6940. return;
  6941. }
  6942. newssrcs.push({
  6943. 'ssrc': ssrc.id,
  6944. 'type': media.type
  6945. });
  6946. });
  6947. }
  6948. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  6949. {
  6950. newssrcs.push({
  6951. 'ssrc': self.localStreamsSSRC[media.type],
  6952. 'type': media.type
  6953. });
  6954. }
  6955. });
  6956. logger.log('new ssrcs', newssrcs);
  6957. // Bind us as local SSRCs owner
  6958. if (newssrcs.length > 0) {
  6959. for (i = 0; i < newssrcs.length; i++) {
  6960. var ssrc = newssrcs[i].ssrc;
  6961. var myJid = self.connection.emuc.myroomjid;
  6962. self.ssrcOwners[ssrc] = myJid;
  6963. }
  6964. }
  6965. }
  6966. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  6967. JingleSessionPC.prototype.sendKeyframe = function () {
  6968. var pc = this.peerconnection;
  6969. logger.log('sendkeyframe', pc.iceConnectionState);
  6970. if (pc.iceConnectionState !== 'connected') return; // safe...
  6971. var self = this;
  6972. pc.setRemoteDescription(
  6973. pc.remoteDescription,
  6974. function () {
  6975. pc.createAnswer(
  6976. function (modifiedAnswer) {
  6977. pc.setLocalDescription(
  6978. modifiedAnswer,
  6979. function () {
  6980. // noop
  6981. },
  6982. function (error) {
  6983. logger.log('triggerKeyframe setLocalDescription failed', error);
  6984. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  6985. }
  6986. );
  6987. },
  6988. function (error) {
  6989. logger.log('triggerKeyframe createAnswer failed', error);
  6990. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  6991. }
  6992. );
  6993. },
  6994. function (error) {
  6995. logger.log('triggerKeyframe setRemoteDescription failed', error);
  6996. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  6997. }
  6998. );
  6999. }
  7000. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  7001. var self = this;
  7002. var thessrc;
  7003. var streamId = RTC.getStreamID(data.stream);
  7004. // look up an associated JID for a stream id
  7005. if (!streamId) {
  7006. logger.error("No stream ID for", data.stream);
  7007. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  7008. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  7009. var ssrclines = this.peerconnection.remoteDescription?
  7010. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  7011. ssrclines = ssrclines.filter(function (line) {
  7012. // NOTE(gp) previously we filtered on the mslabel, but that property
  7013. // is not always present.
  7014. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  7015. if (RTCBrowserType.isTemasysPluginUsed()) {
  7016. return ((line.indexOf('mslabel:' + streamId) !== -1));
  7017. } else {
  7018. return ((line.indexOf('msid:' + streamId) !== -1));
  7019. }
  7020. });
  7021. if (ssrclines.length) {
  7022. thessrc = ssrclines[0].substring(7).split(' ')[0];
  7023. if (!self.ssrcOwners[thessrc]) {
  7024. logger.error("No SSRC owner known for: " + thessrc);
  7025. return;
  7026. }
  7027. data.peerjid = self.ssrcOwners[thessrc];
  7028. logger.log('associated jid', self.ssrcOwners[thessrc]);
  7029. } else {
  7030. logger.error("No SSRC lines for ", streamId);
  7031. }
  7032. }
  7033. this.room.remoteStreamAdded(data, this.sid, thessrc);
  7034. var isVideo = data.stream.getVideoTracks().length > 0;
  7035. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  7036. if (isVideo &&
  7037. data.peerjid && this.peerjid === data.peerjid &&
  7038. data.stream.getVideoTracks().length === 0 &&
  7039. RTC.localVideo.getTracks().length > 0) {
  7040. window.setTimeout(function () {
  7041. self.sendKeyframe();
  7042. }, 3000);
  7043. }
  7044. }
  7045. module.exports = JingleSessionPC;
  7046. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  7047. },{"../../service/xmpp/XMPPEvents":84,"../RTC/RTC":13,"../RTC/RTCBrowserType":14,"./JingleSession":25,"./LocalSSRCReplacement":27,"./SDP":28,"./SDPDiffer":29,"./SDPUtil":30,"./TraceablePeerConnection":31,"async":40,"jitsi-meet-logger":45,"sdp-transform":73}],27:[function(require,module,exports){
  7048. (function (__filename){
  7049. /* global $ */
  7050. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7051. /*
  7052. Here we do modifications of local video SSRCs. There are 2 situations we have
  7053. to handle:
  7054. 1. We generate SSRC for local recvonly video stream. This is the case when we
  7055. have no local camera and it is not generated automatically, but SSRC=1 is
  7056. used implicitly. If that happens RTCP packets will be dropped by the JVB
  7057. and we won't be able to request video key frames correctly.
  7058. 2. A hack to re-use SSRC of the first video stream for any new stream created
  7059. in future. It turned out that Chrome may keep on using the SSRC of removed
  7060. video stream in RTCP even though a new one has been created. So we just
  7061. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  7062. notifications are blocked once first video SSRC is advertised to the focus.
  7063. What this hack does:
  7064. 1. Stores the SSRC of the first video stream created by
  7065. a) scanning Jingle session-accept/session-invite for existing video SSRC
  7066. b) watching for 'source-add' for new video stream if it has not been
  7067. created in step a)
  7068. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  7069. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  7070. returned to the other parts of the application.
  7071. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  7072. blocks those notifications. This makes Jicofo and all participants think
  7073. that it exists all the time even if the video stream has been removed or
  7074. replaced locally. Thanks to that there is no additional signaling activity
  7075. on video mute or when switching to the desktop stream.
  7076. */
  7077. var SDP = require('./SDP');
  7078. var RandomUtil = require('../util/RandomUtil');
  7079. var RTCBrowserType = require('../RTC/RTCBrowserType');
  7080. /**
  7081. * The hack is enabled on all browsers except FF by default
  7082. * FIXME finish the hack once removeStream method is implemented in FF
  7083. * @type {boolean}
  7084. */
  7085. var isEnabled = !RTCBrowserType.isFirefox();
  7086. /**
  7087. * Stored SSRC of local video stream.
  7088. */
  7089. var localVideoSSRC;
  7090. /**
  7091. * SSRC, msid, mslabel, label used for recvonly video stream when we have no local camera.
  7092. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  7093. * instead of 1.
  7094. */
  7095. var localRecvOnlySSRC, localRecvOnlyMSID, localRecvOnlyMSLabel, localRecvOnlyLabel;
  7096. /**
  7097. * cname for <tt>localRecvOnlySSRC</tt>
  7098. */
  7099. var localRecvOnlyCName;
  7100. /**
  7101. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  7102. * from given Jingle IQ.
  7103. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  7104. * @param actionName display name of the action which will be printed in log
  7105. * messages.
  7106. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  7107. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  7108. * other SSRCs left to be signaled after removing it.
  7109. */
  7110. var filterOutSource = function (modifyIq, actionName) {
  7111. var modifyIqTree = $(modifyIq.tree());
  7112. if (!localVideoSSRC)
  7113. return modifyIqTree[0];
  7114. var videoSSRC = modifyIqTree.find(
  7115. '>jingle>content[name="video"]' +
  7116. '>description>source[ssrc="' + localVideoSSRC + '"]');
  7117. if (!videoSSRC.length) {
  7118. return modifyIqTree[0];
  7119. }
  7120. logger.info(
  7121. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  7122. videoSSRC.remove();
  7123. // Check if any sources still left to be added/removed
  7124. if (modifyIqTree.find('>jingle>content>description>source').length) {
  7125. return modifyIqTree[0];
  7126. } else {
  7127. return null;
  7128. }
  7129. };
  7130. /**
  7131. * Scans given Jingle IQ for video SSRC and stores it.
  7132. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  7133. */
  7134. var storeLocalVideoSSRC = function (jingleIq) {
  7135. var videoSSRCs =
  7136. $(jingleIq.tree())
  7137. .find('>jingle>content[name="video"]>description>source');
  7138. videoSSRCs.each(function (idx, ssrcElem) {
  7139. if (localVideoSSRC)
  7140. return;
  7141. // We consider SSRC real only if it has msid attribute
  7142. // recvonly streams in FF do not have it as well as local SSRCs
  7143. // we generate for recvonly streams in Chrome
  7144. var ssrSel = $(ssrcElem);
  7145. var msid = ssrSel.find('>parameter[name="msid"]');
  7146. if (msid.length) {
  7147. var ssrcVal = ssrSel.attr('ssrc');
  7148. if (ssrcVal) {
  7149. localVideoSSRC = ssrcVal;
  7150. logger.info('Stored local video SSRC' +
  7151. ' for future re-use: ' + localVideoSSRC);
  7152. }
  7153. }
  7154. });
  7155. };
  7156. /**
  7157. * Generates new label/mslabel attribute
  7158. * @returns {string} label/mslabel attribute
  7159. */
  7160. function generateLabel() {
  7161. return RandomUtil.randomHexString(8) + "-" + RandomUtil.randomHexString(4) +
  7162. "-" + RandomUtil.randomHexString(4) + "-" +
  7163. RandomUtil.randomHexString(4) + "-" + RandomUtil.randomHexString(12);
  7164. }
  7165. /**
  7166. * Generates new SSRC, CNAME, mslabel, label and msid for local video recvonly stream.
  7167. * FIXME what about eventual SSRC collision ?
  7168. */
  7169. function generateRecvonlySSRC() {
  7170. localRecvOnlySSRC =
  7171. Math.random().toString(10).substring(2, 11);
  7172. localRecvOnlyCName =
  7173. Math.random().toString(36).substring(2);
  7174. localRecvOnlyMSLabel = generateLabel();
  7175. localRecvOnlyLabel = generateLabel();
  7176. localRecvOnlyMSID = localRecvOnlyMSLabel + " " + localRecvOnlyLabel;
  7177. logger.info(
  7178. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  7179. ", cname: " + localRecvOnlyCName);
  7180. }
  7181. var LocalSSRCReplacement = {
  7182. /**
  7183. * Method must be called before 'session-initiate' or 'session-invite' is
  7184. * sent. Scans the IQ for local video SSRC and stores it if detected.
  7185. *
  7186. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  7187. * which will be scanned for local video SSRC.
  7188. */
  7189. processSessionInit: function (sessionInit) {
  7190. if (!isEnabled)
  7191. return;
  7192. if (localVideoSSRC) {
  7193. logger.error("Local SSRC stored already: " + localVideoSSRC);
  7194. return;
  7195. }
  7196. storeLocalVideoSSRC(sessionInit);
  7197. },
  7198. /**
  7199. * If we have local video SSRC stored searched given
  7200. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  7201. * with the stored one.
  7202. * @param localDescription local description object that will have local
  7203. * video SSRC replaced with the stored one
  7204. * @returns modified <tt>localDescription</tt> object.
  7205. */
  7206. mungeLocalVideoSSRC: function (localDescription) {
  7207. if (!isEnabled)
  7208. return localDescription;
  7209. if (!localDescription) {
  7210. logger.warn("localDescription is null or undefined");
  7211. return localDescription;
  7212. }
  7213. // IF we have local video SSRC stored make sure it is replaced
  7214. // with old SSRC
  7215. if (localVideoSSRC) {
  7216. var newSdp = new SDP(localDescription.sdp);
  7217. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  7218. !newSdp.containsSSRC(localVideoSSRC)) {
  7219. // Get new video SSRC
  7220. var map = newSdp.getMediaSsrcMap();
  7221. var videoPart = map[1];
  7222. var videoSSRCs = videoPart.ssrcs;
  7223. var newSSRC = Object.keys(videoSSRCs)[0];
  7224. logger.info(
  7225. "Replacing new video SSRC: " + newSSRC +
  7226. " with " + localVideoSSRC);
  7227. localDescription.sdp =
  7228. newSdp.raw.replace(
  7229. new RegExp('a=ssrc:' + newSSRC, 'g'),
  7230. 'a=ssrc:' + localVideoSSRC);
  7231. }
  7232. } else {
  7233. // Make sure we have any SSRC for recvonly video stream
  7234. var sdp = new SDP(localDescription.sdp);
  7235. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  7236. sdp.media[1].indexOf('a=recvonly') !== -1) {
  7237. if (!localRecvOnlySSRC) {
  7238. generateRecvonlySSRC();
  7239. }
  7240. localVideoSSRC = localRecvOnlySSRC;
  7241. logger.info('No SSRC in video recvonly stream' +
  7242. ' - adding SSRC: ' + localRecvOnlySSRC);
  7243. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  7244. ' cname:' + localRecvOnlyCName + '\r\n' +
  7245. 'a=ssrc:' + localRecvOnlySSRC +
  7246. ' msid:' + localRecvOnlyMSID + '\r\n' +
  7247. 'a=ssrc:' + localRecvOnlySSRC +
  7248. ' mslabel:' + localRecvOnlyMSLabel + '\r\n' +
  7249. 'a=ssrc:' + localRecvOnlySSRC +
  7250. ' label:' + localRecvOnlyLabel + '\r\n';
  7251. localDescription.sdp = sdp.session + sdp.media.join('');
  7252. }
  7253. }
  7254. return localDescription;
  7255. },
  7256. /**
  7257. * Method must be called before 'source-add' notification is sent. In case
  7258. * we have local video SSRC advertised already it will be removed from the
  7259. * notification. If no other SSRCs are described by given IQ null will be
  7260. * returned which means that there is no point in sending the notification.
  7261. * @param sourceAdd 'source-add' Jingle IQ to be processed
  7262. * @returns modified 'source-add' IQ which can be sent to the focus or
  7263. * <tt>null</tt> if no notification shall be sent. It is no longer
  7264. * a Strophe IQ Builder instance, but DOM element tree.
  7265. */
  7266. processSourceAdd: function (sourceAdd) {
  7267. if (!isEnabled)
  7268. return sourceAdd;
  7269. if (!localVideoSSRC) {
  7270. // Store local SSRC if available
  7271. storeLocalVideoSSRC(sourceAdd);
  7272. return sourceAdd;
  7273. } else {
  7274. return filterOutSource(sourceAdd, 'source-add');
  7275. }
  7276. },
  7277. /**
  7278. * Method must be called before 'source-remove' notification is sent.
  7279. * Removes local video SSRC from the notification. If there are no other
  7280. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  7281. * means that there is no point in sending the notification.
  7282. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  7283. * @returns modified 'source-remove' IQ which can be sent to the focus or
  7284. * <tt>null</tt> if no notification shall be sent. It is no longer
  7285. * a Strophe IQ Builder instance, but DOM element tree.
  7286. */
  7287. processSourceRemove: function (sourceRemove) {
  7288. if (!isEnabled)
  7289. return sourceRemove;
  7290. return filterOutSource(sourceRemove, 'source-remove');
  7291. },
  7292. /**
  7293. * Turns the hack on or off
  7294. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  7295. * to disable it
  7296. */
  7297. setEnabled: function (enabled) {
  7298. isEnabled = enabled;
  7299. }
  7300. };
  7301. module.exports = LocalSSRCReplacement;
  7302. }).call(this,"/modules/xmpp/LocalSSRCReplacement.js")
  7303. },{"../RTC/RTCBrowserType":14,"../util/RandomUtil":23,"./SDP":28,"jitsi-meet-logger":45}],28:[function(require,module,exports){
  7304. (function (__filename){
  7305. /* jshint -W117 */
  7306. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7307. var SDPUtil = require("./SDPUtil");
  7308. // SDP STUFF
  7309. function SDP(sdp) {
  7310. /**
  7311. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  7312. * @type {boolean}
  7313. */
  7314. this.removeTcpCandidates = false;
  7315. /**
  7316. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  7317. * @type {boolean}
  7318. */
  7319. this.removeUdpCandidates = false;
  7320. this.media = sdp.split('\r\nm=');
  7321. for (var i = 1; i < this.media.length; i++) {
  7322. this.media[i] = 'm=' + this.media[i];
  7323. if (i != this.media.length - 1) {
  7324. this.media[i] += '\r\n';
  7325. }
  7326. }
  7327. this.session = this.media.shift() + '\r\n';
  7328. this.raw = this.session + this.media.join('');
  7329. }
  7330. /**
  7331. * Returns map of MediaChannel mapped per channel idx.
  7332. */
  7333. SDP.prototype.getMediaSsrcMap = function() {
  7334. var self = this;
  7335. var media_ssrcs = {};
  7336. var tmp;
  7337. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  7338. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  7339. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  7340. var media = {
  7341. mediaindex: mediaindex,
  7342. mid: mid,
  7343. ssrcs: {},
  7344. ssrcGroups: []
  7345. };
  7346. media_ssrcs[mediaindex] = media;
  7347. tmp.forEach(function (line) {
  7348. var linessrc = line.substring(7).split(' ')[0];
  7349. // allocate new ChannelSsrc
  7350. if(!media.ssrcs[linessrc]) {
  7351. media.ssrcs[linessrc] = {
  7352. ssrc: linessrc,
  7353. lines: []
  7354. };
  7355. }
  7356. media.ssrcs[linessrc].lines.push(line);
  7357. });
  7358. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  7359. tmp.forEach(function(line){
  7360. var idx = line.indexOf(' ');
  7361. var semantics = line.substr(0, idx).substr(13);
  7362. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7363. if (ssrcs.length) {
  7364. media.ssrcGroups.push({
  7365. semantics: semantics,
  7366. ssrcs: ssrcs
  7367. });
  7368. }
  7369. });
  7370. }
  7371. return media_ssrcs;
  7372. };
  7373. /**
  7374. * Returns <tt>true</tt> if this SDP contains given SSRC.
  7375. * @param ssrc the ssrc to check.
  7376. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  7377. */
  7378. SDP.prototype.containsSSRC = function(ssrc) {
  7379. var medias = this.getMediaSsrcMap();
  7380. Object.keys(medias).forEach(function(mediaindex){
  7381. var media = medias[mediaindex];
  7382. //logger.log("Check", channel, ssrc);
  7383. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  7384. return true;
  7385. }
  7386. });
  7387. return false;
  7388. };
  7389. // remove iSAC and CN from SDP
  7390. SDP.prototype.mangle = function () {
  7391. var i, j, mline, lines, rtpmap, newdesc;
  7392. for (i = 0; i < this.media.length; i++) {
  7393. lines = this.media[i].split('\r\n');
  7394. lines.pop(); // remove empty last element
  7395. mline = SDPUtil.parse_mline(lines.shift());
  7396. if (mline.media != 'audio')
  7397. continue;
  7398. newdesc = '';
  7399. mline.fmt.length = 0;
  7400. for (j = 0; j < lines.length; j++) {
  7401. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  7402. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  7403. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  7404. continue;
  7405. mline.fmt.push(rtpmap.id);
  7406. newdesc += lines[j] + '\r\n';
  7407. } else {
  7408. newdesc += lines[j] + '\r\n';
  7409. }
  7410. }
  7411. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  7412. this.media[i] += newdesc;
  7413. }
  7414. this.raw = this.session + this.media.join('');
  7415. };
  7416. // remove lines matching prefix from session section
  7417. SDP.prototype.removeSessionLines = function(prefix) {
  7418. var self = this;
  7419. var lines = SDPUtil.find_lines(this.session, prefix);
  7420. lines.forEach(function(line) {
  7421. self.session = self.session.replace(line + '\r\n', '');
  7422. });
  7423. this.raw = this.session + this.media.join('');
  7424. return lines;
  7425. }
  7426. // remove lines matching prefix from a media section specified by mediaindex
  7427. // TODO: non-numeric mediaindex could match mid
  7428. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  7429. var self = this;
  7430. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  7431. lines.forEach(function(line) {
  7432. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  7433. });
  7434. this.raw = this.session + this.media.join('');
  7435. return lines;
  7436. }
  7437. // add content's to a jingle element
  7438. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  7439. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  7440. var self = this;
  7441. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  7442. // new bundle plan
  7443. if (SDPUtil.find_line(this.session, 'a=group:')) {
  7444. lines = SDPUtil.find_lines(this.session, 'a=group:');
  7445. for (i = 0; i < lines.length; i++) {
  7446. tmp = lines[i].split(' ');
  7447. var semantics = tmp.shift().substr(8);
  7448. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  7449. for (j = 0; j < tmp.length; j++) {
  7450. elem.c('content', {name: tmp[j]}).up();
  7451. }
  7452. elem.up();
  7453. }
  7454. }
  7455. for (i = 0; i < this.media.length; i++) {
  7456. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  7457. if (!(mline.media === 'audio' ||
  7458. mline.media === 'video' ||
  7459. mline.media === 'application'))
  7460. {
  7461. continue;
  7462. }
  7463. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  7464. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  7465. } else {
  7466. if(ssrcs && ssrcs[mline.media]) {
  7467. ssrc = ssrcs[mline.media];
  7468. } else {
  7469. ssrc = false;
  7470. }
  7471. }
  7472. elem.c('content', {creator: thecreator, name: mline.media});
  7473. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  7474. // prefer identifier from a=mid if present
  7475. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  7476. elem.attrs({ name: mid });
  7477. }
  7478. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  7479. elem.c('description',
  7480. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  7481. media: mline.media });
  7482. if (ssrc) {
  7483. elem.attrs({ssrc: ssrc});
  7484. }
  7485. for (j = 0; j < mline.fmt.length; j++) {
  7486. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  7487. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  7488. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  7489. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  7490. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  7491. for (k = 0; k < tmp.length; k++) {
  7492. elem.c('parameter', tmp[k]).up();
  7493. }
  7494. }
  7495. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  7496. elem.up();
  7497. }
  7498. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  7499. elem.c('encryption', {required: 1});
  7500. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  7501. crypto.forEach(function(line) {
  7502. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  7503. });
  7504. elem.up(); // end of encryption
  7505. }
  7506. if (ssrc) {
  7507. // new style mapping
  7508. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7509. // FIXME: group by ssrc and support multiple different ssrcs
  7510. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  7511. if(ssrclines.length > 0) {
  7512. ssrclines.forEach(function (line) {
  7513. var idx = line.indexOf(' ');
  7514. var linessrc = line.substr(0, idx).substr(7);
  7515. if (linessrc != ssrc) {
  7516. elem.up();
  7517. ssrc = linessrc;
  7518. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7519. }
  7520. var kv = line.substr(idx + 1);
  7521. elem.c('parameter');
  7522. if (kv.indexOf(':') == -1) {
  7523. elem.attrs({ name: kv });
  7524. } else {
  7525. var k = kv.split(':', 2)[0];
  7526. elem.attrs({ name: k });
  7527. var v = kv.split(':', 2)[1];
  7528. v = SDPUtil.filter_special_chars(v);
  7529. elem.attrs({ value: v });
  7530. }
  7531. elem.up();
  7532. });
  7533. } else {
  7534. elem.up();
  7535. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7536. elem.c('parameter');
  7537. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  7538. elem.up();
  7539. var msid = null;
  7540. if(mline.media == "audio")
  7541. {
  7542. msid = APP.RTC.localAudio.getId();
  7543. }
  7544. else
  7545. {
  7546. msid = APP.RTC.localVideo.getId();
  7547. }
  7548. if(msid != null)
  7549. {
  7550. msid = SDPUtil.filter_special_chars(msid);
  7551. elem.c('parameter');
  7552. elem.attrs({name: "msid", value:msid});
  7553. elem.up();
  7554. elem.c('parameter');
  7555. elem.attrs({name: "mslabel", value:msid});
  7556. elem.up();
  7557. elem.c('parameter');
  7558. elem.attrs({name: "label", value:msid});
  7559. elem.up();
  7560. }
  7561. }
  7562. elem.up();
  7563. // XEP-0339 handle ssrc-group attributes
  7564. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  7565. ssrc_group_lines.forEach(function(line) {
  7566. var idx = line.indexOf(' ');
  7567. var semantics = line.substr(0, idx).substr(13);
  7568. var ssrcs = line.substr(14 + semantics.length).split(' ');
  7569. if (ssrcs.length) {
  7570. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  7571. ssrcs.forEach(function(ssrc) {
  7572. elem.c('source', { ssrc: ssrc })
  7573. .up();
  7574. });
  7575. elem.up();
  7576. }
  7577. });
  7578. }
  7579. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  7580. elem.c('rtcp-mux').up();
  7581. }
  7582. // XEP-0293 -- map a=rtcp-fb:*
  7583. this.rtcpFbToJingle(i, elem, '*');
  7584. // XEP-0294
  7585. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  7586. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  7587. for (j = 0; j < lines.length; j++) {
  7588. tmp = SDPUtil.parse_extmap(lines[j]);
  7589. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  7590. uri: tmp.uri,
  7591. id: tmp.value });
  7592. if (tmp.hasOwnProperty('direction')) {
  7593. switch (tmp.direction) {
  7594. case 'sendonly':
  7595. elem.attrs({senders: 'responder'});
  7596. break;
  7597. case 'recvonly':
  7598. elem.attrs({senders: 'initiator'});
  7599. break;
  7600. case 'sendrecv':
  7601. elem.attrs({senders: 'both'});
  7602. break;
  7603. case 'inactive':
  7604. elem.attrs({senders: 'none'});
  7605. break;
  7606. }
  7607. }
  7608. // TODO: handle params
  7609. elem.up();
  7610. }
  7611. }
  7612. elem.up(); // end of description
  7613. }
  7614. // map ice-ufrag/pwd, dtls fingerprint, candidates
  7615. this.transportToJingle(i, elem);
  7616. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  7617. elem.attrs({senders: 'both'});
  7618. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  7619. elem.attrs({senders: 'initiator'});
  7620. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  7621. elem.attrs({senders: 'responder'});
  7622. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  7623. elem.attrs({senders: 'none'});
  7624. }
  7625. if (mline.port == '0') {
  7626. // estos hack to reject an m-line
  7627. elem.attrs({senders: 'rejected'});
  7628. }
  7629. elem.up(); // end of content
  7630. }
  7631. elem.up();
  7632. return elem;
  7633. };
  7634. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  7635. var tmp, sctpmap, sctpAttrs, fingerprints;
  7636. var self = this;
  7637. elem.c('transport');
  7638. // XEP-0343 DTLS/SCTP
  7639. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  7640. {
  7641. sctpmap = SDPUtil.find_line(
  7642. this.media[mediaindex], 'a=sctpmap:', self.session);
  7643. if (sctpmap)
  7644. {
  7645. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  7646. elem.c('sctpmap',
  7647. {
  7648. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  7649. number: sctpAttrs[0], /* SCTP port */
  7650. protocol: sctpAttrs[1] /* protocol */
  7651. });
  7652. // Optional stream count attribute
  7653. if (sctpAttrs.length > 2)
  7654. elem.attrs({ streams: sctpAttrs[2]});
  7655. elem.up();
  7656. }
  7657. }
  7658. // XEP-0320
  7659. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  7660. fingerprints.forEach(function(line) {
  7661. tmp = SDPUtil.parse_fingerprint(line);
  7662. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  7663. elem.c('fingerprint').t(tmp.fingerprint);
  7664. delete tmp.fingerprint;
  7665. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  7666. if (line) {
  7667. tmp.setup = line.substr(8);
  7668. }
  7669. elem.attrs(tmp);
  7670. elem.up(); // end of fingerprint
  7671. });
  7672. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  7673. if (tmp) {
  7674. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7675. elem.attrs(tmp);
  7676. // XEP-0176
  7677. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  7678. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  7679. lines.forEach(function (line) {
  7680. var candidate = SDPUtil.candidateToJingle(line);
  7681. var protocol = (candidate &&
  7682. typeof candidate.protocol === 'string')
  7683. ? candidate.protocol.toLowerCase() : '';
  7684. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  7685. (self.removeUdpCandidates && protocol === 'udp')) {
  7686. return;
  7687. }
  7688. elem.c('candidate', candidate).up();
  7689. });
  7690. }
  7691. }
  7692. elem.up(); // end of transport
  7693. }
  7694. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  7695. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  7696. lines.forEach(function (line) {
  7697. var tmp = SDPUtil.parse_rtcpfb(line);
  7698. if (tmp.type == 'trr-int') {
  7699. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  7700. elem.up();
  7701. } else {
  7702. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  7703. if (tmp.params.length > 0) {
  7704. elem.attrs({'subtype': tmp.params[0]});
  7705. }
  7706. elem.up();
  7707. }
  7708. });
  7709. };
  7710. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  7711. var media = '';
  7712. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7713. if (tmp.length) {
  7714. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  7715. if (tmp.attr('value')) {
  7716. media += tmp.attr('value');
  7717. } else {
  7718. media += '0';
  7719. }
  7720. media += '\r\n';
  7721. }
  7722. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  7723. tmp.each(function () {
  7724. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  7725. if ($(this).attr('subtype')) {
  7726. media += ' ' + $(this).attr('subtype');
  7727. }
  7728. media += '\r\n';
  7729. });
  7730. return media;
  7731. };
  7732. // construct an SDP from a jingle stanza
  7733. SDP.prototype.fromJingle = function (jingle) {
  7734. var self = this;
  7735. this.raw = 'v=0\r\n' +
  7736. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  7737. 's=-\r\n' +
  7738. 't=0 0\r\n';
  7739. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  7740. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  7741. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  7742. var contents = $(group).find('>content').map(function (idx, content) {
  7743. return content.getAttribute('name');
  7744. }).get();
  7745. if (contents.length > 0) {
  7746. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  7747. }
  7748. });
  7749. }
  7750. this.session = this.raw;
  7751. jingle.find('>content').each(function () {
  7752. var m = self.jingle2media($(this));
  7753. self.media.push(m);
  7754. });
  7755. // reconstruct msid-semantic -- apparently not necessary
  7756. /*
  7757. var msid = SDPUtil.parse_ssrc(this.raw);
  7758. if (msid.hasOwnProperty('mslabel')) {
  7759. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  7760. }
  7761. */
  7762. this.raw = this.session + this.media.join('');
  7763. };
  7764. // translate a jingle content element into an an SDP media part
  7765. SDP.prototype.jingle2media = function (content) {
  7766. var media = '',
  7767. desc = content.find('description'),
  7768. ssrc = desc.attr('ssrc'),
  7769. self = this,
  7770. tmp;
  7771. var sctp = content.find(
  7772. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  7773. tmp = { media: desc.attr('media') };
  7774. tmp.port = '1';
  7775. if (content.attr('senders') == 'rejected') {
  7776. // estos hack to reject an m-line.
  7777. tmp.port = '0';
  7778. }
  7779. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  7780. if (sctp.length)
  7781. tmp.proto = 'DTLS/SCTP';
  7782. else
  7783. tmp.proto = 'RTP/SAVPF';
  7784. } else {
  7785. tmp.proto = 'RTP/AVPF';
  7786. }
  7787. if (!sctp.length) {
  7788. tmp.fmt = desc.find('payload-type').map(
  7789. function () { return this.getAttribute('id'); }).get();
  7790. media += SDPUtil.build_mline(tmp) + '\r\n';
  7791. } else {
  7792. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  7793. media += 'a=sctpmap:' + sctp.attr('number') +
  7794. ' ' + sctp.attr('protocol');
  7795. var streamCount = sctp.attr('streams');
  7796. if (streamCount)
  7797. media += ' ' + streamCount + '\r\n';
  7798. else
  7799. media += '\r\n';
  7800. }
  7801. media += 'c=IN IP4 0.0.0.0\r\n';
  7802. if (!sctp.length)
  7803. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  7804. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  7805. if (tmp.length) {
  7806. if (tmp.attr('ufrag')) {
  7807. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  7808. }
  7809. if (tmp.attr('pwd')) {
  7810. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  7811. }
  7812. tmp.find('>fingerprint').each(function () {
  7813. // FIXME: check namespace at some point
  7814. media += 'a=fingerprint:' + this.getAttribute('hash');
  7815. media += ' ' + $(this).text();
  7816. media += '\r\n';
  7817. if (this.getAttribute('setup')) {
  7818. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  7819. }
  7820. });
  7821. }
  7822. switch (content.attr('senders')) {
  7823. case 'initiator':
  7824. media += 'a=sendonly\r\n';
  7825. break;
  7826. case 'responder':
  7827. media += 'a=recvonly\r\n';
  7828. break;
  7829. case 'none':
  7830. media += 'a=inactive\r\n';
  7831. break;
  7832. case 'both':
  7833. media += 'a=sendrecv\r\n';
  7834. break;
  7835. }
  7836. media += 'a=mid:' + content.attr('name') + '\r\n';
  7837. // <description><rtcp-mux/></description>
  7838. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  7839. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  7840. if (desc.find('rtcp-mux').length) {
  7841. media += 'a=rtcp-mux\r\n';
  7842. }
  7843. if (desc.find('encryption').length) {
  7844. desc.find('encryption>crypto').each(function () {
  7845. media += 'a=crypto:' + this.getAttribute('tag');
  7846. media += ' ' + this.getAttribute('crypto-suite');
  7847. media += ' ' + this.getAttribute('key-params');
  7848. if (this.getAttribute('session-params')) {
  7849. media += ' ' + this.getAttribute('session-params');
  7850. }
  7851. media += '\r\n';
  7852. });
  7853. }
  7854. desc.find('payload-type').each(function () {
  7855. media += SDPUtil.build_rtpmap(this) + '\r\n';
  7856. if ($(this).find('>parameter').length) {
  7857. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  7858. media += $(this).find('parameter').map(function () {
  7859. return (this.getAttribute('name')
  7860. ? (this.getAttribute('name') + '=') : '') +
  7861. this.getAttribute('value');
  7862. }).get().join('; ');
  7863. media += '\r\n';
  7864. }
  7865. // xep-0293
  7866. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  7867. });
  7868. // xep-0293
  7869. media += self.rtcpFbFromJingle(desc, '*');
  7870. // xep-0294
  7871. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  7872. tmp.each(function () {
  7873. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  7874. });
  7875. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  7876. var protocol = this.getAttribute('protocol');
  7877. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  7878. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  7879. (self.removeUdpCandidates && protocol === 'udp')) {
  7880. return;
  7881. }
  7882. media += SDPUtil.candidateFromJingle(this);
  7883. });
  7884. // XEP-0339 handle ssrc-group attributes
  7885. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  7886. var semantics = this.getAttribute('semantics');
  7887. var ssrcs = $(this).find('>source').map(function() {
  7888. return this.getAttribute('ssrc');
  7889. }).get();
  7890. if (ssrcs.length) {
  7891. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  7892. }
  7893. });
  7894. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7895. tmp.each(function () {
  7896. var ssrc = this.getAttribute('ssrc');
  7897. $(this).find('>parameter').each(function () {
  7898. var name = this.getAttribute('name');
  7899. var value = this.getAttribute('value');
  7900. value = SDPUtil.filter_special_chars(value);
  7901. media += 'a=ssrc:' + ssrc + ' ' + name;
  7902. if (value && value.length)
  7903. media += ':' + value;
  7904. media += '\r\n';
  7905. });
  7906. });
  7907. return media;
  7908. };
  7909. module.exports = SDP;
  7910. }).call(this,"/modules/xmpp/SDP.js")
  7911. },{"./SDPUtil":30,"jitsi-meet-logger":45}],29:[function(require,module,exports){
  7912. var SDPUtil = require("./SDPUtil");
  7913. function SDPDiffer(mySDP, otherSDP)
  7914. {
  7915. this.mySDP = mySDP;
  7916. this.otherSDP = otherSDP;
  7917. }
  7918. /**
  7919. * Returns map of MediaChannel that contains media contained in
  7920. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  7921. */
  7922. SDPDiffer.prototype.getNewMedia = function() {
  7923. // this could be useful in Array.prototype.
  7924. function arrayEquals(array) {
  7925. // if the other array is a falsy value, return
  7926. if (!array)
  7927. return false;
  7928. // compare lengths - can save a lot of time
  7929. if (this.length != array.length)
  7930. return false;
  7931. for (var i = 0, l=this.length; i < l; i++) {
  7932. // Check if we have nested arrays
  7933. if (this[i] instanceof Array && array[i] instanceof Array) {
  7934. // recurse into the nested arrays
  7935. if (!this[i].equals(array[i]))
  7936. return false;
  7937. }
  7938. else if (this[i] != array[i]) {
  7939. // Warning - two different object instances will never be
  7940. // equal: {x:20} != {x:20}
  7941. return false;
  7942. }
  7943. }
  7944. return true;
  7945. }
  7946. var myMedias = this.mySDP.getMediaSsrcMap();
  7947. var othersMedias = this.otherSDP.getMediaSsrcMap();
  7948. var newMedia = {};
  7949. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  7950. var myMedia = myMedias[othersMediaIdx];
  7951. var othersMedia = othersMedias[othersMediaIdx];
  7952. if(!myMedia && othersMedia) {
  7953. // Add whole channel
  7954. newMedia[othersMediaIdx] = othersMedia;
  7955. return;
  7956. }
  7957. // Look for new ssrcs across the channel
  7958. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  7959. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  7960. // Allocate channel if we've found ssrc that doesn't exist in
  7961. // our channel
  7962. if(!newMedia[othersMediaIdx]){
  7963. newMedia[othersMediaIdx] = {
  7964. mediaindex: othersMedia.mediaindex,
  7965. mid: othersMedia.mid,
  7966. ssrcs: {},
  7967. ssrcGroups: []
  7968. };
  7969. }
  7970. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  7971. }
  7972. });
  7973. // Look for new ssrc groups across the channels
  7974. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  7975. // try to match the other ssrc-group with an ssrc-group of ours
  7976. var matched = false;
  7977. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  7978. var mySsrcGroup = myMedia.ssrcGroups[i];
  7979. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  7980. arrayEquals.apply(otherSsrcGroup.ssrcs,
  7981. [mySsrcGroup.ssrcs])) {
  7982. matched = true;
  7983. break;
  7984. }
  7985. }
  7986. if (!matched) {
  7987. // Allocate channel if we've found an ssrc-group that doesn't
  7988. // exist in our channel
  7989. if(!newMedia[othersMediaIdx]){
  7990. newMedia[othersMediaIdx] = {
  7991. mediaindex: othersMedia.mediaindex,
  7992. mid: othersMedia.mid,
  7993. ssrcs: {},
  7994. ssrcGroups: []
  7995. };
  7996. }
  7997. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  7998. }
  7999. });
  8000. });
  8001. return newMedia;
  8002. };
  8003. /**
  8004. * TODO: document!
  8005. */
  8006. SDPDiffer.prototype.toJingle = function(modify) {
  8007. var sdpMediaSsrcs = this.getNewMedia();
  8008. var modified = false;
  8009. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  8010. modified = true;
  8011. var media = sdpMediaSsrcs[mediaindex];
  8012. modify.c('content', {name: media.mid});
  8013. modify.c('description',
  8014. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  8015. // FIXME: not completely sure this operates on blocks and / or handles
  8016. // different ssrcs correctly
  8017. // generate sources from lines
  8018. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  8019. var mediaSsrc = media.ssrcs[ssrcNum];
  8020. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8021. modify.attrs({ssrc: mediaSsrc.ssrc});
  8022. // iterate over ssrc lines
  8023. mediaSsrc.lines.forEach(function (line) {
  8024. var idx = line.indexOf(' ');
  8025. var kv = line.substr(idx + 1);
  8026. modify.c('parameter');
  8027. if (kv.indexOf(':') == -1) {
  8028. modify.attrs({ name: kv });
  8029. } else {
  8030. var nv = kv.split(':', 2);
  8031. var name = nv[0];
  8032. var value = SDPUtil.filter_special_chars(nv[1]);
  8033. modify.attrs({ name: name });
  8034. modify.attrs({ value: value });
  8035. }
  8036. modify.up(); // end of parameter
  8037. });
  8038. modify.up(); // end of source
  8039. });
  8040. // generate source groups from lines
  8041. media.ssrcGroups.forEach(function(ssrcGroup) {
  8042. if (ssrcGroup.ssrcs.length) {
  8043. modify.c('ssrc-group', {
  8044. semantics: ssrcGroup.semantics,
  8045. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  8046. });
  8047. ssrcGroup.ssrcs.forEach(function (ssrc) {
  8048. modify.c('source', { ssrc: ssrc })
  8049. .up(); // end of source
  8050. });
  8051. modify.up(); // end of ssrc-group
  8052. }
  8053. });
  8054. modify.up(); // end of description
  8055. modify.up(); // end of content
  8056. });
  8057. return modified;
  8058. };
  8059. module.exports = SDPDiffer;
  8060. },{"./SDPUtil":30}],30:[function(require,module,exports){
  8061. (function (__filename){
  8062. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8063. SDPUtil = {
  8064. filter_special_chars: function (text) {
  8065. return text.replace(/[\\\/\{,\}\+]/g, "");
  8066. },
  8067. iceparams: function (mediadesc, sessiondesc) {
  8068. var data = null;
  8069. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  8070. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  8071. data = {
  8072. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  8073. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  8074. };
  8075. }
  8076. return data;
  8077. },
  8078. parse_iceufrag: function (line) {
  8079. return line.substring(12);
  8080. },
  8081. build_iceufrag: function (frag) {
  8082. return 'a=ice-ufrag:' + frag;
  8083. },
  8084. parse_icepwd: function (line) {
  8085. return line.substring(10);
  8086. },
  8087. build_icepwd: function (pwd) {
  8088. return 'a=ice-pwd:' + pwd;
  8089. },
  8090. parse_mid: function (line) {
  8091. return line.substring(6);
  8092. },
  8093. parse_mline: function (line) {
  8094. var parts = line.substring(2).split(' '),
  8095. data = {};
  8096. data.media = parts.shift();
  8097. data.port = parts.shift();
  8098. data.proto = parts.shift();
  8099. if (parts[parts.length - 1] === '') { // trailing whitespace
  8100. parts.pop();
  8101. }
  8102. data.fmt = parts;
  8103. return data;
  8104. },
  8105. build_mline: function (mline) {
  8106. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  8107. },
  8108. parse_rtpmap: function (line) {
  8109. var parts = line.substring(9).split(' '),
  8110. data = {};
  8111. data.id = parts.shift();
  8112. parts = parts[0].split('/');
  8113. data.name = parts.shift();
  8114. data.clockrate = parts.shift();
  8115. data.channels = parts.length ? parts.shift() : '1';
  8116. return data;
  8117. },
  8118. /**
  8119. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  8120. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  8121. * @returns [SCTP port number, protocol, streams]
  8122. */
  8123. parse_sctpmap: function (line)
  8124. {
  8125. var parts = line.substring(10).split(' ');
  8126. var sctpPort = parts[0];
  8127. var protocol = parts[1];
  8128. // Stream count is optional
  8129. var streamCount = parts.length > 2 ? parts[2] : null;
  8130. return [sctpPort, protocol, streamCount];// SCTP port
  8131. },
  8132. build_rtpmap: function (el) {
  8133. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  8134. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  8135. line += '/' + el.getAttribute('channels');
  8136. }
  8137. return line;
  8138. },
  8139. parse_crypto: function (line) {
  8140. var parts = line.substring(9).split(' '),
  8141. data = {};
  8142. data.tag = parts.shift();
  8143. data['crypto-suite'] = parts.shift();
  8144. data['key-params'] = parts.shift();
  8145. if (parts.length) {
  8146. data['session-params'] = parts.join(' ');
  8147. }
  8148. return data;
  8149. },
  8150. parse_fingerprint: function (line) { // RFC 4572
  8151. var parts = line.substring(14).split(' '),
  8152. data = {};
  8153. data.hash = parts.shift();
  8154. data.fingerprint = parts.shift();
  8155. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  8156. return data;
  8157. },
  8158. parse_fmtp: function (line) {
  8159. var parts = line.split(' '),
  8160. i, key, value,
  8161. data = [];
  8162. parts.shift();
  8163. parts = parts.join(' ').split(';');
  8164. for (i = 0; i < parts.length; i++) {
  8165. key = parts[i].split('=')[0];
  8166. while (key.length && key[0] == ' ') {
  8167. key = key.substring(1);
  8168. }
  8169. value = parts[i].split('=')[1];
  8170. if (key && value) {
  8171. data.push({name: key, value: value});
  8172. } else if (key) {
  8173. // rfc 4733 (DTMF) style stuff
  8174. data.push({name: '', value: key});
  8175. }
  8176. }
  8177. return data;
  8178. },
  8179. parse_icecandidate: function (line) {
  8180. var candidate = {},
  8181. elems = line.split(' ');
  8182. candidate.foundation = elems[0].substring(12);
  8183. candidate.component = elems[1];
  8184. candidate.protocol = elems[2].toLowerCase();
  8185. candidate.priority = elems[3];
  8186. candidate.ip = elems[4];
  8187. candidate.port = elems[5];
  8188. // elems[6] => "typ"
  8189. candidate.type = elems[7];
  8190. candidate.generation = 0; // default value, may be overwritten below
  8191. for (var i = 8; i < elems.length; i += 2) {
  8192. switch (elems[i]) {
  8193. case 'raddr':
  8194. candidate['rel-addr'] = elems[i + 1];
  8195. break;
  8196. case 'rport':
  8197. candidate['rel-port'] = elems[i + 1];
  8198. break;
  8199. case 'generation':
  8200. candidate.generation = elems[i + 1];
  8201. break;
  8202. case 'tcptype':
  8203. candidate.tcptype = elems[i + 1];
  8204. break;
  8205. default: // TODO
  8206. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8207. }
  8208. }
  8209. candidate.network = '1';
  8210. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8211. return candidate;
  8212. },
  8213. build_icecandidate: function (cand) {
  8214. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  8215. line += ' ';
  8216. switch (cand.type) {
  8217. case 'srflx':
  8218. case 'prflx':
  8219. case 'relay':
  8220. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  8221. line += 'raddr';
  8222. line += ' ';
  8223. line += cand['rel-addr'];
  8224. line += ' ';
  8225. line += 'rport';
  8226. line += ' ';
  8227. line += cand['rel-port'];
  8228. line += ' ';
  8229. }
  8230. break;
  8231. }
  8232. if (cand.hasOwnAttribute('tcptype')) {
  8233. line += 'tcptype';
  8234. line += ' ';
  8235. line += cand.tcptype;
  8236. line += ' ';
  8237. }
  8238. line += 'generation';
  8239. line += ' ';
  8240. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  8241. return line;
  8242. },
  8243. parse_ssrc: function (desc) {
  8244. // proprietary mapping of a=ssrc lines
  8245. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  8246. // and parse according to that
  8247. var lines = desc.split('\r\n'),
  8248. data = {};
  8249. for (var i = 0; i < lines.length; i++) {
  8250. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  8251. var idx = lines[i].indexOf(' ');
  8252. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  8253. }
  8254. }
  8255. return data;
  8256. },
  8257. parse_rtcpfb: function (line) {
  8258. var parts = line.substr(10).split(' ');
  8259. var data = {};
  8260. data.pt = parts.shift();
  8261. data.type = parts.shift();
  8262. data.params = parts;
  8263. return data;
  8264. },
  8265. parse_extmap: function (line) {
  8266. var parts = line.substr(9).split(' ');
  8267. var data = {};
  8268. data.value = parts.shift();
  8269. if (data.value.indexOf('/') != -1) {
  8270. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  8271. data.value = data.value.substr(0, data.value.indexOf('/'));
  8272. } else {
  8273. data.direction = 'both';
  8274. }
  8275. data.uri = parts.shift();
  8276. data.params = parts;
  8277. return data;
  8278. },
  8279. find_line: function (haystack, needle, sessionpart) {
  8280. var lines = haystack.split('\r\n');
  8281. for (var i = 0; i < lines.length; i++) {
  8282. if (lines[i].substring(0, needle.length) == needle) {
  8283. return lines[i];
  8284. }
  8285. }
  8286. if (!sessionpart) {
  8287. return false;
  8288. }
  8289. // search session part
  8290. lines = sessionpart.split('\r\n');
  8291. for (var j = 0; j < lines.length; j++) {
  8292. if (lines[j].substring(0, needle.length) == needle) {
  8293. return lines[j];
  8294. }
  8295. }
  8296. return false;
  8297. },
  8298. find_lines: function (haystack, needle, sessionpart) {
  8299. var lines = haystack.split('\r\n'),
  8300. needles = [];
  8301. for (var i = 0; i < lines.length; i++) {
  8302. if (lines[i].substring(0, needle.length) == needle)
  8303. needles.push(lines[i]);
  8304. }
  8305. if (needles.length || !sessionpart) {
  8306. return needles;
  8307. }
  8308. // search session part
  8309. lines = sessionpart.split('\r\n');
  8310. for (var j = 0; j < lines.length; j++) {
  8311. if (lines[j].substring(0, needle.length) == needle) {
  8312. needles.push(lines[j]);
  8313. }
  8314. }
  8315. return needles;
  8316. },
  8317. candidateToJingle: function (line) {
  8318. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  8319. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  8320. if (line.indexOf('candidate:') === 0) {
  8321. line = 'a=' + line;
  8322. } else if (line.substring(0, 12) != 'a=candidate:') {
  8323. logger.log('parseCandidate called with a line that is not a candidate line');
  8324. logger.log(line);
  8325. return null;
  8326. }
  8327. if (line.substring(line.length - 2) == '\r\n') // chomp it
  8328. line = line.substring(0, line.length - 2);
  8329. var candidate = {},
  8330. elems = line.split(' '),
  8331. i;
  8332. if (elems[6] != 'typ') {
  8333. logger.log('did not find typ in the right place');
  8334. logger.log(line);
  8335. return null;
  8336. }
  8337. candidate.foundation = elems[0].substring(12);
  8338. candidate.component = elems[1];
  8339. candidate.protocol = elems[2].toLowerCase();
  8340. candidate.priority = elems[3];
  8341. candidate.ip = elems[4];
  8342. candidate.port = elems[5];
  8343. // elems[6] => "typ"
  8344. candidate.type = elems[7];
  8345. candidate.generation = '0'; // default, may be overwritten below
  8346. for (i = 8; i < elems.length; i += 2) {
  8347. switch (elems[i]) {
  8348. case 'raddr':
  8349. candidate['rel-addr'] = elems[i + 1];
  8350. break;
  8351. case 'rport':
  8352. candidate['rel-port'] = elems[i + 1];
  8353. break;
  8354. case 'generation':
  8355. candidate.generation = elems[i + 1];
  8356. break;
  8357. case 'tcptype':
  8358. candidate.tcptype = elems[i + 1];
  8359. break;
  8360. default: // TODO
  8361. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  8362. }
  8363. }
  8364. candidate.network = '1';
  8365. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  8366. return candidate;
  8367. },
  8368. candidateFromJingle: function (cand) {
  8369. var line = 'a=candidate:';
  8370. line += cand.getAttribute('foundation');
  8371. line += ' ';
  8372. line += cand.getAttribute('component');
  8373. line += ' ';
  8374. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  8375. line += ' ';
  8376. line += cand.getAttribute('priority');
  8377. line += ' ';
  8378. line += cand.getAttribute('ip');
  8379. line += ' ';
  8380. line += cand.getAttribute('port');
  8381. line += ' ';
  8382. line += 'typ';
  8383. line += ' ' + cand.getAttribute('type');
  8384. line += ' ';
  8385. switch (cand.getAttribute('type')) {
  8386. case 'srflx':
  8387. case 'prflx':
  8388. case 'relay':
  8389. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  8390. line += 'raddr';
  8391. line += ' ';
  8392. line += cand.getAttribute('rel-addr');
  8393. line += ' ';
  8394. line += 'rport';
  8395. line += ' ';
  8396. line += cand.getAttribute('rel-port');
  8397. line += ' ';
  8398. }
  8399. break;
  8400. }
  8401. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  8402. line += 'tcptype';
  8403. line += ' ';
  8404. line += cand.getAttribute('tcptype');
  8405. line += ' ';
  8406. }
  8407. line += 'generation';
  8408. line += ' ';
  8409. line += cand.getAttribute('generation') || '0';
  8410. return line + '\r\n';
  8411. }
  8412. };
  8413. module.exports = SDPUtil;
  8414. }).call(this,"/modules/xmpp/SDPUtil.js")
  8415. },{"jitsi-meet-logger":45}],31:[function(require,module,exports){
  8416. (function (__filename){
  8417. /* global $ */
  8418. var RTC = require('../RTC/RTC');
  8419. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8420. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  8421. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8422. var SSRCReplacement = require("./LocalSSRCReplacement");
  8423. function TraceablePeerConnection(ice_config, constraints, session) {
  8424. var self = this;
  8425. this.session = session;
  8426. var RTCPeerConnectionType = null;
  8427. if (RTCBrowserType.isFirefox()) {
  8428. RTCPeerConnectionType = mozRTCPeerConnection;
  8429. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  8430. RTCPeerConnectionType = RTCPeerConnection;
  8431. } else {
  8432. RTCPeerConnectionType = webkitRTCPeerConnection;
  8433. }
  8434. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  8435. this.updateLog = [];
  8436. this.stats = {};
  8437. this.statsinterval = null;
  8438. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  8439. var Interop = require('sdp-interop').Interop;
  8440. this.interop = new Interop();
  8441. var Simulcast = require('sdp-simulcast');
  8442. this.simulcast = new Simulcast({numOfLayers: 2, explodeRemoteSimulcast: false});
  8443. // override as desired
  8444. this.trace = function (what, info) {
  8445. /*logger.warn('WTRACE', what, info);
  8446. if (info && RTCBrowserType.isIExplorer()) {
  8447. if (info.length > 1024) {
  8448. logger.warn('WTRACE', what, info.substr(1024));
  8449. }
  8450. if (info.length > 2048) {
  8451. logger.warn('WTRACE', what, info.substr(2048));
  8452. }
  8453. }*/
  8454. self.updateLog.push({
  8455. time: new Date(),
  8456. type: what,
  8457. value: info || ""
  8458. });
  8459. };
  8460. this.onicecandidate = null;
  8461. this.peerconnection.onicecandidate = function (event) {
  8462. // FIXME: this causes stack overflow with Temasys Plugin
  8463. if (!RTCBrowserType.isTemasysPluginUsed())
  8464. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  8465. if (self.onicecandidate !== null) {
  8466. self.onicecandidate(event);
  8467. }
  8468. };
  8469. this.onaddstream = null;
  8470. this.peerconnection.onaddstream = function (event) {
  8471. self.trace('onaddstream', event.stream.id);
  8472. if (self.onaddstream !== null) {
  8473. self.onaddstream(event);
  8474. }
  8475. };
  8476. this.onremovestream = null;
  8477. this.peerconnection.onremovestream = function (event) {
  8478. self.trace('onremovestream', event.stream.id);
  8479. if (self.onremovestream !== null) {
  8480. self.onremovestream(event);
  8481. }
  8482. };
  8483. this.onsignalingstatechange = null;
  8484. this.peerconnection.onsignalingstatechange = function (event) {
  8485. self.trace('onsignalingstatechange', self.signalingState);
  8486. if (self.onsignalingstatechange !== null) {
  8487. self.onsignalingstatechange(event);
  8488. }
  8489. };
  8490. this.oniceconnectionstatechange = null;
  8491. this.peerconnection.oniceconnectionstatechange = function (event) {
  8492. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  8493. if (self.oniceconnectionstatechange !== null) {
  8494. self.oniceconnectionstatechange(event);
  8495. }
  8496. };
  8497. this.onnegotiationneeded = null;
  8498. this.peerconnection.onnegotiationneeded = function (event) {
  8499. self.trace('onnegotiationneeded');
  8500. if (self.onnegotiationneeded !== null) {
  8501. self.onnegotiationneeded(event);
  8502. }
  8503. };
  8504. self.ondatachannel = null;
  8505. this.peerconnection.ondatachannel = function (event) {
  8506. self.trace('ondatachannel', event);
  8507. if (self.ondatachannel !== null) {
  8508. self.ondatachannel(event);
  8509. }
  8510. };
  8511. // XXX: do all non-firefox browsers which we support also support this?
  8512. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  8513. this.statsinterval = window.setInterval(function() {
  8514. self.peerconnection.getStats(function(stats) {
  8515. var results = stats.result();
  8516. var now = new Date();
  8517. for (var i = 0; i < results.length; ++i) {
  8518. results[i].names().forEach(function (name) {
  8519. var id = results[i].id + '-' + name;
  8520. if (!self.stats[id]) {
  8521. self.stats[id] = {
  8522. startTime: now,
  8523. endTime: now,
  8524. values: [],
  8525. times: []
  8526. };
  8527. }
  8528. self.stats[id].values.push(results[i].stat(name));
  8529. self.stats[id].times.push(now.getTime());
  8530. if (self.stats[id].values.length > self.maxstats) {
  8531. self.stats[id].values.shift();
  8532. self.stats[id].times.shift();
  8533. }
  8534. self.stats[id].endTime = now;
  8535. });
  8536. }
  8537. });
  8538. }, 1000);
  8539. }
  8540. }
  8541. /**
  8542. * Returns a string representation of a SessionDescription object.
  8543. */
  8544. var dumpSDP = function(description) {
  8545. if (typeof description === 'undefined' || description == null) {
  8546. return '';
  8547. }
  8548. return 'type: ' + description.type + '\r\n' + description.sdp;
  8549. };
  8550. /**
  8551. * Takes a SessionDescription object and returns a "normalized" version.
  8552. * Currently it only takes care of ordering the a=ssrc lines.
  8553. */
  8554. var normalizePlanB = function(desc) {
  8555. if (typeof desc !== 'object' || desc === null ||
  8556. typeof desc.sdp !== 'string') {
  8557. logger.warn('An empty description was passed as an argument.');
  8558. return desc;
  8559. }
  8560. var transform = require('sdp-transform');
  8561. var session = transform.parse(desc.sdp);
  8562. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  8563. Array.isArray(session.media)) {
  8564. session.media.forEach(function (mLine) {
  8565. // Chrome appears to be picky about the order in which a=ssrc lines
  8566. // are listed in an m-line when rtx is enabled (and thus there are
  8567. // a=ssrc-group lines with FID semantics). Specifically if we have
  8568. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  8569. // the "a=ssrc:S1" lines, SRD fails.
  8570. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  8571. // first.
  8572. var firstSsrcs = [];
  8573. var newSsrcLines = [];
  8574. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  8575. mLine.ssrcGroups.forEach(function (group) {
  8576. if (typeof group.semantics !== 'undefined' &&
  8577. group.semantics === 'FID') {
  8578. if (typeof group.ssrcs !== 'undefined') {
  8579. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  8580. }
  8581. }
  8582. });
  8583. }
  8584. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  8585. var i;
  8586. for (i = 0; i<mLine.ssrcs.length; i++){
  8587. if (typeof mLine.ssrcs[i] === 'object'
  8588. && typeof mLine.ssrcs[i].id !== 'undefined'
  8589. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  8590. newSsrcLines.push(mLine.ssrcs[i]);
  8591. delete mLine.ssrcs[i];
  8592. }
  8593. }
  8594. for (i = 0; i<mLine.ssrcs.length; i++){
  8595. if (typeof mLine.ssrcs[i] !== 'undefined') {
  8596. newSsrcLines.push(mLine.ssrcs[i]);
  8597. }
  8598. }
  8599. mLine.ssrcs = newSsrcLines;
  8600. }
  8601. });
  8602. }
  8603. var resStr = transform.write(session);
  8604. return new RTCSessionDescription({
  8605. type: desc.type,
  8606. sdp: resStr
  8607. });
  8608. };
  8609. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  8610. TraceablePeerConnection.prototype.__defineGetter__(
  8611. 'signalingState',
  8612. function() { return this.peerconnection.signalingState; });
  8613. TraceablePeerConnection.prototype.__defineGetter__(
  8614. 'iceConnectionState',
  8615. function() { return this.peerconnection.iceConnectionState; });
  8616. TraceablePeerConnection.prototype.__defineGetter__(
  8617. 'localDescription',
  8618. function() {
  8619. var desc = this.peerconnection.localDescription;
  8620. // TODO this should be after the Unified Plan -> Plan B
  8621. // transformation.
  8622. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  8623. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  8624. // if we're running on FF, transform to Plan B first.
  8625. if (RTCBrowserType.usesUnifiedPlan()) {
  8626. desc = this.interop.toPlanB(desc);
  8627. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  8628. }
  8629. return desc;
  8630. });
  8631. TraceablePeerConnection.prototype.__defineGetter__(
  8632. 'remoteDescription',
  8633. function() {
  8634. var desc = this.peerconnection.remoteDescription;
  8635. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  8636. // if we're running on FF, transform to Plan B first.
  8637. if (RTCBrowserType.usesUnifiedPlan()) {
  8638. desc = this.interop.toPlanB(desc);
  8639. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  8640. }
  8641. return desc;
  8642. });
  8643. }
  8644. TraceablePeerConnection.prototype.addStream = function (stream) {
  8645. this.trace('addStream', stream.id);
  8646. try
  8647. {
  8648. this.peerconnection.addStream(stream);
  8649. }
  8650. catch (e)
  8651. {
  8652. logger.error(e);
  8653. }
  8654. };
  8655. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  8656. this.trace('removeStream', stream.id);
  8657. if(stopStreams) {
  8658. RTC.stopMediaStream(stream);
  8659. }
  8660. try {
  8661. // FF doesn't support this yet.
  8662. if (this.peerconnection.removeStream)
  8663. this.peerconnection.removeStream(stream);
  8664. } catch (e) {
  8665. logger.error(e);
  8666. }
  8667. };
  8668. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  8669. this.trace('createDataChannel', label, opts);
  8670. return this.peerconnection.createDataChannel(label, opts);
  8671. };
  8672. TraceablePeerConnection.prototype.setLocalDescription
  8673. = function (description, successCallback, failureCallback) {
  8674. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  8675. // if we're running on FF, transform to Plan A first.
  8676. if (RTCBrowserType.usesUnifiedPlan()) {
  8677. description = this.interop.toUnifiedPlan(description);
  8678. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  8679. }
  8680. var self = this;
  8681. this.peerconnection.setLocalDescription(description,
  8682. function () {
  8683. self.trace('setLocalDescriptionOnSuccess');
  8684. successCallback();
  8685. },
  8686. function (err) {
  8687. self.trace('setLocalDescriptionOnFailure', err);
  8688. failureCallback(err);
  8689. }
  8690. );
  8691. /*
  8692. if (this.statsinterval === null && this.maxstats > 0) {
  8693. // start gathering stats
  8694. }
  8695. */
  8696. };
  8697. TraceablePeerConnection.prototype.setRemoteDescription
  8698. = function (description, successCallback, failureCallback) {
  8699. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  8700. // TODO the focus should squeze or explode the remote simulcast
  8701. description = this.simulcast.mungeRemoteDescription(description);
  8702. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  8703. // if we're running on FF, transform to Plan A first.
  8704. if (RTCBrowserType.usesUnifiedPlan()) {
  8705. description = this.interop.toUnifiedPlan(description);
  8706. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  8707. }
  8708. if (RTCBrowserType.usesPlanB()) {
  8709. description = normalizePlanB(description);
  8710. }
  8711. var self = this;
  8712. this.peerconnection.setRemoteDescription(description,
  8713. function () {
  8714. self.trace('setRemoteDescriptionOnSuccess');
  8715. successCallback();
  8716. },
  8717. function (err) {
  8718. self.trace('setRemoteDescriptionOnFailure', err);
  8719. failureCallback(err);
  8720. }
  8721. );
  8722. /*
  8723. if (this.statsinterval === null && this.maxstats > 0) {
  8724. // start gathering stats
  8725. }
  8726. */
  8727. };
  8728. TraceablePeerConnection.prototype.close = function () {
  8729. this.trace('stop');
  8730. if (this.statsinterval !== null) {
  8731. window.clearInterval(this.statsinterval);
  8732. this.statsinterval = null;
  8733. }
  8734. this.peerconnection.close();
  8735. };
  8736. TraceablePeerConnection.prototype.createOffer
  8737. = function (successCallback, failureCallback, constraints) {
  8738. var self = this;
  8739. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  8740. this.peerconnection.createOffer(
  8741. function (offer) {
  8742. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  8743. // NOTE this is not tested because in meet the focus generates the
  8744. // offer.
  8745. // if we're running on FF, transform to Plan B first.
  8746. if (RTCBrowserType.usesUnifiedPlan()) {
  8747. offer = self.interop.toPlanB(offer);
  8748. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  8749. }
  8750. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  8751. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8752. offer = self.simulcast.mungeLocalDescription(offer);
  8753. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  8754. }
  8755. successCallback(offer);
  8756. },
  8757. function(err) {
  8758. self.trace('createOfferOnFailure', err);
  8759. failureCallback(err);
  8760. },
  8761. constraints
  8762. );
  8763. };
  8764. TraceablePeerConnection.prototype.createAnswer
  8765. = function (successCallback, failureCallback, constraints) {
  8766. var self = this;
  8767. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  8768. this.peerconnection.createAnswer(
  8769. function (answer) {
  8770. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  8771. // if we're running on FF, transform to Plan A first.
  8772. if (RTCBrowserType.usesUnifiedPlan()) {
  8773. answer = self.interop.toPlanB(answer);
  8774. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  8775. }
  8776. // munge local video SSRC
  8777. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  8778. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  8779. answer = self.simulcast.mungeLocalDescription(answer);
  8780. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  8781. }
  8782. successCallback(answer);
  8783. },
  8784. function(err) {
  8785. self.trace('createAnswerOnFailure', err);
  8786. failureCallback(err);
  8787. },
  8788. constraints
  8789. );
  8790. };
  8791. TraceablePeerConnection.prototype.addIceCandidate
  8792. = function (candidate, successCallback, failureCallback) {
  8793. //var self = this;
  8794. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  8795. this.peerconnection.addIceCandidate(candidate);
  8796. /* maybe later
  8797. this.peerconnection.addIceCandidate(candidate,
  8798. function () {
  8799. self.trace('addIceCandidateOnSuccess');
  8800. successCallback();
  8801. },
  8802. function (err) {
  8803. self.trace('addIceCandidateOnFailure', err);
  8804. failureCallback(err);
  8805. }
  8806. );
  8807. */
  8808. };
  8809. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  8810. // TODO: Is this the correct way to handle Opera, Temasys?
  8811. if (RTCBrowserType.isFirefox()) {
  8812. // ignore for now...
  8813. if(!errback)
  8814. errback = function () {};
  8815. this.peerconnection.getStats(null, callback, errback);
  8816. } else {
  8817. this.peerconnection.getStats(callback);
  8818. }
  8819. };
  8820. module.exports = TraceablePeerConnection;
  8821. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  8822. },{"../../service/xmpp/XMPPEvents":84,"../RTC/RTC":13,"../RTC/RTCBrowserType.js":14,"./LocalSSRCReplacement":27,"jitsi-meet-logger":45,"sdp-interop":63,"sdp-simulcast":66,"sdp-transform":73}],32:[function(require,module,exports){
  8823. (function (__filename){
  8824. /* global $, $iq, APP, config, messageHandler,
  8825. roomName, sessionTerminated, Strophe, Util */
  8826. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8827. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8828. var Settings = require("../settings/Settings");
  8829. var AuthenticationEvents
  8830. = require("../../service/authentication/AuthenticationEvents");
  8831. function createExpBackoffTimer(step) {
  8832. var count = 1;
  8833. return function (reset) {
  8834. // Reset call
  8835. if (reset) {
  8836. count = 1;
  8837. return;
  8838. }
  8839. // Calculate next timeout
  8840. var timeout = Math.pow(2, count - 1);
  8841. count += 1;
  8842. return timeout * step;
  8843. };
  8844. }
  8845. function Moderator(roomName, xmpp, emitter) {
  8846. this.roomName = roomName;
  8847. this.xmppService = xmpp;
  8848. this.getNextTimeout = createExpBackoffTimer(1000);
  8849. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  8850. // External authentication stuff
  8851. this.externalAuthEnabled = false;
  8852. this.settings = new Settings(roomName);
  8853. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  8854. // it will be enabled automatically if focus detects the component through
  8855. // service discovery.
  8856. this.sipGatewayEnabled =
  8857. this.xmppService.options.hosts.call_control !== undefined;
  8858. this.eventEmitter = emitter;
  8859. this.connection = this.xmppService.connection;
  8860. this.focusUserJid;
  8861. //FIXME:
  8862. // Message listener that talks to POPUP window
  8863. function listener(event) {
  8864. if (event.data && event.data.sessionId) {
  8865. if (event.origin !== window.location.origin) {
  8866. logger.warn("Ignoring sessionId from different origin: " +
  8867. event.origin);
  8868. return;
  8869. }
  8870. localStorage.setItem('sessionId', event.data.sessionId);
  8871. // After popup is closed we will authenticate
  8872. }
  8873. }
  8874. // Register
  8875. if (window.addEventListener) {
  8876. window.addEventListener("message", listener, false);
  8877. } else {
  8878. window.attachEvent("onmessage", listener);
  8879. }
  8880. }
  8881. Moderator.prototype.isExternalAuthEnabled = function () {
  8882. return this.externalAuthEnabled;
  8883. };
  8884. Moderator.prototype.isSipGatewayEnabled = function () {
  8885. return this.sipGatewayEnabled;
  8886. };
  8887. Moderator.prototype.onMucMemberLeft = function (jid) {
  8888. logger.info("Someone left is it focus ? " + jid);
  8889. var resource = Strophe.getResourceFromJid(jid);
  8890. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  8891. logger.info(
  8892. "Focus has left the room - leaving conference");
  8893. //hangUp();
  8894. // We'd rather reload to have everything re-initialized
  8895. //FIXME: show some message before reload
  8896. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  8897. }
  8898. };
  8899. Moderator.prototype.setFocusUserJid = function (focusJid) {
  8900. if (!this.focusUserJid) {
  8901. this.focusUserJid = focusJid;
  8902. logger.info("Focus jid set to: " + this.focusUserJid);
  8903. }
  8904. };
  8905. Moderator.prototype.getFocusUserJid = function () {
  8906. return this.focusUserJid;
  8907. };
  8908. Moderator.prototype.getFocusComponent = function () {
  8909. // Get focus component address
  8910. var focusComponent = this.xmppService.options.hosts.focus;
  8911. // If not specified use default: 'focus.domain'
  8912. if (!focusComponent) {
  8913. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  8914. }
  8915. return focusComponent;
  8916. };
  8917. Moderator.prototype.createConferenceIq = function () {
  8918. // Generate create conference IQ
  8919. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  8920. // Session Id used for authentication
  8921. var sessionId = localStorage.getItem('sessionId');
  8922. var machineUID = this.settings.getSettings().uid;
  8923. logger.info(
  8924. "Session ID: " + sessionId + " machine UID: " + machineUID);
  8925. elem.c('conference', {
  8926. xmlns: 'http://jitsi.org/protocol/focus',
  8927. room: this.roomName,
  8928. 'machine-uid': machineUID
  8929. });
  8930. if (sessionId) {
  8931. elem.attrs({ 'session-id': sessionId});
  8932. }
  8933. if (this.xmppService.options.hosts.bridge !== undefined) {
  8934. elem.c(
  8935. 'property', {
  8936. name: 'bridge',
  8937. value: this.xmppService.options.hosts.bridge
  8938. }).up();
  8939. }
  8940. // Tell the focus we have Jigasi configured
  8941. if (this.xmppService.options.hosts.call_control !== undefined) {
  8942. elem.c(
  8943. 'property', {
  8944. name: 'call_control',
  8945. value: this.xmppService.options.hosts.call_control
  8946. }).up();
  8947. }
  8948. if (this.xmppService.options.channelLastN !== undefined) {
  8949. elem.c(
  8950. 'property', {
  8951. name: 'channelLastN',
  8952. value: this.xmppService.options.channelLastN
  8953. }).up();
  8954. }
  8955. if (this.xmppService.options.adaptiveLastN !== undefined) {
  8956. elem.c(
  8957. 'property', {
  8958. name: 'adaptiveLastN',
  8959. value: this.xmppService.options.adaptiveLastN
  8960. }).up();
  8961. }
  8962. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  8963. elem.c(
  8964. 'property', {
  8965. name: 'adaptiveSimulcast',
  8966. value: this.xmppService.options.adaptiveSimulcast
  8967. }).up();
  8968. }
  8969. if (this.xmppService.options.openSctp !== undefined) {
  8970. elem.c(
  8971. 'property', {
  8972. name: 'openSctp',
  8973. value: this.xmppService.options.openSctp
  8974. }).up();
  8975. }
  8976. if (this.xmppService.options.startAudioMuted !== undefined)
  8977. {
  8978. elem.c(
  8979. 'property', {
  8980. name: 'startAudioMuted',
  8981. value: this.xmppService.options.startAudioMuted
  8982. }).up();
  8983. }
  8984. if (this.xmppService.options.startVideoMuted !== undefined)
  8985. {
  8986. elem.c(
  8987. 'property', {
  8988. name: 'startVideoMuted',
  8989. value: this.xmppService.options.startVideoMuted
  8990. }).up();
  8991. }
  8992. elem.c(
  8993. 'property', {
  8994. name: 'simulcastMode',
  8995. value: 'rewriting'
  8996. }).up();
  8997. elem.up();
  8998. return elem;
  8999. };
  9000. Moderator.prototype.parseSessionId = function (resultIq) {
  9001. var sessionId = $(resultIq).find('conference').attr('session-id');
  9002. if (sessionId) {
  9003. logger.info('Received sessionId: ' + sessionId);
  9004. localStorage.setItem('sessionId', sessionId);
  9005. }
  9006. };
  9007. Moderator.prototype.parseConfigOptions = function (resultIq) {
  9008. this.setFocusUserJid(
  9009. $(resultIq).find('conference').attr('focusjid'));
  9010. var authenticationEnabled
  9011. = $(resultIq).find(
  9012. '>conference>property' +
  9013. '[name=\'authentication\'][value=\'true\']').length > 0;
  9014. logger.info("Authentication enabled: " + authenticationEnabled);
  9015. this.externalAuthEnabled = $(resultIq).find(
  9016. '>conference>property' +
  9017. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  9018. console.info(
  9019. 'External authentication enabled: ' + this.externalAuthEnabled);
  9020. if (!this.externalAuthEnabled) {
  9021. // We expect to receive sessionId in 'internal' authentication mode
  9022. this.parseSessionId(resultIq);
  9023. }
  9024. var authIdentity = $(resultIq).find('>conference').attr('identity');
  9025. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  9026. authenticationEnabled, authIdentity);
  9027. // Check if focus has auto-detected Jigasi component(this will be also
  9028. // included if we have passed our host from the config)
  9029. if ($(resultIq).find(
  9030. '>conference>property' +
  9031. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  9032. this.sipGatewayEnabled = true;
  9033. }
  9034. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  9035. };
  9036. // FIXME = we need to show the fact that we're waiting for the focus
  9037. // to the user(or that focus is not available)
  9038. Moderator.prototype.allocateConferenceFocus = function (callback) {
  9039. // Try to use focus user JID from the config
  9040. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  9041. // Send create conference IQ
  9042. var iq = this.createConferenceIq();
  9043. var self = this;
  9044. this.connection.sendIQ(
  9045. iq,
  9046. function (result) {
  9047. // Setup config options
  9048. self.parseConfigOptions(result);
  9049. if ('true' === $(result).find('conference').attr('ready')) {
  9050. // Reset both timers
  9051. self.getNextTimeout(true);
  9052. self.getNextErrorTimeout(true);
  9053. // Exec callback
  9054. callback();
  9055. } else {
  9056. var waitMs = self.getNextTimeout();
  9057. logger.info("Waiting for the focus... " + waitMs);
  9058. // Reset error timeout
  9059. self.getNextErrorTimeout(true);
  9060. window.setTimeout(
  9061. function () {
  9062. self.allocateConferenceFocus(callback);
  9063. }, waitMs);
  9064. }
  9065. },
  9066. function (error) {
  9067. // Invalid session ? remove and try again
  9068. // without session ID to get a new one
  9069. var invalidSession
  9070. = $(error).find('>error>session-invalid').length;
  9071. if (invalidSession) {
  9072. logger.info("Session expired! - removing");
  9073. localStorage.removeItem("sessionId");
  9074. }
  9075. if ($(error).find('>error>graceful-shutdown').length) {
  9076. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  9077. return;
  9078. }
  9079. // Check for error returned by the reservation system
  9080. var reservationErr = $(error).find('>error>reservation-error');
  9081. if (reservationErr.length) {
  9082. // Trigger error event
  9083. var errorCode = reservationErr.attr('error-code');
  9084. var errorMsg;
  9085. if ($(error).find('>error>text')) {
  9086. errorMsg = $(error).find('>error>text').text();
  9087. }
  9088. self.eventEmitter.emit(
  9089. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  9090. return;
  9091. }
  9092. // Not authorized to create new room
  9093. if ($(error).find('>error>not-authorized').length) {
  9094. logger.warn("Unauthorized to start the conference", error);
  9095. var toDomain
  9096. = Strophe.getDomainFromJid(error.getAttribute('to'));
  9097. if (toDomain !==
  9098. this.xmppService.options.hosts.anonymousdomain) {
  9099. //FIXME: "is external" should come either from
  9100. // the focus or config.js
  9101. self.externalAuthEnabled = true;
  9102. }
  9103. self.eventEmitter.emit(
  9104. XMPPEvents.AUTHENTICATION_REQUIRED,
  9105. function () {
  9106. self.allocateConferenceFocus(
  9107. callback);
  9108. });
  9109. return;
  9110. }
  9111. var waitMs = self.getNextErrorTimeout();
  9112. logger.error("Focus error, retry after " + waitMs, error);
  9113. // Show message
  9114. var focusComponent = self.getFocusComponent();
  9115. var retrySec = waitMs / 1000;
  9116. //FIXME: message is duplicated ?
  9117. // Do not show in case of session invalid
  9118. // which means just a retry
  9119. if (!invalidSession) {
  9120. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  9121. focusComponent, retrySec);
  9122. }
  9123. // Reset response timeout
  9124. self.getNextTimeout(true);
  9125. window.setTimeout(
  9126. function () {
  9127. self.allocateConferenceFocus(callback);
  9128. }, waitMs);
  9129. }
  9130. );
  9131. };
  9132. Moderator.prototype.getLoginUrl = function (urlCallback) {
  9133. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9134. iq.c('login-url', {
  9135. xmlns: 'http://jitsi.org/protocol/focus',
  9136. room: this.roomName,
  9137. 'machine-uid': this.settings.getSettings().uid
  9138. });
  9139. this.connection.sendIQ(
  9140. iq,
  9141. function (result) {
  9142. var url = $(result).find('login-url').attr('url');
  9143. url = url = decodeURIComponent(url);
  9144. if (url) {
  9145. logger.info("Got auth url: " + url);
  9146. urlCallback(url);
  9147. } else {
  9148. logger.error(
  9149. "Failed to get auth url from the focus", result);
  9150. }
  9151. },
  9152. function (error) {
  9153. logger.error("Get auth url error", error);
  9154. }
  9155. );
  9156. };
  9157. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  9158. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  9159. iq.c('login-url', {
  9160. xmlns: 'http://jitsi.org/protocol/focus',
  9161. room: this.roomName,
  9162. 'machine-uid': this.settings.getSettings().uid,
  9163. popup: true
  9164. });
  9165. this.connection.sendIQ(
  9166. iq,
  9167. function (result) {
  9168. var url = $(result).find('login-url').attr('url');
  9169. url = url = decodeURIComponent(url);
  9170. if (url) {
  9171. logger.info("Got POPUP auth url: " + url);
  9172. urlCallback(url);
  9173. } else {
  9174. logger.error(
  9175. "Failed to get POPUP auth url from the focus", result);
  9176. }
  9177. },
  9178. function (error) {
  9179. logger.error('Get POPUP auth url error', error);
  9180. }
  9181. );
  9182. };
  9183. Moderator.prototype.logout = function (callback) {
  9184. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  9185. var sessionId = localStorage.getItem('sessionId');
  9186. if (!sessionId) {
  9187. callback();
  9188. return;
  9189. }
  9190. iq.c('logout', {
  9191. xmlns: 'http://jitsi.org/protocol/focus',
  9192. 'session-id': sessionId
  9193. });
  9194. this.connection.sendIQ(
  9195. iq,
  9196. function (result) {
  9197. var logoutUrl = $(result).find('logout').attr('logout-url');
  9198. if (logoutUrl) {
  9199. logoutUrl = decodeURIComponent(logoutUrl);
  9200. }
  9201. logger.info("Log out OK, url: " + logoutUrl, result);
  9202. localStorage.removeItem('sessionId');
  9203. callback(logoutUrl);
  9204. },
  9205. function (error) {
  9206. logger.error("Logout error", error);
  9207. }
  9208. );
  9209. };
  9210. module.exports = Moderator;
  9211. }).call(this,"/modules/xmpp/moderator.js")
  9212. },{"../../service/authentication/AuthenticationEvents":80,"../../service/xmpp/XMPPEvents":84,"../settings/Settings":19,"jitsi-meet-logger":45}],33:[function(require,module,exports){
  9213. (function (__filename){
  9214. /* jshint -W117 */
  9215. /* a simple MUC connection plugin
  9216. * can only handle a single MUC room
  9217. */
  9218. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9219. var ChatRoom = require("./ChatRoom");
  9220. module.exports = function(XMPP) {
  9221. Strophe.addConnectionPlugin('emuc', {
  9222. connection: null,
  9223. rooms: {},//map with the rooms
  9224. init: function (conn) {
  9225. this.connection = conn;
  9226. // add handlers (just once)
  9227. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  9228. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  9229. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  9230. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  9231. },
  9232. createRoom: function (jid, password, options) {
  9233. var roomJid = Strophe.getBareJidFromJid(jid);
  9234. if (this.rooms[roomJid]) {
  9235. logger.error("You are already in the room!");
  9236. return;
  9237. }
  9238. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  9239. return this.rooms[roomJid];
  9240. },
  9241. doLeave: function (jid) {
  9242. this.rooms[jid].doLeave();
  9243. delete this.rooms[jid];
  9244. },
  9245. onPresence: function (pres) {
  9246. var from = pres.getAttribute('from');
  9247. // What is this for? A workaround for something?
  9248. if (pres.getAttribute('type')) {
  9249. return true;
  9250. }
  9251. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9252. if(!room)
  9253. return;
  9254. // Parse status.
  9255. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  9256. room.createNonAnonymousRoom();
  9257. }
  9258. room.onPresence(pres);
  9259. return true;
  9260. },
  9261. onPresenceUnavailable: function (pres) {
  9262. var from = pres.getAttribute('from');
  9263. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9264. if(!room)
  9265. return;
  9266. room.onPresenceUnavailable(pres, from);
  9267. return true;
  9268. },
  9269. onPresenceError: function (pres) {
  9270. var from = pres.getAttribute('from');
  9271. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9272. if(!room)
  9273. return;
  9274. room.onPresenceError(pres, from);
  9275. return true;
  9276. },
  9277. onMessage: function (msg) {
  9278. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  9279. var from = msg.getAttribute('from');
  9280. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9281. if(!room)
  9282. return;
  9283. room.onMessage(msg, from);
  9284. return true;
  9285. },
  9286. setJingleSession: function (from, session) {
  9287. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  9288. if(!room)
  9289. return;
  9290. room.setJingleSession(session);
  9291. }
  9292. });
  9293. };
  9294. }).call(this,"/modules/xmpp/strophe.emuc.js")
  9295. },{"./ChatRoom":24,"jitsi-meet-logger":45}],34:[function(require,module,exports){
  9296. (function (__filename){
  9297. /* jshint -W117 */
  9298. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9299. var JingleSession = require("./JingleSessionPC");
  9300. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9301. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9302. module.exports = function(XMPP, eventEmitter) {
  9303. Strophe.addConnectionPlugin('jingle', {
  9304. connection: null,
  9305. sessions: {},
  9306. jid2session: {},
  9307. ice_config: {iceServers: []},
  9308. media_constraints: {
  9309. mandatory: {
  9310. 'OfferToReceiveAudio': true,
  9311. 'OfferToReceiveVideo': true
  9312. }
  9313. // MozDontOfferDataChannel: true when this is firefox
  9314. },
  9315. init: function (conn) {
  9316. this.connection = conn;
  9317. if (this.connection.disco) {
  9318. // http://xmpp.org/extensions/xep-0167.html#support
  9319. // http://xmpp.org/extensions/xep-0176.html#support
  9320. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  9321. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  9322. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  9323. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  9324. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  9325. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  9326. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  9327. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  9328. || RTCBrowserType.isTemasysPluginUsed()) {
  9329. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  9330. }
  9331. // this is dealt with by SDP O/A so we don't need to announce this
  9332. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  9333. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  9334. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  9335. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  9336. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  9337. }
  9338. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  9339. },
  9340. onJingle: function (iq) {
  9341. var sid = $(iq).find('jingle').attr('sid');
  9342. var action = $(iq).find('jingle').attr('action');
  9343. var fromJid = iq.getAttribute('from');
  9344. // send ack first
  9345. var ack = $iq({type: 'result',
  9346. to: fromJid,
  9347. id: iq.getAttribute('id')
  9348. });
  9349. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  9350. var sess = this.sessions[sid];
  9351. if ('session-initiate' != action) {
  9352. if (sess === null) {
  9353. ack.type = 'error';
  9354. ack.c('error', {type: 'cancel'})
  9355. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9356. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9357. this.connection.send(ack);
  9358. return true;
  9359. }
  9360. // local jid is not checked
  9361. if (fromJid != sess.peerjid) {
  9362. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  9363. ack.type = 'error';
  9364. ack.c('error', {type: 'cancel'})
  9365. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  9366. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  9367. this.connection.send(ack);
  9368. return true;
  9369. }
  9370. } else if (sess !== undefined) {
  9371. // existing session with same session id
  9372. // this might be out-of-order if the sess.peerjid is the same as from
  9373. ack.type = 'error';
  9374. ack.c('error', {type: 'cancel'})
  9375. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  9376. logger.warn('duplicate session id', sid);
  9377. this.connection.send(ack);
  9378. return true;
  9379. }
  9380. // FIXME: check for a defined action
  9381. this.connection.send(ack);
  9382. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  9383. switch (action) {
  9384. case 'session-initiate':
  9385. console.log("(TIME) received session-initiate:\t",
  9386. window.performance.now());
  9387. var startMuted = $(iq).find('jingle>startmuted');
  9388. if (startMuted && startMuted.length > 0) {
  9389. var audioMuted = startMuted.attr("audio");
  9390. var videoMuted = startMuted.attr("video");
  9391. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  9392. audioMuted === "true", videoMuted === "true");
  9393. }
  9394. sess = new JingleSession(
  9395. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  9396. this.connection, XMPP);
  9397. // configure session
  9398. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  9399. this.connection.emuc.setJingleSession(fromBareJid, sess);
  9400. sess.media_constraints = this.media_constraints;
  9401. sess.ice_config = this.ice_config;
  9402. sess.initialize(fromJid, false);
  9403. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  9404. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  9405. sess.setOffer($(iq).find('>jingle'));
  9406. this.sessions[sess.sid] = sess;
  9407. this.jid2session[sess.peerjid] = sess;
  9408. // the callback should either
  9409. // .sendAnswer and .accept
  9410. // or .sendTerminate -- not necessarily synchronous
  9411. sess.sendAnswer();
  9412. sess.accept();
  9413. break;
  9414. case 'session-accept':
  9415. sess.setAnswer($(iq).find('>jingle'));
  9416. sess.accept();
  9417. break;
  9418. case 'session-terminate':
  9419. // If this is not the focus sending the terminate, we have
  9420. // nothing more to do here.
  9421. if (Object.keys(this.sessions).length < 1
  9422. || !(this.sessions[Object.keys(this.sessions)[0]]
  9423. instanceof JingleSession))
  9424. {
  9425. break;
  9426. }
  9427. logger.log('terminating...', sess.sid);
  9428. sess.terminate();
  9429. this.terminate(sess.sid);
  9430. if ($(iq).find('>jingle>reason').length) {
  9431. $(document).trigger('callterminated.jingle', [
  9432. sess.sid,
  9433. sess.peerjid,
  9434. $(iq).find('>jingle>reason>:first')[0].tagName,
  9435. $(iq).find('>jingle>reason>text').text()
  9436. ]);
  9437. } else {
  9438. $(document).trigger('callterminated.jingle',
  9439. [sess.sid, sess.peerjid]);
  9440. }
  9441. break;
  9442. case 'transport-info':
  9443. sess.addIceCandidate($(iq).find('>jingle>content'));
  9444. break;
  9445. case 'session-info':
  9446. var affected;
  9447. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9448. $(document).trigger('ringing.jingle', [sess.sid]);
  9449. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9450. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9451. $(document).trigger('mute.jingle', [sess.sid, affected]);
  9452. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  9453. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  9454. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  9455. }
  9456. break;
  9457. case 'addsource': // FIXME: proprietary, un-jingleish
  9458. case 'source-add': // FIXME: proprietary
  9459. sess.addSource($(iq).find('>jingle>content'));
  9460. break;
  9461. case 'removesource': // FIXME: proprietary, un-jingleish
  9462. case 'source-remove': // FIXME: proprietary
  9463. sess.removeSource($(iq).find('>jingle>content'));
  9464. break;
  9465. default:
  9466. logger.warn('jingle action not implemented', action);
  9467. break;
  9468. }
  9469. return true;
  9470. },
  9471. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  9472. if (sid === null || sid === undefined) {
  9473. for (sid in this.sessions) {
  9474. if (this.sessions[sid].state != 'ended') {
  9475. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  9476. this.sessions[sid].terminate();
  9477. }
  9478. delete this.jid2session[this.sessions[sid].peerjid];
  9479. delete this.sessions[sid];
  9480. }
  9481. } else if (this.sessions.hasOwnProperty(sid)) {
  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. },
  9490. getStunAndTurnCredentials: function () {
  9491. // get stun and turn configuration from server via xep-0215
  9492. // uses time-limited credentials as described in
  9493. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  9494. //
  9495. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  9496. // for a prosody module which implements this
  9497. //
  9498. // currently, this doesn't work with updateIce and therefore credentials with a long
  9499. // validity have to be fetched before creating the peerconnection
  9500. // TODO: implement refresh via updateIce as described in
  9501. // https://code.google.com/p/webrtc/issues/detail?id=1650
  9502. var self = this;
  9503. this.connection.sendIQ(
  9504. $iq({type: 'get', to: this.connection.domain})
  9505. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  9506. function (res) {
  9507. var iceservers = [];
  9508. $(res).find('>services>service').each(function (idx, el) {
  9509. el = $(el);
  9510. var dict = {};
  9511. var type = el.attr('type');
  9512. switch (type) {
  9513. case 'stun':
  9514. dict.url = 'stun:' + el.attr('host');
  9515. if (el.attr('port')) {
  9516. dict.url += ':' + el.attr('port');
  9517. }
  9518. iceservers.push(dict);
  9519. break;
  9520. case 'turn':
  9521. case 'turns':
  9522. dict.url = type + ':';
  9523. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  9524. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  9525. dict.url += el.attr('username') + '@';
  9526. } else {
  9527. dict.username = el.attr('username'); // only works in M28
  9528. }
  9529. }
  9530. dict.url += el.attr('host');
  9531. if (el.attr('port') && el.attr('port') != '3478') {
  9532. dict.url += ':' + el.attr('port');
  9533. }
  9534. if (el.attr('transport') && el.attr('transport') != 'udp') {
  9535. dict.url += '?transport=' + el.attr('transport');
  9536. }
  9537. if (el.attr('password')) {
  9538. dict.credential = el.attr('password');
  9539. }
  9540. iceservers.push(dict);
  9541. break;
  9542. }
  9543. });
  9544. self.ice_config.iceServers = iceservers;
  9545. },
  9546. function (err) {
  9547. logger.warn('getting turn credentials failed', err);
  9548. logger.warn('is mod_turncredentials or similar installed?');
  9549. }
  9550. );
  9551. // implement push?
  9552. },
  9553. /**
  9554. * Returns the data saved in 'updateLog' in a format to be logged.
  9555. */
  9556. getLog: function () {
  9557. var data = {};
  9558. var self = this;
  9559. Object.keys(this.sessions).forEach(function (sid) {
  9560. var session = self.sessions[sid];
  9561. if (session.peerconnection && session.peerconnection.updateLog) {
  9562. // FIXME: should probably be a .dump call
  9563. data["jingle_" + session.sid] = {
  9564. updateLog: session.peerconnection.updateLog,
  9565. stats: session.peerconnection.stats,
  9566. url: window.location.href
  9567. };
  9568. }
  9569. });
  9570. return data;
  9571. }
  9572. });
  9573. };
  9574. }).call(this,"/modules/xmpp/strophe.jingle.js")
  9575. },{"../../service/xmpp/XMPPEvents":84,"../RTC/RTCBrowserType":14,"./JingleSessionPC":26,"jitsi-meet-logger":45}],35:[function(require,module,exports){
  9576. /* global Strophe */
  9577. module.exports = function () {
  9578. Strophe.addConnectionPlugin('logger', {
  9579. // logs raw stanzas and makes them available for download as JSON
  9580. connection: null,
  9581. log: [],
  9582. init: function (conn) {
  9583. this.connection = conn;
  9584. this.connection.rawInput = this.log_incoming.bind(this);
  9585. this.connection.rawOutput = this.log_outgoing.bind(this);
  9586. },
  9587. log_incoming: function (stanza) {
  9588. this.log.push([new Date().getTime(), 'incoming', stanza]);
  9589. },
  9590. log_outgoing: function (stanza) {
  9591. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  9592. }
  9593. });
  9594. };
  9595. },{}],36:[function(require,module,exports){
  9596. (function (__filename){
  9597. /* global $, $iq, Strophe */
  9598. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9599. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9600. /**
  9601. * Ping every 20 sec
  9602. */
  9603. var PING_INTERVAL = 20000;
  9604. /**
  9605. * Ping timeout error after 15 sec of waiting.
  9606. */
  9607. var PING_TIMEOUT = 15000;
  9608. /**
  9609. * Will close the connection after 3 consecutive ping errors.
  9610. */
  9611. var PING_THRESHOLD = 3;
  9612. /**
  9613. * XEP-0199 ping plugin.
  9614. *
  9615. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  9616. */
  9617. module.exports = function (XMPP, eventEmitter) {
  9618. Strophe.addConnectionPlugin('ping', {
  9619. connection: null,
  9620. failedPings: 0,
  9621. /**
  9622. * Initializes the plugin. Method called by Strophe.
  9623. * @param connection Strophe connection instance.
  9624. */
  9625. init: function (connection) {
  9626. this.connection = connection;
  9627. Strophe.addNamespace('PING', "urn:xmpp:ping");
  9628. },
  9629. /**
  9630. * Sends "ping" to given <tt>jid</tt>
  9631. * @param jid the JID to which ping request will be sent.
  9632. * @param success callback called on success.
  9633. * @param error callback called on error.
  9634. * @param timeout ms how long are we going to wait for the response. On
  9635. * timeout <tt>error<//t> callback is called with undefined error
  9636. * argument.
  9637. */
  9638. ping: function (jid, success, error, timeout) {
  9639. var iq = $iq({type: 'get', to: jid});
  9640. iq.c('ping', {xmlns: Strophe.NS.PING});
  9641. this.connection.sendIQ(iq, success, error, timeout);
  9642. },
  9643. /**
  9644. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  9645. * @param jid the JID to be checked for ping support.
  9646. * @param callback function with boolean argument which will be
  9647. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  9648. */
  9649. hasPingSupport: function (jid, callback) {
  9650. this.connection.disco.info(
  9651. jid, null,
  9652. function (result) {
  9653. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  9654. callback(ping.length > 0);
  9655. },
  9656. function (error) {
  9657. logger.error("Ping feature discovery error", error);
  9658. callback(false);
  9659. }
  9660. );
  9661. },
  9662. /**
  9663. * Starts to send ping in given interval to specified remote JID.
  9664. * This plugin supports only one such task and <tt>stopInterval</tt>
  9665. * must be called before starting a new one.
  9666. * @param remoteJid remote JID to which ping requests will be sent to.
  9667. * @param interval task interval in ms.
  9668. */
  9669. startInterval: function (remoteJid, interval) {
  9670. if (this.intervalId) {
  9671. logger.error("Ping task scheduled already");
  9672. return;
  9673. }
  9674. if (!interval)
  9675. interval = PING_INTERVAL;
  9676. var self = this;
  9677. this.intervalId = window.setInterval(function () {
  9678. self.ping(remoteJid,
  9679. function (result) {
  9680. // Ping OK
  9681. self.failedPings = 0;
  9682. },
  9683. function (error) {
  9684. self.failedPings += 1;
  9685. logger.error(
  9686. "Ping " + (error ? "error" : "timeout"), error);
  9687. if (self.failedPings >= PING_THRESHOLD) {
  9688. self.connection.disconnect();
  9689. }
  9690. }, PING_TIMEOUT);
  9691. }, interval);
  9692. logger.info("XMPP pings will be sent every " + interval + " ms");
  9693. },
  9694. /**
  9695. * Stops current "ping" interval task.
  9696. */
  9697. stopInterval: function () {
  9698. if (this.intervalId) {
  9699. window.clearInterval(this.intervalId);
  9700. this.intervalId = null;
  9701. this.failedPings = 0;
  9702. logger.info("Ping interval cleared");
  9703. }
  9704. }
  9705. });
  9706. };
  9707. }).call(this,"/modules/xmpp/strophe.ping.js")
  9708. },{"../../service/xmpp/XMPPEvents":84,"jitsi-meet-logger":45}],37:[function(require,module,exports){
  9709. (function (__filename){
  9710. /* jshint -W117 */
  9711. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9712. module.exports = function() {
  9713. Strophe.addConnectionPlugin('rayo',
  9714. {
  9715. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  9716. connection: null,
  9717. init: function (conn) {
  9718. this.connection = conn;
  9719. if (this.connection.disco) {
  9720. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  9721. }
  9722. this.connection.addHandler(
  9723. this.onRayo.bind(this),
  9724. this.RAYO_XMLNS, 'iq', 'set', null, null);
  9725. },
  9726. onRayo: function (iq) {
  9727. logger.info("Rayo IQ", iq);
  9728. },
  9729. dial: function (to, from, roomName, roomPass) {
  9730. var self = this;
  9731. var req = $iq(
  9732. {
  9733. type: 'set',
  9734. to: this.connection.emuc.focusMucJid
  9735. }
  9736. );
  9737. req.c('dial',
  9738. {
  9739. xmlns: this.RAYO_XMLNS,
  9740. to: to,
  9741. from: from
  9742. });
  9743. req.c('header',
  9744. {
  9745. name: 'JvbRoomName',
  9746. value: roomName
  9747. }).up();
  9748. if (roomPass !== null && roomPass.length) {
  9749. req.c('header',
  9750. {
  9751. name: 'JvbRoomPassword',
  9752. value: roomPass
  9753. }).up();
  9754. }
  9755. this.connection.sendIQ(
  9756. req,
  9757. function (result) {
  9758. logger.info('Dial result ', result);
  9759. var resource = $(result).find('ref').attr('uri');
  9760. this.call_resource = resource.substr('xmpp:'.length);
  9761. logger.info(
  9762. "Received call resource: " + this.call_resource);
  9763. },
  9764. function (error) {
  9765. logger.info('Dial error ', error);
  9766. }
  9767. );
  9768. },
  9769. hang_up: function () {
  9770. if (!this.call_resource) {
  9771. logger.warn("No call in progress");
  9772. return;
  9773. }
  9774. var self = this;
  9775. var req = $iq(
  9776. {
  9777. type: 'set',
  9778. to: this.call_resource
  9779. }
  9780. );
  9781. req.c('hangup',
  9782. {
  9783. xmlns: this.RAYO_XMLNS
  9784. });
  9785. this.connection.sendIQ(
  9786. req,
  9787. function (result) {
  9788. logger.info('Hangup result ', result);
  9789. self.call_resource = null;
  9790. },
  9791. function (error) {
  9792. logger.info('Hangup error ', error);
  9793. self.call_resource = null;
  9794. }
  9795. );
  9796. }
  9797. }
  9798. );
  9799. };
  9800. }).call(this,"/modules/xmpp/strophe.rayo.js")
  9801. },{"jitsi-meet-logger":45}],38:[function(require,module,exports){
  9802. (function (__filename){
  9803. /* global Strophe */
  9804. /**
  9805. * Strophe logger implementation. Logs from level WARN and above.
  9806. */
  9807. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9808. module.exports = function () {
  9809. Strophe.log = function (level, msg) {
  9810. switch (level) {
  9811. case Strophe.LogLevel.WARN:
  9812. logger.warn("Strophe: " + msg);
  9813. break;
  9814. case Strophe.LogLevel.ERROR:
  9815. case Strophe.LogLevel.FATAL:
  9816. logger.error("Strophe: " + msg);
  9817. break;
  9818. }
  9819. };
  9820. Strophe.getStatusString = function (status) {
  9821. switch (status) {
  9822. case Strophe.Status.ERROR:
  9823. return "ERROR";
  9824. case Strophe.Status.CONNECTING:
  9825. return "CONNECTING";
  9826. case Strophe.Status.CONNFAIL:
  9827. return "CONNFAIL";
  9828. case Strophe.Status.AUTHENTICATING:
  9829. return "AUTHENTICATING";
  9830. case Strophe.Status.AUTHFAIL:
  9831. return "AUTHFAIL";
  9832. case Strophe.Status.CONNECTED:
  9833. return "CONNECTED";
  9834. case Strophe.Status.DISCONNECTED:
  9835. return "DISCONNECTED";
  9836. case Strophe.Status.DISCONNECTING:
  9837. return "DISCONNECTING";
  9838. case Strophe.Status.ATTACHED:
  9839. return "ATTACHED";
  9840. default:
  9841. return "unknown";
  9842. }
  9843. };
  9844. };
  9845. }).call(this,"/modules/xmpp/strophe.util.js")
  9846. },{"jitsi-meet-logger":45}],39:[function(require,module,exports){
  9847. (function (__filename){
  9848. /* global $, APP, config, Strophe*/
  9849. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9850. var EventEmitter = require("events");
  9851. var Pako = require("pako");
  9852. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  9853. var RTCEvents = require("../../service/RTC/RTCEvents");
  9854. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9855. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  9856. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  9857. var RTC = require("../RTC/RTC");
  9858. var authenticatedUser = false;
  9859. function createConnection(bosh) {
  9860. bosh = bosh || '/http-bind';
  9861. return new Strophe.Connection(bosh);
  9862. };
  9863. //!!!!!!!!!! FIXME: ...
  9864. function initStrophePlugins(XMPP)
  9865. {
  9866. require("./strophe.emuc")(XMPP);
  9867. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  9868. // require("./strophe.moderate")(XMPP, eventEmitter);
  9869. require("./strophe.util")();
  9870. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  9871. require("./strophe.rayo")();
  9872. require("./strophe.logger")();
  9873. }
  9874. //!!!!!!!!!! FIXME: ...
  9875. ///**
  9876. // * If given <tt>localStream</tt> is video one this method will advertise it's
  9877. // * video type in MUC presence.
  9878. // * @param localStream new or modified <tt>LocalStream</tt>.
  9879. // */
  9880. //function broadcastLocalVideoType(localStream) {
  9881. // if (localStream.videoType)
  9882. // XMPP.addToPresence('videoType', localStream.videoType);
  9883. //}
  9884. //
  9885. //function registerListeners() {
  9886. // RTC.addStreamListener(
  9887. // broadcastLocalVideoType,
  9888. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  9889. // );
  9890. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  9891. // XMPP.addToPresence("devices", devices);
  9892. // });
  9893. //}
  9894. function XMPP(options) {
  9895. this.eventEmitter = new EventEmitter();
  9896. this.connection = null;
  9897. this.disconnectInProgress = false;
  9898. this.forceMuted = false;
  9899. this.options = options;
  9900. initStrophePlugins(this);
  9901. // registerListeners();
  9902. this.connection = createConnection(options.bosh);
  9903. }
  9904. XMPP.prototype.getConnection = function(){ return connection; };
  9905. XMPP.prototype._connect = function (jid, password) {
  9906. var self = this;
  9907. // connection.connect() starts the connection process.
  9908. //
  9909. // As the connection process proceeds, the user supplied callback will
  9910. // be triggered multiple times with status updates. The callback should
  9911. // take two arguments - the status code and the error condition.
  9912. //
  9913. // The status code will be one of the values in the Strophe.Status
  9914. // constants. The error condition will be one of the conditions defined
  9915. // in RFC 3920 or the condition ‘strophe-parsererror’.
  9916. //
  9917. // The Parameters wait, hold and route are optional and only relevant
  9918. // for BOSH connections. Please see XEP 124 for a more detailed
  9919. // explanation of the optional parameters.
  9920. //
  9921. // Connection status constants for use by the connection handler
  9922. // callback.
  9923. //
  9924. // Status.ERROR - An error has occurred (websockets specific)
  9925. // Status.CONNECTING - The connection is currently being made
  9926. // Status.CONNFAIL - The connection attempt failed
  9927. // Status.AUTHENTICATING - The connection is authenticating
  9928. // Status.AUTHFAIL - The authentication attempt failed
  9929. // Status.CONNECTED - The connection has succeeded
  9930. // Status.DISCONNECTED - The connection has been terminated
  9931. // Status.DISCONNECTING - The connection is currently being terminated
  9932. // Status.ATTACHED - The connection has been attached
  9933. var anonymousConnectionFailed = false;
  9934. var connectionFailed = false;
  9935. var lastErrorMsg;
  9936. this.connection.connect(jid, password, function (status, msg) {
  9937. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  9938. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  9939. if (status === Strophe.Status.CONNECTED) {
  9940. if (self.options.useStunTurn) {
  9941. self.connection.jingle.getStunAndTurnCredentials();
  9942. }
  9943. logger.info("My Jabber ID: " + self.connection.jid);
  9944. // Schedule ping ?
  9945. var pingJid = self.connection.domain;
  9946. self.connection.ping.hasPingSupport(
  9947. pingJid,
  9948. function (hasPing) {
  9949. if (hasPing)
  9950. self.connection.ping.startInterval(pingJid);
  9951. else
  9952. logger.warn("Ping NOT supported by " + pingJid);
  9953. }
  9954. );
  9955. if (password)
  9956. authenticatedUser = true;
  9957. if (self.connection && self.connection.connected &&
  9958. Strophe.getResourceFromJid(self.connection.jid)) {
  9959. // .connected is true while connecting?
  9960. // self.connection.send($pres());
  9961. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  9962. Strophe.getResourceFromJid(self.connection.jid));
  9963. }
  9964. } else if (status === Strophe.Status.CONNFAIL) {
  9965. if (msg === 'x-strophe-bad-non-anon-jid') {
  9966. anonymousConnectionFailed = true;
  9967. }
  9968. else
  9969. {
  9970. connectionFailed = true;
  9971. }
  9972. lastErrorMsg = msg;
  9973. } else if (status === Strophe.Status.DISCONNECTED) {
  9974. // Stop ping interval
  9975. self.connection.ping.stopInterval();
  9976. self.disconnectInProgress = false;
  9977. if (anonymousConnectionFailed) {
  9978. // prompt user for username and password
  9979. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9980. JitsiConnectionErrors.PASSWORD_REQUIRED);
  9981. } else if(connectionFailed) {
  9982. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9983. JitsiConnectionErrors.OTHER_ERROR,
  9984. msg ? msg : lastErrorMsg);
  9985. } else {
  9986. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  9987. msg ? msg : lastErrorMsg);
  9988. }
  9989. } else if (status === Strophe.Status.AUTHFAIL) {
  9990. // wrong password or username, prompt user
  9991. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  9992. JitsiConnectionErrors.PASSWORD_REQUIRED);
  9993. }
  9994. });
  9995. }
  9996. XMPP.prototype.connect = function (jid, password) {
  9997. if(!jid) {
  9998. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  9999. // Force authenticated domain if room is appended with '?login=true'
  10000. if (this.options.hosts.anonymousdomain &&
  10001. window.location.search.indexOf("login=true") !== -1) {
  10002. configDomain = this.options.hosts.domain;
  10003. }
  10004. jid = configDomain || window.location.hostname;
  10005. }
  10006. return this._connect(jid, password);
  10007. };
  10008. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  10009. var roomjid = roomName + '@' + this.options.hosts.muc;
  10010. if (useNicks) {
  10011. if (nick) {
  10012. roomjid += '/' + nick;
  10013. } else {
  10014. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  10015. }
  10016. } else {
  10017. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  10018. if(!authenticatedUser)
  10019. tmpJid = tmpJid.substr(0, 8);
  10020. roomjid += '/' + tmpJid;
  10021. }
  10022. return this.connection.emuc.createRoom(roomjid, null, options);
  10023. }
  10024. XMPP.prototype.addListener = function(type, listener) {
  10025. this.eventEmitter.on(type, listener);
  10026. };
  10027. XMPP.prototype.removeListener = function (type, listener) {
  10028. this.eventEmitter.removeListener(type, listener);
  10029. };
  10030. //FIXME: this should work with the room
  10031. XMPP.prototype.leaveRoom = function (jid) {
  10032. var handler = this.connection.jingle.jid2session[jid];
  10033. if (handler && handler.peerconnection) {
  10034. // FIXME: probably removing streams is not required and close() should
  10035. // be enough
  10036. if (RTC.localAudio) {
  10037. handler.peerconnection.removeStream(
  10038. RTC.localAudio.getOriginalStream(), true);
  10039. }
  10040. if (RTC.localVideo) {
  10041. handler.peerconnection.removeStream(
  10042. RTC.localVideo.getOriginalStream(), true);
  10043. }
  10044. handler.peerconnection.close();
  10045. }
  10046. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  10047. this.connection.emuc.doLeave(jid);
  10048. };
  10049. /**
  10050. * Sends 'data' as a log message to the focus. Returns true iff a message
  10051. * was sent.
  10052. * @param data
  10053. * @returns {boolean} true iff a message was sent.
  10054. */
  10055. XMPP.prototype.sendLogs = function (data) {
  10056. if(!this.connection.emuc.focusMucJid)
  10057. return false;
  10058. var deflate = true;
  10059. var content = JSON.stringify(data);
  10060. if (deflate) {
  10061. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  10062. }
  10063. content = Base64.encode(content);
  10064. // XEP-0337-ish
  10065. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  10066. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  10067. id: 'PeerConnectionStats'});
  10068. message.c('message').t(content).up();
  10069. if (deflate) {
  10070. message.c('tag', {name: "deflated", value: "true"}).up();
  10071. }
  10072. message.up();
  10073. this.connection.send(message);
  10074. return true;
  10075. };
  10076. // Gets the logs from strophe.jingle.
  10077. XMPP.prototype.getJingleLog = function () {
  10078. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  10079. };
  10080. // Gets the logs from strophe.
  10081. XMPP.prototype.getXmppLog = function () {
  10082. return this.connection.logger ? this.connection.logger.log : null;
  10083. };
  10084. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  10085. this.connection.rayo.dial(to, from, roomName,roomPass);
  10086. };
  10087. XMPP.prototype.setMute = function (jid, mute) {
  10088. this.connection.moderate.setMute(jid, mute);
  10089. };
  10090. XMPP.prototype.eject = function (jid) {
  10091. this.connection.moderate.eject(jid);
  10092. };
  10093. XMPP.prototype.getSessions = function () {
  10094. return this.connection.jingle.sessions;
  10095. };
  10096. XMPP.prototype.disconnect = function () {
  10097. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  10098. {
  10099. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  10100. return;
  10101. }
  10102. this.disconnectInProgress = true;
  10103. this.connection.disconnect();
  10104. };
  10105. module.exports = XMPP;
  10106. }).call(this,"/modules/xmpp/xmpp.js")
  10107. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":77,"../../service/RTC/StreamEventTypes":79,"../../service/xmpp/XMPPEvents":84,"../RTC/RTC":13,"./strophe.emuc":33,"./strophe.jingle":34,"./strophe.logger":35,"./strophe.ping":36,"./strophe.rayo":37,"./strophe.util":38,"events":41,"jitsi-meet-logger":45,"pako":46}],40:[function(require,module,exports){
  10108. (function (process){
  10109. /*!
  10110. * async
  10111. * https://github.com/caolan/async
  10112. *
  10113. * Copyright 2010-2014 Caolan McMahon
  10114. * Released under the MIT license
  10115. */
  10116. /*jshint onevar: false, indent:4 */
  10117. /*global setImmediate: false, setTimeout: false, console: false */
  10118. (function () {
  10119. var async = {};
  10120. // global on the server, window in the browser
  10121. var root, previous_async;
  10122. root = this;
  10123. if (root != null) {
  10124. previous_async = root.async;
  10125. }
  10126. async.noConflict = function () {
  10127. root.async = previous_async;
  10128. return async;
  10129. };
  10130. function only_once(fn) {
  10131. var called = false;
  10132. return function() {
  10133. if (called) throw new Error("Callback was already called.");
  10134. called = true;
  10135. fn.apply(root, arguments);
  10136. }
  10137. }
  10138. //// cross-browser compatiblity functions ////
  10139. var _toString = Object.prototype.toString;
  10140. var _isArray = Array.isArray || function (obj) {
  10141. return _toString.call(obj) === '[object Array]';
  10142. };
  10143. var _each = function (arr, iterator) {
  10144. if (arr.forEach) {
  10145. return arr.forEach(iterator);
  10146. }
  10147. for (var i = 0; i < arr.length; i += 1) {
  10148. iterator(arr[i], i, arr);
  10149. }
  10150. };
  10151. var _map = function (arr, iterator) {
  10152. if (arr.map) {
  10153. return arr.map(iterator);
  10154. }
  10155. var results = [];
  10156. _each(arr, function (x, i, a) {
  10157. results.push(iterator(x, i, a));
  10158. });
  10159. return results;
  10160. };
  10161. var _reduce = function (arr, iterator, memo) {
  10162. if (arr.reduce) {
  10163. return arr.reduce(iterator, memo);
  10164. }
  10165. _each(arr, function (x, i, a) {
  10166. memo = iterator(memo, x, i, a);
  10167. });
  10168. return memo;
  10169. };
  10170. var _keys = function (obj) {
  10171. if (Object.keys) {
  10172. return Object.keys(obj);
  10173. }
  10174. var keys = [];
  10175. for (var k in obj) {
  10176. if (obj.hasOwnProperty(k)) {
  10177. keys.push(k);
  10178. }
  10179. }
  10180. return keys;
  10181. };
  10182. //// exported async module functions ////
  10183. //// nextTick implementation with browser-compatible fallback ////
  10184. if (typeof process === 'undefined' || !(process.nextTick)) {
  10185. if (typeof setImmediate === 'function') {
  10186. async.nextTick = function (fn) {
  10187. // not a direct alias for IE10 compatibility
  10188. setImmediate(fn);
  10189. };
  10190. async.setImmediate = async.nextTick;
  10191. }
  10192. else {
  10193. async.nextTick = function (fn) {
  10194. setTimeout(fn, 0);
  10195. };
  10196. async.setImmediate = async.nextTick;
  10197. }
  10198. }
  10199. else {
  10200. async.nextTick = process.nextTick;
  10201. if (typeof setImmediate !== 'undefined') {
  10202. async.setImmediate = function (fn) {
  10203. // not a direct alias for IE10 compatibility
  10204. setImmediate(fn);
  10205. };
  10206. }
  10207. else {
  10208. async.setImmediate = async.nextTick;
  10209. }
  10210. }
  10211. async.each = function (arr, iterator, callback) {
  10212. callback = callback || function () {};
  10213. if (!arr.length) {
  10214. return callback();
  10215. }
  10216. var completed = 0;
  10217. _each(arr, function (x) {
  10218. iterator(x, only_once(done) );
  10219. });
  10220. function done(err) {
  10221. if (err) {
  10222. callback(err);
  10223. callback = function () {};
  10224. }
  10225. else {
  10226. completed += 1;
  10227. if (completed >= arr.length) {
  10228. callback();
  10229. }
  10230. }
  10231. }
  10232. };
  10233. async.forEach = async.each;
  10234. async.eachSeries = function (arr, iterator, callback) {
  10235. callback = callback || function () {};
  10236. if (!arr.length) {
  10237. return callback();
  10238. }
  10239. var completed = 0;
  10240. var iterate = function () {
  10241. iterator(arr[completed], function (err) {
  10242. if (err) {
  10243. callback(err);
  10244. callback = function () {};
  10245. }
  10246. else {
  10247. completed += 1;
  10248. if (completed >= arr.length) {
  10249. callback();
  10250. }
  10251. else {
  10252. iterate();
  10253. }
  10254. }
  10255. });
  10256. };
  10257. iterate();
  10258. };
  10259. async.forEachSeries = async.eachSeries;
  10260. async.eachLimit = function (arr, limit, iterator, callback) {
  10261. var fn = _eachLimit(limit);
  10262. fn.apply(null, [arr, iterator, callback]);
  10263. };
  10264. async.forEachLimit = async.eachLimit;
  10265. var _eachLimit = function (limit) {
  10266. return function (arr, iterator, callback) {
  10267. callback = callback || function () {};
  10268. if (!arr.length || limit <= 0) {
  10269. return callback();
  10270. }
  10271. var completed = 0;
  10272. var started = 0;
  10273. var running = 0;
  10274. (function replenish () {
  10275. if (completed >= arr.length) {
  10276. return callback();
  10277. }
  10278. while (running < limit && started < arr.length) {
  10279. started += 1;
  10280. running += 1;
  10281. iterator(arr[started - 1], function (err) {
  10282. if (err) {
  10283. callback(err);
  10284. callback = function () {};
  10285. }
  10286. else {
  10287. completed += 1;
  10288. running -= 1;
  10289. if (completed >= arr.length) {
  10290. callback();
  10291. }
  10292. else {
  10293. replenish();
  10294. }
  10295. }
  10296. });
  10297. }
  10298. })();
  10299. };
  10300. };
  10301. var doParallel = function (fn) {
  10302. return function () {
  10303. var args = Array.prototype.slice.call(arguments);
  10304. return fn.apply(null, [async.each].concat(args));
  10305. };
  10306. };
  10307. var doParallelLimit = function(limit, fn) {
  10308. return function () {
  10309. var args = Array.prototype.slice.call(arguments);
  10310. return fn.apply(null, [_eachLimit(limit)].concat(args));
  10311. };
  10312. };
  10313. var doSeries = function (fn) {
  10314. return function () {
  10315. var args = Array.prototype.slice.call(arguments);
  10316. return fn.apply(null, [async.eachSeries].concat(args));
  10317. };
  10318. };
  10319. var _asyncMap = function (eachfn, arr, iterator, callback) {
  10320. arr = _map(arr, function (x, i) {
  10321. return {index: i, value: x};
  10322. });
  10323. if (!callback) {
  10324. eachfn(arr, function (x, callback) {
  10325. iterator(x.value, function (err) {
  10326. callback(err);
  10327. });
  10328. });
  10329. } else {
  10330. var results = [];
  10331. eachfn(arr, function (x, callback) {
  10332. iterator(x.value, function (err, v) {
  10333. results[x.index] = v;
  10334. callback(err);
  10335. });
  10336. }, function (err) {
  10337. callback(err, results);
  10338. });
  10339. }
  10340. };
  10341. async.map = doParallel(_asyncMap);
  10342. async.mapSeries = doSeries(_asyncMap);
  10343. async.mapLimit = function (arr, limit, iterator, callback) {
  10344. return _mapLimit(limit)(arr, iterator, callback);
  10345. };
  10346. var _mapLimit = function(limit) {
  10347. return doParallelLimit(limit, _asyncMap);
  10348. };
  10349. // reduce only has a series version, as doing reduce in parallel won't
  10350. // work in many situations.
  10351. async.reduce = function (arr, memo, iterator, callback) {
  10352. async.eachSeries(arr, function (x, callback) {
  10353. iterator(memo, x, function (err, v) {
  10354. memo = v;
  10355. callback(err);
  10356. });
  10357. }, function (err) {
  10358. callback(err, memo);
  10359. });
  10360. };
  10361. // inject alias
  10362. async.inject = async.reduce;
  10363. // foldl alias
  10364. async.foldl = async.reduce;
  10365. async.reduceRight = function (arr, memo, iterator, callback) {
  10366. var reversed = _map(arr, function (x) {
  10367. return x;
  10368. }).reverse();
  10369. async.reduce(reversed, memo, iterator, callback);
  10370. };
  10371. // foldr alias
  10372. async.foldr = async.reduceRight;
  10373. var _filter = function (eachfn, arr, iterator, callback) {
  10374. var results = [];
  10375. arr = _map(arr, function (x, i) {
  10376. return {index: i, value: x};
  10377. });
  10378. eachfn(arr, function (x, callback) {
  10379. iterator(x.value, function (v) {
  10380. if (v) {
  10381. results.push(x);
  10382. }
  10383. callback();
  10384. });
  10385. }, function (err) {
  10386. callback(_map(results.sort(function (a, b) {
  10387. return a.index - b.index;
  10388. }), function (x) {
  10389. return x.value;
  10390. }));
  10391. });
  10392. };
  10393. async.filter = doParallel(_filter);
  10394. async.filterSeries = doSeries(_filter);
  10395. // select alias
  10396. async.select = async.filter;
  10397. async.selectSeries = async.filterSeries;
  10398. var _reject = function (eachfn, arr, iterator, callback) {
  10399. var results = [];
  10400. arr = _map(arr, function (x, i) {
  10401. return {index: i, value: x};
  10402. });
  10403. eachfn(arr, function (x, callback) {
  10404. iterator(x.value, function (v) {
  10405. if (!v) {
  10406. results.push(x);
  10407. }
  10408. callback();
  10409. });
  10410. }, function (err) {
  10411. callback(_map(results.sort(function (a, b) {
  10412. return a.index - b.index;
  10413. }), function (x) {
  10414. return x.value;
  10415. }));
  10416. });
  10417. };
  10418. async.reject = doParallel(_reject);
  10419. async.rejectSeries = doSeries(_reject);
  10420. var _detect = function (eachfn, arr, iterator, main_callback) {
  10421. eachfn(arr, function (x, callback) {
  10422. iterator(x, function (result) {
  10423. if (result) {
  10424. main_callback(x);
  10425. main_callback = function () {};
  10426. }
  10427. else {
  10428. callback();
  10429. }
  10430. });
  10431. }, function (err) {
  10432. main_callback();
  10433. });
  10434. };
  10435. async.detect = doParallel(_detect);
  10436. async.detectSeries = doSeries(_detect);
  10437. async.some = function (arr, iterator, main_callback) {
  10438. async.each(arr, function (x, callback) {
  10439. iterator(x, function (v) {
  10440. if (v) {
  10441. main_callback(true);
  10442. main_callback = function () {};
  10443. }
  10444. callback();
  10445. });
  10446. }, function (err) {
  10447. main_callback(false);
  10448. });
  10449. };
  10450. // any alias
  10451. async.any = async.some;
  10452. async.every = function (arr, iterator, main_callback) {
  10453. async.each(arr, function (x, callback) {
  10454. iterator(x, function (v) {
  10455. if (!v) {
  10456. main_callback(false);
  10457. main_callback = function () {};
  10458. }
  10459. callback();
  10460. });
  10461. }, function (err) {
  10462. main_callback(true);
  10463. });
  10464. };
  10465. // all alias
  10466. async.all = async.every;
  10467. async.sortBy = function (arr, iterator, callback) {
  10468. async.map(arr, function (x, callback) {
  10469. iterator(x, function (err, criteria) {
  10470. if (err) {
  10471. callback(err);
  10472. }
  10473. else {
  10474. callback(null, {value: x, criteria: criteria});
  10475. }
  10476. });
  10477. }, function (err, results) {
  10478. if (err) {
  10479. return callback(err);
  10480. }
  10481. else {
  10482. var fn = function (left, right) {
  10483. var a = left.criteria, b = right.criteria;
  10484. return a < b ? -1 : a > b ? 1 : 0;
  10485. };
  10486. callback(null, _map(results.sort(fn), function (x) {
  10487. return x.value;
  10488. }));
  10489. }
  10490. });
  10491. };
  10492. async.auto = function (tasks, callback) {
  10493. callback = callback || function () {};
  10494. var keys = _keys(tasks);
  10495. var remainingTasks = keys.length
  10496. if (!remainingTasks) {
  10497. return callback();
  10498. }
  10499. var results = {};
  10500. var listeners = [];
  10501. var addListener = function (fn) {
  10502. listeners.unshift(fn);
  10503. };
  10504. var removeListener = function (fn) {
  10505. for (var i = 0; i < listeners.length; i += 1) {
  10506. if (listeners[i] === fn) {
  10507. listeners.splice(i, 1);
  10508. return;
  10509. }
  10510. }
  10511. };
  10512. var taskComplete = function () {
  10513. remainingTasks--
  10514. _each(listeners.slice(0), function (fn) {
  10515. fn();
  10516. });
  10517. };
  10518. addListener(function () {
  10519. if (!remainingTasks) {
  10520. var theCallback = callback;
  10521. // prevent final callback from calling itself if it errors
  10522. callback = function () {};
  10523. theCallback(null, results);
  10524. }
  10525. });
  10526. _each(keys, function (k) {
  10527. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  10528. var taskCallback = function (err) {
  10529. var args = Array.prototype.slice.call(arguments, 1);
  10530. if (args.length <= 1) {
  10531. args = args[0];
  10532. }
  10533. if (err) {
  10534. var safeResults = {};
  10535. _each(_keys(results), function(rkey) {
  10536. safeResults[rkey] = results[rkey];
  10537. });
  10538. safeResults[k] = args;
  10539. callback(err, safeResults);
  10540. // stop subsequent errors hitting callback multiple times
  10541. callback = function () {};
  10542. }
  10543. else {
  10544. results[k] = args;
  10545. async.setImmediate(taskComplete);
  10546. }
  10547. };
  10548. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  10549. var ready = function () {
  10550. return _reduce(requires, function (a, x) {
  10551. return (a && results.hasOwnProperty(x));
  10552. }, true) && !results.hasOwnProperty(k);
  10553. };
  10554. if (ready()) {
  10555. task[task.length - 1](taskCallback, results);
  10556. }
  10557. else {
  10558. var listener = function () {
  10559. if (ready()) {
  10560. removeListener(listener);
  10561. task[task.length - 1](taskCallback, results);
  10562. }
  10563. };
  10564. addListener(listener);
  10565. }
  10566. });
  10567. };
  10568. async.retry = function(times, task, callback) {
  10569. var DEFAULT_TIMES = 5;
  10570. var attempts = [];
  10571. // Use defaults if times not passed
  10572. if (typeof times === 'function') {
  10573. callback = task;
  10574. task = times;
  10575. times = DEFAULT_TIMES;
  10576. }
  10577. // Make sure times is a number
  10578. times = parseInt(times, 10) || DEFAULT_TIMES;
  10579. var wrappedTask = function(wrappedCallback, wrappedResults) {
  10580. var retryAttempt = function(task, finalAttempt) {
  10581. return function(seriesCallback) {
  10582. task(function(err, result){
  10583. seriesCallback(!err || finalAttempt, {err: err, result: result});
  10584. }, wrappedResults);
  10585. };
  10586. };
  10587. while (times) {
  10588. attempts.push(retryAttempt(task, !(times-=1)));
  10589. }
  10590. async.series(attempts, function(done, data){
  10591. data = data[data.length - 1];
  10592. (wrappedCallback || callback)(data.err, data.result);
  10593. });
  10594. }
  10595. // If a callback is passed, run this as a controll flow
  10596. return callback ? wrappedTask() : wrappedTask
  10597. };
  10598. async.waterfall = function (tasks, callback) {
  10599. callback = callback || function () {};
  10600. if (!_isArray(tasks)) {
  10601. var err = new Error('First argument to waterfall must be an array of functions');
  10602. return callback(err);
  10603. }
  10604. if (!tasks.length) {
  10605. return callback();
  10606. }
  10607. var wrapIterator = function (iterator) {
  10608. return function (err) {
  10609. if (err) {
  10610. callback.apply(null, arguments);
  10611. callback = function () {};
  10612. }
  10613. else {
  10614. var args = Array.prototype.slice.call(arguments, 1);
  10615. var next = iterator.next();
  10616. if (next) {
  10617. args.push(wrapIterator(next));
  10618. }
  10619. else {
  10620. args.push(callback);
  10621. }
  10622. async.setImmediate(function () {
  10623. iterator.apply(null, args);
  10624. });
  10625. }
  10626. };
  10627. };
  10628. wrapIterator(async.iterator(tasks))();
  10629. };
  10630. var _parallel = function(eachfn, tasks, callback) {
  10631. callback = callback || function () {};
  10632. if (_isArray(tasks)) {
  10633. eachfn.map(tasks, function (fn, callback) {
  10634. if (fn) {
  10635. fn(function (err) {
  10636. var args = Array.prototype.slice.call(arguments, 1);
  10637. if (args.length <= 1) {
  10638. args = args[0];
  10639. }
  10640. callback.call(null, err, args);
  10641. });
  10642. }
  10643. }, callback);
  10644. }
  10645. else {
  10646. var results = {};
  10647. eachfn.each(_keys(tasks), function (k, callback) {
  10648. tasks[k](function (err) {
  10649. var args = Array.prototype.slice.call(arguments, 1);
  10650. if (args.length <= 1) {
  10651. args = args[0];
  10652. }
  10653. results[k] = args;
  10654. callback(err);
  10655. });
  10656. }, function (err) {
  10657. callback(err, results);
  10658. });
  10659. }
  10660. };
  10661. async.parallel = function (tasks, callback) {
  10662. _parallel({ map: async.map, each: async.each }, tasks, callback);
  10663. };
  10664. async.parallelLimit = function(tasks, limit, callback) {
  10665. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  10666. };
  10667. async.series = function (tasks, callback) {
  10668. callback = callback || function () {};
  10669. if (_isArray(tasks)) {
  10670. async.mapSeries(tasks, function (fn, callback) {
  10671. if (fn) {
  10672. fn(function (err) {
  10673. var args = Array.prototype.slice.call(arguments, 1);
  10674. if (args.length <= 1) {
  10675. args = args[0];
  10676. }
  10677. callback.call(null, err, args);
  10678. });
  10679. }
  10680. }, callback);
  10681. }
  10682. else {
  10683. var results = {};
  10684. async.eachSeries(_keys(tasks), function (k, callback) {
  10685. tasks[k](function (err) {
  10686. var args = Array.prototype.slice.call(arguments, 1);
  10687. if (args.length <= 1) {
  10688. args = args[0];
  10689. }
  10690. results[k] = args;
  10691. callback(err);
  10692. });
  10693. }, function (err) {
  10694. callback(err, results);
  10695. });
  10696. }
  10697. };
  10698. async.iterator = function (tasks) {
  10699. var makeCallback = function (index) {
  10700. var fn = function () {
  10701. if (tasks.length) {
  10702. tasks[index].apply(null, arguments);
  10703. }
  10704. return fn.next();
  10705. };
  10706. fn.next = function () {
  10707. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  10708. };
  10709. return fn;
  10710. };
  10711. return makeCallback(0);
  10712. };
  10713. async.apply = function (fn) {
  10714. var args = Array.prototype.slice.call(arguments, 1);
  10715. return function () {
  10716. return fn.apply(
  10717. null, args.concat(Array.prototype.slice.call(arguments))
  10718. );
  10719. };
  10720. };
  10721. var _concat = function (eachfn, arr, fn, callback) {
  10722. var r = [];
  10723. eachfn(arr, function (x, cb) {
  10724. fn(x, function (err, y) {
  10725. r = r.concat(y || []);
  10726. cb(err);
  10727. });
  10728. }, function (err) {
  10729. callback(err, r);
  10730. });
  10731. };
  10732. async.concat = doParallel(_concat);
  10733. async.concatSeries = doSeries(_concat);
  10734. async.whilst = function (test, iterator, callback) {
  10735. if (test()) {
  10736. iterator(function (err) {
  10737. if (err) {
  10738. return callback(err);
  10739. }
  10740. async.whilst(test, iterator, callback);
  10741. });
  10742. }
  10743. else {
  10744. callback();
  10745. }
  10746. };
  10747. async.doWhilst = function (iterator, test, callback) {
  10748. iterator(function (err) {
  10749. if (err) {
  10750. return callback(err);
  10751. }
  10752. var args = Array.prototype.slice.call(arguments, 1);
  10753. if (test.apply(null, args)) {
  10754. async.doWhilst(iterator, test, callback);
  10755. }
  10756. else {
  10757. callback();
  10758. }
  10759. });
  10760. };
  10761. async.until = function (test, iterator, callback) {
  10762. if (!test()) {
  10763. iterator(function (err) {
  10764. if (err) {
  10765. return callback(err);
  10766. }
  10767. async.until(test, iterator, callback);
  10768. });
  10769. }
  10770. else {
  10771. callback();
  10772. }
  10773. };
  10774. async.doUntil = function (iterator, test, callback) {
  10775. iterator(function (err) {
  10776. if (err) {
  10777. return callback(err);
  10778. }
  10779. var args = Array.prototype.slice.call(arguments, 1);
  10780. if (!test.apply(null, args)) {
  10781. async.doUntil(iterator, test, callback);
  10782. }
  10783. else {
  10784. callback();
  10785. }
  10786. });
  10787. };
  10788. async.queue = function (worker, concurrency) {
  10789. if (concurrency === undefined) {
  10790. concurrency = 1;
  10791. }
  10792. function _insert(q, data, pos, callback) {
  10793. if (!q.started){
  10794. q.started = true;
  10795. }
  10796. if (!_isArray(data)) {
  10797. data = [data];
  10798. }
  10799. if(data.length == 0) {
  10800. // call drain immediately if there are no tasks
  10801. return async.setImmediate(function() {
  10802. if (q.drain) {
  10803. q.drain();
  10804. }
  10805. });
  10806. }
  10807. _each(data, function(task) {
  10808. var item = {
  10809. data: task,
  10810. callback: typeof callback === 'function' ? callback : null
  10811. };
  10812. if (pos) {
  10813. q.tasks.unshift(item);
  10814. } else {
  10815. q.tasks.push(item);
  10816. }
  10817. if (q.saturated && q.tasks.length === q.concurrency) {
  10818. q.saturated();
  10819. }
  10820. async.setImmediate(q.process);
  10821. });
  10822. }
  10823. var workers = 0;
  10824. var q = {
  10825. tasks: [],
  10826. concurrency: concurrency,
  10827. saturated: null,
  10828. empty: null,
  10829. drain: null,
  10830. started: false,
  10831. paused: false,
  10832. push: function (data, callback) {
  10833. _insert(q, data, false, callback);
  10834. },
  10835. kill: function () {
  10836. q.drain = null;
  10837. q.tasks = [];
  10838. },
  10839. unshift: function (data, callback) {
  10840. _insert(q, data, true, callback);
  10841. },
  10842. process: function () {
  10843. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  10844. var task = q.tasks.shift();
  10845. if (q.empty && q.tasks.length === 0) {
  10846. q.empty();
  10847. }
  10848. workers += 1;
  10849. var next = function () {
  10850. workers -= 1;
  10851. if (task.callback) {
  10852. task.callback.apply(task, arguments);
  10853. }
  10854. if (q.drain && q.tasks.length + workers === 0) {
  10855. q.drain();
  10856. }
  10857. q.process();
  10858. };
  10859. var cb = only_once(next);
  10860. worker(task.data, cb);
  10861. }
  10862. },
  10863. length: function () {
  10864. return q.tasks.length;
  10865. },
  10866. running: function () {
  10867. return workers;
  10868. },
  10869. idle: function() {
  10870. return q.tasks.length + workers === 0;
  10871. },
  10872. pause: function () {
  10873. if (q.paused === true) { return; }
  10874. q.paused = true;
  10875. q.process();
  10876. },
  10877. resume: function () {
  10878. if (q.paused === false) { return; }
  10879. q.paused = false;
  10880. q.process();
  10881. }
  10882. };
  10883. return q;
  10884. };
  10885. async.priorityQueue = function (worker, concurrency) {
  10886. function _compareTasks(a, b){
  10887. return a.priority - b.priority;
  10888. };
  10889. function _binarySearch(sequence, item, compare) {
  10890. var beg = -1,
  10891. end = sequence.length - 1;
  10892. while (beg < end) {
  10893. var mid = beg + ((end - beg + 1) >>> 1);
  10894. if (compare(item, sequence[mid]) >= 0) {
  10895. beg = mid;
  10896. } else {
  10897. end = mid - 1;
  10898. }
  10899. }
  10900. return beg;
  10901. }
  10902. function _insert(q, data, priority, callback) {
  10903. if (!q.started){
  10904. q.started = true;
  10905. }
  10906. if (!_isArray(data)) {
  10907. data = [data];
  10908. }
  10909. if(data.length == 0) {
  10910. // call drain immediately if there are no tasks
  10911. return async.setImmediate(function() {
  10912. if (q.drain) {
  10913. q.drain();
  10914. }
  10915. });
  10916. }
  10917. _each(data, function(task) {
  10918. var item = {
  10919. data: task,
  10920. priority: priority,
  10921. callback: typeof callback === 'function' ? callback : null
  10922. };
  10923. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  10924. if (q.saturated && q.tasks.length === q.concurrency) {
  10925. q.saturated();
  10926. }
  10927. async.setImmediate(q.process);
  10928. });
  10929. }
  10930. // Start with a normal queue
  10931. var q = async.queue(worker, concurrency);
  10932. // Override push to accept second parameter representing priority
  10933. q.push = function (data, priority, callback) {
  10934. _insert(q, data, priority, callback);
  10935. };
  10936. // Remove unshift function
  10937. delete q.unshift;
  10938. return q;
  10939. };
  10940. async.cargo = function (worker, payload) {
  10941. var working = false,
  10942. tasks = [];
  10943. var cargo = {
  10944. tasks: tasks,
  10945. payload: payload,
  10946. saturated: null,
  10947. empty: null,
  10948. drain: null,
  10949. drained: true,
  10950. push: function (data, callback) {
  10951. if (!_isArray(data)) {
  10952. data = [data];
  10953. }
  10954. _each(data, function(task) {
  10955. tasks.push({
  10956. data: task,
  10957. callback: typeof callback === 'function' ? callback : null
  10958. });
  10959. cargo.drained = false;
  10960. if (cargo.saturated && tasks.length === payload) {
  10961. cargo.saturated();
  10962. }
  10963. });
  10964. async.setImmediate(cargo.process);
  10965. },
  10966. process: function process() {
  10967. if (working) return;
  10968. if (tasks.length === 0) {
  10969. if(cargo.drain && !cargo.drained) cargo.drain();
  10970. cargo.drained = true;
  10971. return;
  10972. }
  10973. var ts = typeof payload === 'number'
  10974. ? tasks.splice(0, payload)
  10975. : tasks.splice(0, tasks.length);
  10976. var ds = _map(ts, function (task) {
  10977. return task.data;
  10978. });
  10979. if(cargo.empty) cargo.empty();
  10980. working = true;
  10981. worker(ds, function () {
  10982. working = false;
  10983. var args = arguments;
  10984. _each(ts, function (data) {
  10985. if (data.callback) {
  10986. data.callback.apply(null, args);
  10987. }
  10988. });
  10989. process();
  10990. });
  10991. },
  10992. length: function () {
  10993. return tasks.length;
  10994. },
  10995. running: function () {
  10996. return working;
  10997. }
  10998. };
  10999. return cargo;
  11000. };
  11001. var _console_fn = function (name) {
  11002. return function (fn) {
  11003. var args = Array.prototype.slice.call(arguments, 1);
  11004. fn.apply(null, args.concat([function (err) {
  11005. var args = Array.prototype.slice.call(arguments, 1);
  11006. if (typeof console !== 'undefined') {
  11007. if (err) {
  11008. if (console.error) {
  11009. console.error(err);
  11010. }
  11011. }
  11012. else if (console[name]) {
  11013. _each(args, function (x) {
  11014. console[name](x);
  11015. });
  11016. }
  11017. }
  11018. }]));
  11019. };
  11020. };
  11021. async.log = _console_fn('log');
  11022. async.dir = _console_fn('dir');
  11023. /*async.info = _console_fn('info');
  11024. async.warn = _console_fn('warn');
  11025. async.error = _console_fn('error');*/
  11026. async.memoize = function (fn, hasher) {
  11027. var memo = {};
  11028. var queues = {};
  11029. hasher = hasher || function (x) {
  11030. return x;
  11031. };
  11032. var memoized = function () {
  11033. var args = Array.prototype.slice.call(arguments);
  11034. var callback = args.pop();
  11035. var key = hasher.apply(null, args);
  11036. if (key in memo) {
  11037. async.nextTick(function () {
  11038. callback.apply(null, memo[key]);
  11039. });
  11040. }
  11041. else if (key in queues) {
  11042. queues[key].push(callback);
  11043. }
  11044. else {
  11045. queues[key] = [callback];
  11046. fn.apply(null, args.concat([function () {
  11047. memo[key] = arguments;
  11048. var q = queues[key];
  11049. delete queues[key];
  11050. for (var i = 0, l = q.length; i < l; i++) {
  11051. q[i].apply(null, arguments);
  11052. }
  11053. }]));
  11054. }
  11055. };
  11056. memoized.memo = memo;
  11057. memoized.unmemoized = fn;
  11058. return memoized;
  11059. };
  11060. async.unmemoize = function (fn) {
  11061. return function () {
  11062. return (fn.unmemoized || fn).apply(null, arguments);
  11063. };
  11064. };
  11065. async.times = function (count, iterator, callback) {
  11066. var counter = [];
  11067. for (var i = 0; i < count; i++) {
  11068. counter.push(i);
  11069. }
  11070. return async.map(counter, iterator, callback);
  11071. };
  11072. async.timesSeries = function (count, iterator, callback) {
  11073. var counter = [];
  11074. for (var i = 0; i < count; i++) {
  11075. counter.push(i);
  11076. }
  11077. return async.mapSeries(counter, iterator, callback);
  11078. };
  11079. async.seq = function (/* functions... */) {
  11080. var fns = arguments;
  11081. return function () {
  11082. var that = this;
  11083. var args = Array.prototype.slice.call(arguments);
  11084. var callback = args.pop();
  11085. async.reduce(fns, args, function (newargs, fn, cb) {
  11086. fn.apply(that, newargs.concat([function () {
  11087. var err = arguments[0];
  11088. var nextargs = Array.prototype.slice.call(arguments, 1);
  11089. cb(err, nextargs);
  11090. }]))
  11091. },
  11092. function (err, results) {
  11093. callback.apply(that, [err].concat(results));
  11094. });
  11095. };
  11096. };
  11097. async.compose = function (/* functions... */) {
  11098. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  11099. };
  11100. var _applyEach = function (eachfn, fns /*args...*/) {
  11101. var go = function () {
  11102. var that = this;
  11103. var args = Array.prototype.slice.call(arguments);
  11104. var callback = args.pop();
  11105. return eachfn(fns, function (fn, cb) {
  11106. fn.apply(that, args.concat([cb]));
  11107. },
  11108. callback);
  11109. };
  11110. if (arguments.length > 2) {
  11111. var args = Array.prototype.slice.call(arguments, 2);
  11112. return go.apply(this, args);
  11113. }
  11114. else {
  11115. return go;
  11116. }
  11117. };
  11118. async.applyEach = doParallel(_applyEach);
  11119. async.applyEachSeries = doSeries(_applyEach);
  11120. async.forever = function (fn, callback) {
  11121. function next(err) {
  11122. if (err) {
  11123. if (callback) {
  11124. return callback(err);
  11125. }
  11126. throw err;
  11127. }
  11128. fn(next);
  11129. }
  11130. next();
  11131. };
  11132. // Node.js
  11133. if (typeof module !== 'undefined' && module.exports) {
  11134. module.exports = async;
  11135. }
  11136. // AMD / RequireJS
  11137. else if (typeof define !== 'undefined' && define.amd) {
  11138. define([], function () {
  11139. return async;
  11140. });
  11141. }
  11142. // included directly via <script> tag
  11143. else {
  11144. root.async = async;
  11145. }
  11146. }());
  11147. }).call(this,require('_process'))
  11148. },{"_process":42}],41:[function(require,module,exports){
  11149. // Copyright Joyent, Inc. and other Node contributors.
  11150. //
  11151. // Permission is hereby granted, free of charge, to any person obtaining a
  11152. // copy of this software and associated documentation files (the
  11153. // "Software"), to deal in the Software without restriction, including
  11154. // without limitation the rights to use, copy, modify, merge, publish,
  11155. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11156. // persons to whom the Software is furnished to do so, subject to the
  11157. // following conditions:
  11158. //
  11159. // The above copyright notice and this permission notice shall be included
  11160. // in all copies or substantial portions of the Software.
  11161. //
  11162. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11163. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11164. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11165. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11166. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11167. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11168. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11169. function EventEmitter() {
  11170. this._events = this._events || {};
  11171. this._maxListeners = this._maxListeners || undefined;
  11172. }
  11173. module.exports = EventEmitter;
  11174. // Backwards-compat with node 0.10.x
  11175. EventEmitter.EventEmitter = EventEmitter;
  11176. EventEmitter.prototype._events = undefined;
  11177. EventEmitter.prototype._maxListeners = undefined;
  11178. // By default EventEmitters will print a warning if more than 10 listeners are
  11179. // added to it. This is a useful default which helps finding memory leaks.
  11180. EventEmitter.defaultMaxListeners = 10;
  11181. // Obviously not all Emitters should be limited to 10. This function allows
  11182. // that to be increased. Set to zero for unlimited.
  11183. EventEmitter.prototype.setMaxListeners = function(n) {
  11184. if (!isNumber(n) || n < 0 || isNaN(n))
  11185. throw TypeError('n must be a positive number');
  11186. this._maxListeners = n;
  11187. return this;
  11188. };
  11189. EventEmitter.prototype.emit = function(type) {
  11190. var er, handler, len, args, i, listeners;
  11191. if (!this._events)
  11192. this._events = {};
  11193. // If there is no 'error' event listener then throw.
  11194. if (type === 'error') {
  11195. if (!this._events.error ||
  11196. (isObject(this._events.error) && !this._events.error.length)) {
  11197. er = arguments[1];
  11198. if (er instanceof Error) {
  11199. throw er; // Unhandled 'error' event
  11200. }
  11201. throw TypeError('Uncaught, unspecified "error" event.');
  11202. }
  11203. }
  11204. handler = this._events[type];
  11205. if (isUndefined(handler))
  11206. return false;
  11207. if (isFunction(handler)) {
  11208. switch (arguments.length) {
  11209. // fast cases
  11210. case 1:
  11211. handler.call(this);
  11212. break;
  11213. case 2:
  11214. handler.call(this, arguments[1]);
  11215. break;
  11216. case 3:
  11217. handler.call(this, arguments[1], arguments[2]);
  11218. break;
  11219. // slower
  11220. default:
  11221. len = arguments.length;
  11222. args = new Array(len - 1);
  11223. for (i = 1; i < len; i++)
  11224. args[i - 1] = arguments[i];
  11225. handler.apply(this, args);
  11226. }
  11227. } else if (isObject(handler)) {
  11228. len = arguments.length;
  11229. args = new Array(len - 1);
  11230. for (i = 1; i < len; i++)
  11231. args[i - 1] = arguments[i];
  11232. listeners = handler.slice();
  11233. len = listeners.length;
  11234. for (i = 0; i < len; i++)
  11235. listeners[i].apply(this, args);
  11236. }
  11237. return true;
  11238. };
  11239. EventEmitter.prototype.addListener = function(type, listener) {
  11240. var m;
  11241. if (!isFunction(listener))
  11242. throw TypeError('listener must be a function');
  11243. if (!this._events)
  11244. this._events = {};
  11245. // To avoid recursion in the case that type === "newListener"! Before
  11246. // adding it to the listeners, first emit "newListener".
  11247. if (this._events.newListener)
  11248. this.emit('newListener', type,
  11249. isFunction(listener.listener) ?
  11250. listener.listener : listener);
  11251. if (!this._events[type])
  11252. // Optimize the case of one listener. Don't need the extra array object.
  11253. this._events[type] = listener;
  11254. else if (isObject(this._events[type]))
  11255. // If we've already got an array, just append.
  11256. this._events[type].push(listener);
  11257. else
  11258. // Adding the second element, need to change to array.
  11259. this._events[type] = [this._events[type], listener];
  11260. // Check for listener leak
  11261. if (isObject(this._events[type]) && !this._events[type].warned) {
  11262. var m;
  11263. if (!isUndefined(this._maxListeners)) {
  11264. m = this._maxListeners;
  11265. } else {
  11266. m = EventEmitter.defaultMaxListeners;
  11267. }
  11268. if (m && m > 0 && this._events[type].length > m) {
  11269. this._events[type].warned = true;
  11270. console.error('(node) warning: possible EventEmitter memory ' +
  11271. 'leak detected. %d listeners added. ' +
  11272. 'Use emitter.setMaxListeners() to increase limit.',
  11273. this._events[type].length);
  11274. if (typeof console.trace === 'function') {
  11275. // not supported in IE 10
  11276. console.trace();
  11277. }
  11278. }
  11279. }
  11280. return this;
  11281. };
  11282. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  11283. EventEmitter.prototype.once = function(type, listener) {
  11284. if (!isFunction(listener))
  11285. throw TypeError('listener must be a function');
  11286. var fired = false;
  11287. function g() {
  11288. this.removeListener(type, g);
  11289. if (!fired) {
  11290. fired = true;
  11291. listener.apply(this, arguments);
  11292. }
  11293. }
  11294. g.listener = listener;
  11295. this.on(type, g);
  11296. return this;
  11297. };
  11298. // emits a 'removeListener' event iff the listener was removed
  11299. EventEmitter.prototype.removeListener = function(type, listener) {
  11300. var list, position, length, i;
  11301. if (!isFunction(listener))
  11302. throw TypeError('listener must be a function');
  11303. if (!this._events || !this._events[type])
  11304. return this;
  11305. list = this._events[type];
  11306. length = list.length;
  11307. position = -1;
  11308. if (list === listener ||
  11309. (isFunction(list.listener) && list.listener === listener)) {
  11310. delete this._events[type];
  11311. if (this._events.removeListener)
  11312. this.emit('removeListener', type, listener);
  11313. } else if (isObject(list)) {
  11314. for (i = length; i-- > 0;) {
  11315. if (list[i] === listener ||
  11316. (list[i].listener && list[i].listener === listener)) {
  11317. position = i;
  11318. break;
  11319. }
  11320. }
  11321. if (position < 0)
  11322. return this;
  11323. if (list.length === 1) {
  11324. list.length = 0;
  11325. delete this._events[type];
  11326. } else {
  11327. list.splice(position, 1);
  11328. }
  11329. if (this._events.removeListener)
  11330. this.emit('removeListener', type, listener);
  11331. }
  11332. return this;
  11333. };
  11334. EventEmitter.prototype.removeAllListeners = function(type) {
  11335. var key, listeners;
  11336. if (!this._events)
  11337. return this;
  11338. // not listening for removeListener, no need to emit
  11339. if (!this._events.removeListener) {
  11340. if (arguments.length === 0)
  11341. this._events = {};
  11342. else if (this._events[type])
  11343. delete this._events[type];
  11344. return this;
  11345. }
  11346. // emit removeListener for all listeners on all events
  11347. if (arguments.length === 0) {
  11348. for (key in this._events) {
  11349. if (key === 'removeListener') continue;
  11350. this.removeAllListeners(key);
  11351. }
  11352. this.removeAllListeners('removeListener');
  11353. this._events = {};
  11354. return this;
  11355. }
  11356. listeners = this._events[type];
  11357. if (isFunction(listeners)) {
  11358. this.removeListener(type, listeners);
  11359. } else {
  11360. // LIFO order
  11361. while (listeners.length)
  11362. this.removeListener(type, listeners[listeners.length - 1]);
  11363. }
  11364. delete this._events[type];
  11365. return this;
  11366. };
  11367. EventEmitter.prototype.listeners = function(type) {
  11368. var ret;
  11369. if (!this._events || !this._events[type])
  11370. ret = [];
  11371. else if (isFunction(this._events[type]))
  11372. ret = [this._events[type]];
  11373. else
  11374. ret = this._events[type].slice();
  11375. return ret;
  11376. };
  11377. EventEmitter.listenerCount = function(emitter, type) {
  11378. var ret;
  11379. if (!emitter._events || !emitter._events[type])
  11380. ret = 0;
  11381. else if (isFunction(emitter._events[type]))
  11382. ret = 1;
  11383. else
  11384. ret = emitter._events[type].length;
  11385. return ret;
  11386. };
  11387. function isFunction(arg) {
  11388. return typeof arg === 'function';
  11389. }
  11390. function isNumber(arg) {
  11391. return typeof arg === 'number';
  11392. }
  11393. function isObject(arg) {
  11394. return typeof arg === 'object' && arg !== null;
  11395. }
  11396. function isUndefined(arg) {
  11397. return arg === void 0;
  11398. }
  11399. },{}],42:[function(require,module,exports){
  11400. // shim for using process in browser
  11401. var process = module.exports = {};
  11402. var queue = [];
  11403. var draining = false;
  11404. var currentQueue;
  11405. var queueIndex = -1;
  11406. function cleanUpNextTick() {
  11407. draining = false;
  11408. if (currentQueue.length) {
  11409. queue = currentQueue.concat(queue);
  11410. } else {
  11411. queueIndex = -1;
  11412. }
  11413. if (queue.length) {
  11414. drainQueue();
  11415. }
  11416. }
  11417. function drainQueue() {
  11418. if (draining) {
  11419. return;
  11420. }
  11421. var timeout = setTimeout(cleanUpNextTick);
  11422. draining = true;
  11423. var len = queue.length;
  11424. while(len) {
  11425. currentQueue = queue;
  11426. queue = [];
  11427. while (++queueIndex < len) {
  11428. if (currentQueue) {
  11429. currentQueue[queueIndex].run();
  11430. }
  11431. }
  11432. queueIndex = -1;
  11433. len = queue.length;
  11434. }
  11435. currentQueue = null;
  11436. draining = false;
  11437. clearTimeout(timeout);
  11438. }
  11439. process.nextTick = function (fun) {
  11440. var args = new Array(arguments.length - 1);
  11441. if (arguments.length > 1) {
  11442. for (var i = 1; i < arguments.length; i++) {
  11443. args[i - 1] = arguments[i];
  11444. }
  11445. }
  11446. queue.push(new Item(fun, args));
  11447. if (queue.length === 1 && !draining) {
  11448. setTimeout(drainQueue, 0);
  11449. }
  11450. };
  11451. // v8 likes predictible objects
  11452. function Item(fun, array) {
  11453. this.fun = fun;
  11454. this.array = array;
  11455. }
  11456. Item.prototype.run = function () {
  11457. this.fun.apply(null, this.array);
  11458. };
  11459. process.title = 'browser';
  11460. process.browser = true;
  11461. process.env = {};
  11462. process.argv = [];
  11463. process.version = ''; // empty string to avoid regexp issues
  11464. process.versions = {};
  11465. function noop() {}
  11466. process.on = noop;
  11467. process.addListener = noop;
  11468. process.once = noop;
  11469. process.off = noop;
  11470. process.removeListener = noop;
  11471. process.removeAllListeners = noop;
  11472. process.emit = noop;
  11473. process.binding = function (name) {
  11474. throw new Error('process.binding is not supported');
  11475. };
  11476. process.cwd = function () { return '/' };
  11477. process.chdir = function (dir) {
  11478. throw new Error('process.chdir is not supported');
  11479. };
  11480. process.umask = function() { return 0; };
  11481. },{}],43:[function(require,module,exports){
  11482. (function (process,global){
  11483. /*!
  11484. * @overview es6-promise - a tiny implementation of Promises/A+.
  11485. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  11486. * @license Licensed under MIT license
  11487. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  11488. * @version 3.0.2
  11489. */
  11490. (function() {
  11491. "use strict";
  11492. function lib$es6$promise$utils$$objectOrFunction(x) {
  11493. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  11494. }
  11495. function lib$es6$promise$utils$$isFunction(x) {
  11496. return typeof x === 'function';
  11497. }
  11498. function lib$es6$promise$utils$$isMaybeThenable(x) {
  11499. return typeof x === 'object' && x !== null;
  11500. }
  11501. var lib$es6$promise$utils$$_isArray;
  11502. if (!Array.isArray) {
  11503. lib$es6$promise$utils$$_isArray = function (x) {
  11504. return Object.prototype.toString.call(x) === '[object Array]';
  11505. };
  11506. } else {
  11507. lib$es6$promise$utils$$_isArray = Array.isArray;
  11508. }
  11509. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  11510. var lib$es6$promise$asap$$len = 0;
  11511. var lib$es6$promise$asap$$toString = {}.toString;
  11512. var lib$es6$promise$asap$$vertxNext;
  11513. var lib$es6$promise$asap$$customSchedulerFn;
  11514. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  11515. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  11516. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  11517. lib$es6$promise$asap$$len += 2;
  11518. if (lib$es6$promise$asap$$len === 2) {
  11519. // If len is 2, that means that we need to schedule an async flush.
  11520. // If additional callbacks are queued before the queue is flushed, they
  11521. // will be processed by this flush that we are scheduling.
  11522. if (lib$es6$promise$asap$$customSchedulerFn) {
  11523. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  11524. } else {
  11525. lib$es6$promise$asap$$scheduleFlush();
  11526. }
  11527. }
  11528. }
  11529. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  11530. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  11531. }
  11532. function lib$es6$promise$asap$$setAsap(asapFn) {
  11533. lib$es6$promise$asap$$asap = asapFn;
  11534. }
  11535. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  11536. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  11537. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  11538. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  11539. // test for web worker but not in IE10
  11540. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  11541. typeof importScripts !== 'undefined' &&
  11542. typeof MessageChannel !== 'undefined';
  11543. // node
  11544. function lib$es6$promise$asap$$useNextTick() {
  11545. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  11546. // see https://github.com/cujojs/when/issues/410 for details
  11547. return function() {
  11548. process.nextTick(lib$es6$promise$asap$$flush);
  11549. };
  11550. }
  11551. // vertx
  11552. function lib$es6$promise$asap$$useVertxTimer() {
  11553. return function() {
  11554. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  11555. };
  11556. }
  11557. function lib$es6$promise$asap$$useMutationObserver() {
  11558. var iterations = 0;
  11559. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  11560. var node = document.createTextNode('');
  11561. observer.observe(node, { characterData: true });
  11562. return function() {
  11563. node.data = (iterations = ++iterations % 2);
  11564. };
  11565. }
  11566. // web worker
  11567. function lib$es6$promise$asap$$useMessageChannel() {
  11568. var channel = new MessageChannel();
  11569. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  11570. return function () {
  11571. channel.port2.postMessage(0);
  11572. };
  11573. }
  11574. function lib$es6$promise$asap$$useSetTimeout() {
  11575. return function() {
  11576. setTimeout(lib$es6$promise$asap$$flush, 1);
  11577. };
  11578. }
  11579. var lib$es6$promise$asap$$queue = new Array(1000);
  11580. function lib$es6$promise$asap$$flush() {
  11581. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  11582. var callback = lib$es6$promise$asap$$queue[i];
  11583. var arg = lib$es6$promise$asap$$queue[i+1];
  11584. callback(arg);
  11585. lib$es6$promise$asap$$queue[i] = undefined;
  11586. lib$es6$promise$asap$$queue[i+1] = undefined;
  11587. }
  11588. lib$es6$promise$asap$$len = 0;
  11589. }
  11590. function lib$es6$promise$asap$$attemptVertx() {
  11591. try {
  11592. var r = require;
  11593. var vertx = r('vertx');
  11594. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  11595. return lib$es6$promise$asap$$useVertxTimer();
  11596. } catch(e) {
  11597. return lib$es6$promise$asap$$useSetTimeout();
  11598. }
  11599. }
  11600. var lib$es6$promise$asap$$scheduleFlush;
  11601. // Decide what async method to use to triggering processing of queued callbacks:
  11602. if (lib$es6$promise$asap$$isNode) {
  11603. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  11604. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  11605. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  11606. } else if (lib$es6$promise$asap$$isWorker) {
  11607. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  11608. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  11609. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  11610. } else {
  11611. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  11612. }
  11613. function lib$es6$promise$$internal$$noop() {}
  11614. var lib$es6$promise$$internal$$PENDING = void 0;
  11615. var lib$es6$promise$$internal$$FULFILLED = 1;
  11616. var lib$es6$promise$$internal$$REJECTED = 2;
  11617. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11618. function lib$es6$promise$$internal$$selfFulfillment() {
  11619. return new TypeError("You cannot resolve a promise with itself");
  11620. }
  11621. function lib$es6$promise$$internal$$cannotReturnOwn() {
  11622. return new TypeError('A promises callback cannot return that same promise.');
  11623. }
  11624. function lib$es6$promise$$internal$$getThen(promise) {
  11625. try {
  11626. return promise.then;
  11627. } catch(error) {
  11628. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  11629. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  11630. }
  11631. }
  11632. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  11633. try {
  11634. then.call(value, fulfillmentHandler, rejectionHandler);
  11635. } catch(e) {
  11636. return e;
  11637. }
  11638. }
  11639. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  11640. lib$es6$promise$asap$$asap(function(promise) {
  11641. var sealed = false;
  11642. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  11643. if (sealed) { return; }
  11644. sealed = true;
  11645. if (thenable !== value) {
  11646. lib$es6$promise$$internal$$resolve(promise, value);
  11647. } else {
  11648. lib$es6$promise$$internal$$fulfill(promise, value);
  11649. }
  11650. }, function(reason) {
  11651. if (sealed) { return; }
  11652. sealed = true;
  11653. lib$es6$promise$$internal$$reject(promise, reason);
  11654. }, 'Settle: ' + (promise._label || ' unknown promise'));
  11655. if (!sealed && error) {
  11656. sealed = true;
  11657. lib$es6$promise$$internal$$reject(promise, error);
  11658. }
  11659. }, promise);
  11660. }
  11661. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  11662. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  11663. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  11664. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  11665. lib$es6$promise$$internal$$reject(promise, thenable._result);
  11666. } else {
  11667. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  11668. lib$es6$promise$$internal$$resolve(promise, value);
  11669. }, function(reason) {
  11670. lib$es6$promise$$internal$$reject(promise, reason);
  11671. });
  11672. }
  11673. }
  11674. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  11675. if (maybeThenable.constructor === promise.constructor) {
  11676. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  11677. } else {
  11678. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  11679. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  11680. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  11681. } else if (then === undefined) {
  11682. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11683. } else if (lib$es6$promise$utils$$isFunction(then)) {
  11684. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  11685. } else {
  11686. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  11687. }
  11688. }
  11689. }
  11690. function lib$es6$promise$$internal$$resolve(promise, value) {
  11691. if (promise === value) {
  11692. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  11693. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  11694. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  11695. } else {
  11696. lib$es6$promise$$internal$$fulfill(promise, value);
  11697. }
  11698. }
  11699. function lib$es6$promise$$internal$$publishRejection(promise) {
  11700. if (promise._onerror) {
  11701. promise._onerror(promise._result);
  11702. }
  11703. lib$es6$promise$$internal$$publish(promise);
  11704. }
  11705. function lib$es6$promise$$internal$$fulfill(promise, value) {
  11706. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11707. promise._result = value;
  11708. promise._state = lib$es6$promise$$internal$$FULFILLED;
  11709. if (promise._subscribers.length !== 0) {
  11710. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  11711. }
  11712. }
  11713. function lib$es6$promise$$internal$$reject(promise, reason) {
  11714. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  11715. promise._state = lib$es6$promise$$internal$$REJECTED;
  11716. promise._result = reason;
  11717. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  11718. }
  11719. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  11720. var subscribers = parent._subscribers;
  11721. var length = subscribers.length;
  11722. parent._onerror = null;
  11723. subscribers[length] = child;
  11724. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  11725. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  11726. if (length === 0 && parent._state) {
  11727. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  11728. }
  11729. }
  11730. function lib$es6$promise$$internal$$publish(promise) {
  11731. var subscribers = promise._subscribers;
  11732. var settled = promise._state;
  11733. if (subscribers.length === 0) { return; }
  11734. var child, callback, detail = promise._result;
  11735. for (var i = 0; i < subscribers.length; i += 3) {
  11736. child = subscribers[i];
  11737. callback = subscribers[i + settled];
  11738. if (child) {
  11739. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  11740. } else {
  11741. callback(detail);
  11742. }
  11743. }
  11744. promise._subscribers.length = 0;
  11745. }
  11746. function lib$es6$promise$$internal$$ErrorObject() {
  11747. this.error = null;
  11748. }
  11749. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  11750. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  11751. try {
  11752. return callback(detail);
  11753. } catch(e) {
  11754. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  11755. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  11756. }
  11757. }
  11758. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  11759. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  11760. value, error, succeeded, failed;
  11761. if (hasCallback) {
  11762. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  11763. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  11764. failed = true;
  11765. error = value.error;
  11766. value = null;
  11767. } else {
  11768. succeeded = true;
  11769. }
  11770. if (promise === value) {
  11771. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  11772. return;
  11773. }
  11774. } else {
  11775. value = detail;
  11776. succeeded = true;
  11777. }
  11778. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  11779. // noop
  11780. } else if (hasCallback && succeeded) {
  11781. lib$es6$promise$$internal$$resolve(promise, value);
  11782. } else if (failed) {
  11783. lib$es6$promise$$internal$$reject(promise, error);
  11784. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  11785. lib$es6$promise$$internal$$fulfill(promise, value);
  11786. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  11787. lib$es6$promise$$internal$$reject(promise, value);
  11788. }
  11789. }
  11790. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  11791. try {
  11792. resolver(function resolvePromise(value){
  11793. lib$es6$promise$$internal$$resolve(promise, value);
  11794. }, function rejectPromise(reason) {
  11795. lib$es6$promise$$internal$$reject(promise, reason);
  11796. });
  11797. } catch(e) {
  11798. lib$es6$promise$$internal$$reject(promise, e);
  11799. }
  11800. }
  11801. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  11802. var enumerator = this;
  11803. enumerator._instanceConstructor = Constructor;
  11804. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  11805. if (enumerator._validateInput(input)) {
  11806. enumerator._input = input;
  11807. enumerator.length = input.length;
  11808. enumerator._remaining = input.length;
  11809. enumerator._init();
  11810. if (enumerator.length === 0) {
  11811. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11812. } else {
  11813. enumerator.length = enumerator.length || 0;
  11814. enumerator._enumerate();
  11815. if (enumerator._remaining === 0) {
  11816. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  11817. }
  11818. }
  11819. } else {
  11820. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  11821. }
  11822. }
  11823. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  11824. return lib$es6$promise$utils$$isArray(input);
  11825. };
  11826. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  11827. return new Error('Array Methods must be provided an Array');
  11828. };
  11829. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  11830. this._result = new Array(this.length);
  11831. };
  11832. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  11833. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  11834. var enumerator = this;
  11835. var length = enumerator.length;
  11836. var promise = enumerator.promise;
  11837. var input = enumerator._input;
  11838. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11839. enumerator._eachEntry(input[i], i);
  11840. }
  11841. };
  11842. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  11843. var enumerator = this;
  11844. var c = enumerator._instanceConstructor;
  11845. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  11846. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  11847. entry._onerror = null;
  11848. enumerator._settledAt(entry._state, i, entry._result);
  11849. } else {
  11850. enumerator._willSettleAt(c.resolve(entry), i);
  11851. }
  11852. } else {
  11853. enumerator._remaining--;
  11854. enumerator._result[i] = entry;
  11855. }
  11856. };
  11857. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  11858. var enumerator = this;
  11859. var promise = enumerator.promise;
  11860. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  11861. enumerator._remaining--;
  11862. if (state === lib$es6$promise$$internal$$REJECTED) {
  11863. lib$es6$promise$$internal$$reject(promise, value);
  11864. } else {
  11865. enumerator._result[i] = value;
  11866. }
  11867. }
  11868. if (enumerator._remaining === 0) {
  11869. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  11870. }
  11871. };
  11872. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  11873. var enumerator = this;
  11874. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  11875. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  11876. }, function(reason) {
  11877. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  11878. });
  11879. };
  11880. function lib$es6$promise$promise$all$$all(entries) {
  11881. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  11882. }
  11883. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  11884. function lib$es6$promise$promise$race$$race(entries) {
  11885. /*jshint validthis:true */
  11886. var Constructor = this;
  11887. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11888. if (!lib$es6$promise$utils$$isArray(entries)) {
  11889. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  11890. return promise;
  11891. }
  11892. var length = entries.length;
  11893. function onFulfillment(value) {
  11894. lib$es6$promise$$internal$$resolve(promise, value);
  11895. }
  11896. function onRejection(reason) {
  11897. lib$es6$promise$$internal$$reject(promise, reason);
  11898. }
  11899. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  11900. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  11901. }
  11902. return promise;
  11903. }
  11904. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  11905. function lib$es6$promise$promise$resolve$$resolve(object) {
  11906. /*jshint validthis:true */
  11907. var Constructor = this;
  11908. if (object && typeof object === 'object' && object.constructor === Constructor) {
  11909. return object;
  11910. }
  11911. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11912. lib$es6$promise$$internal$$resolve(promise, object);
  11913. return promise;
  11914. }
  11915. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  11916. function lib$es6$promise$promise$reject$$reject(reason) {
  11917. /*jshint validthis:true */
  11918. var Constructor = this;
  11919. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  11920. lib$es6$promise$$internal$$reject(promise, reason);
  11921. return promise;
  11922. }
  11923. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  11924. var lib$es6$promise$promise$$counter = 0;
  11925. function lib$es6$promise$promise$$needsResolver() {
  11926. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  11927. }
  11928. function lib$es6$promise$promise$$needsNew() {
  11929. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  11930. }
  11931. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  11932. /**
  11933. Promise objects represent the eventual result of an asynchronous operation. The
  11934. primary way of interacting with a promise is through its `then` method, which
  11935. registers callbacks to receive either a promise's eventual value or the reason
  11936. why the promise cannot be fulfilled.
  11937. Terminology
  11938. -----------
  11939. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  11940. - `thenable` is an object or function that defines a `then` method.
  11941. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  11942. - `exception` is a value that is thrown using the throw statement.
  11943. - `reason` is a value that indicates why a promise was rejected.
  11944. - `settled` the final resting state of a promise, fulfilled or rejected.
  11945. A promise can be in one of three states: pending, fulfilled, or rejected.
  11946. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  11947. state. Promises that are rejected have a rejection reason and are in the
  11948. rejected state. A fulfillment value is never a thenable.
  11949. Promises can also be said to *resolve* a value. If this value is also a
  11950. promise, then the original promise's settled state will match the value's
  11951. settled state. So a promise that *resolves* a promise that rejects will
  11952. itself reject, and a promise that *resolves* a promise that fulfills will
  11953. itself fulfill.
  11954. Basic Usage:
  11955. ------------
  11956. ```js
  11957. var promise = new Promise(function(resolve, reject) {
  11958. // on success
  11959. resolve(value);
  11960. // on failure
  11961. reject(reason);
  11962. });
  11963. promise.then(function(value) {
  11964. // on fulfillment
  11965. }, function(reason) {
  11966. // on rejection
  11967. });
  11968. ```
  11969. Advanced Usage:
  11970. ---------------
  11971. Promises shine when abstracting away asynchronous interactions such as
  11972. `XMLHttpRequest`s.
  11973. ```js
  11974. function getJSON(url) {
  11975. return new Promise(function(resolve, reject){
  11976. var xhr = new XMLHttpRequest();
  11977. xhr.open('GET', url);
  11978. xhr.onreadystatechange = handler;
  11979. xhr.responseType = 'json';
  11980. xhr.setRequestHeader('Accept', 'application/json');
  11981. xhr.send();
  11982. function handler() {
  11983. if (this.readyState === this.DONE) {
  11984. if (this.status === 200) {
  11985. resolve(this.response);
  11986. } else {
  11987. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  11988. }
  11989. }
  11990. };
  11991. });
  11992. }
  11993. getJSON('/posts.json').then(function(json) {
  11994. // on fulfillment
  11995. }, function(reason) {
  11996. // on rejection
  11997. });
  11998. ```
  11999. Unlike callbacks, promises are great composable primitives.
  12000. ```js
  12001. Promise.all([
  12002. getJSON('/posts'),
  12003. getJSON('/comments')
  12004. ]).then(function(values){
  12005. values[0] // => postsJSON
  12006. values[1] // => commentsJSON
  12007. return values;
  12008. });
  12009. ```
  12010. @class Promise
  12011. @param {function} resolver
  12012. Useful for tooling.
  12013. @constructor
  12014. */
  12015. function lib$es6$promise$promise$$Promise(resolver) {
  12016. this._id = lib$es6$promise$promise$$counter++;
  12017. this._state = undefined;
  12018. this._result = undefined;
  12019. this._subscribers = [];
  12020. if (lib$es6$promise$$internal$$noop !== resolver) {
  12021. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  12022. lib$es6$promise$promise$$needsResolver();
  12023. }
  12024. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  12025. lib$es6$promise$promise$$needsNew();
  12026. }
  12027. lib$es6$promise$$internal$$initializePromise(this, resolver);
  12028. }
  12029. }
  12030. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  12031. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  12032. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  12033. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  12034. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  12035. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  12036. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  12037. lib$es6$promise$promise$$Promise.prototype = {
  12038. constructor: lib$es6$promise$promise$$Promise,
  12039. /**
  12040. The primary way of interacting with a promise is through its `then` method,
  12041. which registers callbacks to receive either a promise's eventual value or the
  12042. reason why the promise cannot be fulfilled.
  12043. ```js
  12044. findUser().then(function(user){
  12045. // user is available
  12046. }, function(reason){
  12047. // user is unavailable, and you are given the reason why
  12048. });
  12049. ```
  12050. Chaining
  12051. --------
  12052. The return value of `then` is itself a promise. This second, 'downstream'
  12053. promise is resolved with the return value of the first promise's fulfillment
  12054. or rejection handler, or rejected if the handler throws an exception.
  12055. ```js
  12056. findUser().then(function (user) {
  12057. return user.name;
  12058. }, function (reason) {
  12059. return 'default name';
  12060. }).then(function (userName) {
  12061. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  12062. // will be `'default name'`
  12063. });
  12064. findUser().then(function (user) {
  12065. throw new Error('Found user, but still unhappy');
  12066. }, function (reason) {
  12067. throw new Error('`findUser` rejected and we're unhappy');
  12068. }).then(function (value) {
  12069. // never reached
  12070. }, function (reason) {
  12071. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  12072. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  12073. });
  12074. ```
  12075. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  12076. ```js
  12077. findUser().then(function (user) {
  12078. throw new PedagogicalException('Upstream error');
  12079. }).then(function (value) {
  12080. // never reached
  12081. }).then(function (value) {
  12082. // never reached
  12083. }, function (reason) {
  12084. // The `PedgagocialException` is propagated all the way down to here
  12085. });
  12086. ```
  12087. Assimilation
  12088. ------------
  12089. Sometimes the value you want to propagate to a downstream promise can only be
  12090. retrieved asynchronously. This can be achieved by returning a promise in the
  12091. fulfillment or rejection handler. The downstream promise will then be pending
  12092. until the returned promise is settled. This is called *assimilation*.
  12093. ```js
  12094. findUser().then(function (user) {
  12095. return findCommentsByAuthor(user);
  12096. }).then(function (comments) {
  12097. // The user's comments are now available
  12098. });
  12099. ```
  12100. If the assimliated promise rejects, then the downstream promise will also reject.
  12101. ```js
  12102. findUser().then(function (user) {
  12103. return findCommentsByAuthor(user);
  12104. }).then(function (comments) {
  12105. // If `findCommentsByAuthor` fulfills, we'll have the value here
  12106. }, function (reason) {
  12107. // If `findCommentsByAuthor` rejects, we'll have the reason here
  12108. });
  12109. ```
  12110. Simple Example
  12111. --------------
  12112. Synchronous Example
  12113. ```javascript
  12114. var result;
  12115. try {
  12116. result = findResult();
  12117. // success
  12118. } catch(reason) {
  12119. // failure
  12120. }
  12121. ```
  12122. Errback Example
  12123. ```js
  12124. findResult(function(result, err){
  12125. if (err) {
  12126. // failure
  12127. } else {
  12128. // success
  12129. }
  12130. });
  12131. ```
  12132. Promise Example;
  12133. ```javascript
  12134. findResult().then(function(result){
  12135. // success
  12136. }, function(reason){
  12137. // failure
  12138. });
  12139. ```
  12140. Advanced Example
  12141. --------------
  12142. Synchronous Example
  12143. ```javascript
  12144. var author, books;
  12145. try {
  12146. author = findAuthor();
  12147. books = findBooksByAuthor(author);
  12148. // success
  12149. } catch(reason) {
  12150. // failure
  12151. }
  12152. ```
  12153. Errback Example
  12154. ```js
  12155. function foundBooks(books) {
  12156. }
  12157. function failure(reason) {
  12158. }
  12159. findAuthor(function(author, err){
  12160. if (err) {
  12161. failure(err);
  12162. // failure
  12163. } else {
  12164. try {
  12165. findBoooksByAuthor(author, function(books, err) {
  12166. if (err) {
  12167. failure(err);
  12168. } else {
  12169. try {
  12170. foundBooks(books);
  12171. } catch(reason) {
  12172. failure(reason);
  12173. }
  12174. }
  12175. });
  12176. } catch(error) {
  12177. failure(err);
  12178. }
  12179. // success
  12180. }
  12181. });
  12182. ```
  12183. Promise Example;
  12184. ```javascript
  12185. findAuthor().
  12186. then(findBooksByAuthor).
  12187. then(function(books){
  12188. // found books
  12189. }).catch(function(reason){
  12190. // something went wrong
  12191. });
  12192. ```
  12193. @method then
  12194. @param {Function} onFulfilled
  12195. @param {Function} onRejected
  12196. Useful for tooling.
  12197. @return {Promise}
  12198. */
  12199. then: function(onFulfillment, onRejection) {
  12200. var parent = this;
  12201. var state = parent._state;
  12202. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  12203. return this;
  12204. }
  12205. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  12206. var result = parent._result;
  12207. if (state) {
  12208. var callback = arguments[state - 1];
  12209. lib$es6$promise$asap$$asap(function(){
  12210. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  12211. });
  12212. } else {
  12213. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  12214. }
  12215. return child;
  12216. },
  12217. /**
  12218. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  12219. as the catch block of a try/catch statement.
  12220. ```js
  12221. function findAuthor(){
  12222. throw new Error('couldn't find that author');
  12223. }
  12224. // synchronous
  12225. try {
  12226. findAuthor();
  12227. } catch(reason) {
  12228. // something went wrong
  12229. }
  12230. // async with promises
  12231. findAuthor().catch(function(reason){
  12232. // something went wrong
  12233. });
  12234. ```
  12235. @method catch
  12236. @param {Function} onRejection
  12237. Useful for tooling.
  12238. @return {Promise}
  12239. */
  12240. 'catch': function(onRejection) {
  12241. return this.then(null, onRejection);
  12242. }
  12243. };
  12244. function lib$es6$promise$polyfill$$polyfill() {
  12245. var local;
  12246. if (typeof global !== 'undefined') {
  12247. local = global;
  12248. } else if (typeof self !== 'undefined') {
  12249. local = self;
  12250. } else {
  12251. try {
  12252. local = Function('return this')();
  12253. } catch (e) {
  12254. throw new Error('polyfill failed because global object is unavailable in this environment');
  12255. }
  12256. }
  12257. var P = local.Promise;
  12258. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  12259. return;
  12260. }
  12261. local.Promise = lib$es6$promise$promise$$default;
  12262. }
  12263. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  12264. var lib$es6$promise$umd$$ES6Promise = {
  12265. 'Promise': lib$es6$promise$promise$$default,
  12266. 'polyfill': lib$es6$promise$polyfill$$default
  12267. };
  12268. /* global define:true module:true window: true */
  12269. if (typeof define === 'function' && define['amd']) {
  12270. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  12271. } else if (typeof module !== 'undefined' && module['exports']) {
  12272. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  12273. } else if (typeof this !== 'undefined') {
  12274. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  12275. }
  12276. lib$es6$promise$polyfill$$default();
  12277. }).call(this);
  12278. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12279. },{"_process":42}],44:[function(require,module,exports){
  12280. /* Copyright @ 2015 Atlassian Pty Ltd
  12281. *
  12282. * Licensed under the Apache License, Version 2.0 (the "License");
  12283. * you may not use this file except in compliance with the License.
  12284. * You may obtain a copy of the License at
  12285. *
  12286. * http://www.apache.org/licenses/LICENSE-2.0
  12287. *
  12288. * Unless required by applicable law or agreed to in writing, software
  12289. * distributed under the License is distributed on an "AS IS" BASIS,
  12290. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12291. * See the License for the specific language governing permissions and
  12292. * limitations under the License.
  12293. */
  12294. /**
  12295. * Ordered log levels.
  12296. */
  12297. var levels = {
  12298. "trace": 0,
  12299. "debug": 1,
  12300. "info": 2,
  12301. "log": 3,
  12302. "warn": 4,
  12303. "error": 5
  12304. };
  12305. /**
  12306. * Parses Error's object stack trace and extracts information about the last
  12307. * caller before the log method was called.
  12308. * @returns JS object with info about the caller - method name, file location,
  12309. * line and column.
  12310. */
  12311. function getCallerInfo() {
  12312. var callerInfo = {
  12313. methodName: "",
  12314. fileLocation: "",
  12315. line: null,
  12316. column: null
  12317. };
  12318. //gets the part of the stack without the logger wrappers
  12319. var error = new Error();
  12320. var stack = error.stack? error.stack.split("\n") : [];
  12321. if(!stack || stack.length < 1) {
  12322. return callerInfo;
  12323. }
  12324. var m = null;
  12325. if(stack[3]) {
  12326. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  12327. }
  12328. if(!m || m.length <= 4) {
  12329. //Firefox && Safari
  12330. if(stack[2].indexOf("log@") === 0){
  12331. //Safari
  12332. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  12333. } else {
  12334. //Firefox
  12335. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  12336. }
  12337. return callerInfo;
  12338. }
  12339. callerInfo.methodName = m[1];
  12340. callerInfo.fileLocation = m[2];
  12341. callerInfo.line = m[3];
  12342. callerInfo.column = m[4];
  12343. return callerInfo;
  12344. }
  12345. /**
  12346. * Logs messages using the transports and level from the logger.
  12347. * @param logger a logger instance.
  12348. * @param level the log level of the message. See the levels variable.
  12349. * @param arguments array with arguments that will be logged.
  12350. */
  12351. function log() {
  12352. var logger = arguments[0], level = arguments[1],
  12353. args = Array.prototype.slice.call(arguments, 2);
  12354. if(levels[level] <= logger.level) {
  12355. return;
  12356. }
  12357. var callerInfo = getCallerInfo();
  12358. for(var i = 0; i < logger.transports.length; i++) {
  12359. var t = logger.transports[i];
  12360. var l = t[level];
  12361. if(l && typeof(l) === "function") {
  12362. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  12363. .apply(t, args);
  12364. }
  12365. }
  12366. }
  12367. /**
  12368. *
  12369. * Constructs new logger object.
  12370. * @param level the logging level for the new logger
  12371. * @param id optional identifier for the logger instance.
  12372. * @param transports optional list of handlers(objects) for the logs.
  12373. * The handlers must support - log, warn, error, debug, info, trace.
  12374. * @param format optional (NOT implemented) string.
  12375. */
  12376. function Logger(level, id, transports, format) {
  12377. this.id = id;
  12378. this.format = format;
  12379. if(!this.transports) {
  12380. this.transports = [];
  12381. this.transports.push(Logger.consoleTransport);
  12382. }
  12383. this.level = levels[level];
  12384. var methods = Object.keys(levels);
  12385. for(var i = 0; i < methods.length; i++){
  12386. this[methods[i]] =
  12387. log.bind(null, this, methods[i]);
  12388. }
  12389. }
  12390. /**
  12391. * Sets the log level for the logger.
  12392. * @param level the new log level.
  12393. */
  12394. Logger.prototype.setLevel = function (level) {
  12395. this.level = levels[level];
  12396. };
  12397. module.exports = Logger;
  12398. /**
  12399. * The default transport - console
  12400. */
  12401. Logger.consoleTransport = console;
  12402. /**
  12403. * Enum for the supported log levels.
  12404. */
  12405. Logger.levels = {
  12406. TRACE: "trace",
  12407. DEBUG: "debug",
  12408. INFO: "info",
  12409. LOG: "log",
  12410. WARN: "warn",
  12411. ERROR: "error"
  12412. };
  12413. },{}],45:[function(require,module,exports){
  12414. /* Copyright @ 2015 Atlassian Pty Ltd
  12415. *
  12416. * Licensed under the Apache License, Version 2.0 (the "License");
  12417. * you may not use this file except in compliance with the License.
  12418. * You may obtain a copy of the License at
  12419. *
  12420. * http://www.apache.org/licenses/LICENSE-2.0
  12421. *
  12422. * Unless required by applicable law or agreed to in writing, software
  12423. * distributed under the License is distributed on an "AS IS" BASIS,
  12424. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12425. * See the License for the specific language governing permissions and
  12426. * limitations under the License.
  12427. */
  12428. var Logger = require("./Logger");
  12429. /**
  12430. * Map with the created loggers with ID.
  12431. */
  12432. var idLoggers = {};
  12433. /**
  12434. * Array with the loggers without id.
  12435. */
  12436. var loggers = [];
  12437. /**
  12438. * Log level for the lbrary.
  12439. */
  12440. var curLevel = Logger.levels.TRACE;
  12441. module.exports = {
  12442. /**
  12443. * Creates new logger.
  12444. * @arguments the same as Logger constructor
  12445. */
  12446. getLogger: function(id, transports, format) {
  12447. var logger = new Logger(curLevel, id, transports, format);
  12448. if(id) {
  12449. idLoggers[id] = idLoggers[id] || [];
  12450. idLoggers[id].push(logger);
  12451. } else {
  12452. loggers.push(logger);
  12453. }
  12454. return logger;
  12455. },
  12456. /**
  12457. * Changes the log level for the existing loggers by id.
  12458. * @param level the new log level.
  12459. * @param id if specified the level will be changed only for loggers with the
  12460. * same id. Otherwise the operation will affect all loggers that don't
  12461. * have id.
  12462. */
  12463. setLogLevelById: function(level, id) {
  12464. var l = id? (idLoggers[id] || []) : loggers;
  12465. for(var i = 0; i < l.length; i++) {
  12466. l[i].setLevel(level);
  12467. }
  12468. },
  12469. /**
  12470. * Changes the log level for all existing loggers.
  12471. * @param level the new log level.
  12472. */
  12473. setLogLevel: function (level) {
  12474. curLevel = level;
  12475. var i = 0;
  12476. for(; i < loggers.length; i++) {
  12477. loggers[i].setLevel(level);
  12478. }
  12479. for(var id in idLoggers) {
  12480. var l = idLoggers[id] || [];
  12481. for(i = 0; i < l.length; i++) {
  12482. l[i].setLevel(level);
  12483. }
  12484. }
  12485. },
  12486. /**
  12487. * The supported log levels.
  12488. */
  12489. levels: Logger.levels
  12490. };
  12491. },{"./Logger":44}],46:[function(require,module,exports){
  12492. // Top level file is just a mixin of submodules & constants
  12493. 'use strict';
  12494. var assign = require('./lib/utils/common').assign;
  12495. var deflate = require('./lib/deflate');
  12496. var inflate = require('./lib/inflate');
  12497. var constants = require('./lib/zlib/constants');
  12498. var pako = {};
  12499. assign(pako, deflate, inflate, constants);
  12500. module.exports = pako;
  12501. },{"./lib/deflate":47,"./lib/inflate":48,"./lib/utils/common":49,"./lib/zlib/constants":52}],47:[function(require,module,exports){
  12502. 'use strict';
  12503. var zlib_deflate = require('./zlib/deflate.js');
  12504. var utils = require('./utils/common');
  12505. var strings = require('./utils/strings');
  12506. var msg = require('./zlib/messages');
  12507. var zstream = require('./zlib/zstream');
  12508. var toString = Object.prototype.toString;
  12509. /* Public constants ==========================================================*/
  12510. /* ===========================================================================*/
  12511. var Z_NO_FLUSH = 0;
  12512. var Z_FINISH = 4;
  12513. var Z_OK = 0;
  12514. var Z_STREAM_END = 1;
  12515. var Z_SYNC_FLUSH = 2;
  12516. var Z_DEFAULT_COMPRESSION = -1;
  12517. var Z_DEFAULT_STRATEGY = 0;
  12518. var Z_DEFLATED = 8;
  12519. /* ===========================================================================*/
  12520. /**
  12521. * class Deflate
  12522. *
  12523. * Generic JS-style wrapper for zlib calls. If you don't need
  12524. * streaming behaviour - use more simple functions: [[deflate]],
  12525. * [[deflateRaw]] and [[gzip]].
  12526. **/
  12527. /* internal
  12528. * Deflate.chunks -> Array
  12529. *
  12530. * Chunks of output data, if [[Deflate#onData]] not overriden.
  12531. **/
  12532. /**
  12533. * Deflate.result -> Uint8Array|Array
  12534. *
  12535. * Compressed result, generated by default [[Deflate#onData]]
  12536. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  12537. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  12538. * push a chunk with explicit flush (call [[Deflate#push]] with
  12539. * `Z_SYNC_FLUSH` param).
  12540. **/
  12541. /**
  12542. * Deflate.err -> Number
  12543. *
  12544. * Error code after deflate finished. 0 (Z_OK) on success.
  12545. * You will not need it in real life, because deflate errors
  12546. * are possible only on wrong options or bad `onData` / `onEnd`
  12547. * custom handlers.
  12548. **/
  12549. /**
  12550. * Deflate.msg -> String
  12551. *
  12552. * Error message, if [[Deflate.err]] != 0
  12553. **/
  12554. /**
  12555. * new Deflate(options)
  12556. * - options (Object): zlib deflate options.
  12557. *
  12558. * Creates new deflator instance with specified params. Throws exception
  12559. * on bad params. Supported options:
  12560. *
  12561. * - `level`
  12562. * - `windowBits`
  12563. * - `memLevel`
  12564. * - `strategy`
  12565. *
  12566. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12567. * for more information on these.
  12568. *
  12569. * Additional options, for internal needs:
  12570. *
  12571. * - `chunkSize` - size of generated data chunks (16K by default)
  12572. * - `raw` (Boolean) - do raw deflate
  12573. * - `gzip` (Boolean) - create gzip wrapper
  12574. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12575. * (each char code [0..255])
  12576. * - `header` (Object) - custom header for gzip
  12577. * - `text` (Boolean) - true if compressed data believed to be text
  12578. * - `time` (Number) - modification time, unix timestamp
  12579. * - `os` (Number) - operation system code
  12580. * - `extra` (Array) - array of bytes with extra data (max 65536)
  12581. * - `name` (String) - file name (binary string)
  12582. * - `comment` (String) - comment (binary string)
  12583. * - `hcrc` (Boolean) - true if header crc should be added
  12584. *
  12585. * ##### Example:
  12586. *
  12587. * ```javascript
  12588. * var pako = require('pako')
  12589. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12590. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12591. *
  12592. * var deflate = new pako.Deflate({ level: 3});
  12593. *
  12594. * deflate.push(chunk1, false);
  12595. * deflate.push(chunk2, true); // true -> last chunk
  12596. *
  12597. * if (deflate.err) { throw new Error(deflate.err); }
  12598. *
  12599. * console.log(deflate.result);
  12600. * ```
  12601. **/
  12602. var Deflate = function(options) {
  12603. this.options = utils.assign({
  12604. level: Z_DEFAULT_COMPRESSION,
  12605. method: Z_DEFLATED,
  12606. chunkSize: 16384,
  12607. windowBits: 15,
  12608. memLevel: 8,
  12609. strategy: Z_DEFAULT_STRATEGY,
  12610. to: ''
  12611. }, options || {});
  12612. var opt = this.options;
  12613. if (opt.raw && (opt.windowBits > 0)) {
  12614. opt.windowBits = -opt.windowBits;
  12615. }
  12616. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  12617. opt.windowBits += 16;
  12618. }
  12619. this.err = 0; // error code, if happens (0 = Z_OK)
  12620. this.msg = ''; // error message
  12621. this.ended = false; // used to avoid multiple onEnd() calls
  12622. this.chunks = []; // chunks of compressed data
  12623. this.strm = new zstream();
  12624. this.strm.avail_out = 0;
  12625. var status = zlib_deflate.deflateInit2(
  12626. this.strm,
  12627. opt.level,
  12628. opt.method,
  12629. opt.windowBits,
  12630. opt.memLevel,
  12631. opt.strategy
  12632. );
  12633. if (status !== Z_OK) {
  12634. throw new Error(msg[status]);
  12635. }
  12636. if (opt.header) {
  12637. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  12638. }
  12639. };
  12640. /**
  12641. * Deflate#push(data[, mode]) -> Boolean
  12642. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  12643. * converted to utf8 byte sequence.
  12644. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12645. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12646. *
  12647. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  12648. * new compressed chunks. Returns `true` on success. The last data block must have
  12649. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12650. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12651. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  12652. *
  12653. * On fail call [[Deflate#onEnd]] with error code and return false.
  12654. *
  12655. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12656. * array format is detected automatically). Also, don't skip last param and always
  12657. * use the same type in your code (boolean or number). That will improve JS speed.
  12658. *
  12659. * For regular `Array`-s make sure all elements are [0..255].
  12660. *
  12661. * ##### Example
  12662. *
  12663. * ```javascript
  12664. * push(chunk, false); // push one of data chunks
  12665. * ...
  12666. * push(chunk, true); // push last chunk
  12667. * ```
  12668. **/
  12669. Deflate.prototype.push = function(data, mode) {
  12670. var strm = this.strm;
  12671. var chunkSize = this.options.chunkSize;
  12672. var status, _mode;
  12673. if (this.ended) { return false; }
  12674. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  12675. // Convert data if needed
  12676. if (typeof data === 'string') {
  12677. // If we need to compress text, change encoding to utf8.
  12678. strm.input = strings.string2buf(data);
  12679. } else if (toString.call(data) === '[object ArrayBuffer]') {
  12680. strm.input = new Uint8Array(data);
  12681. } else {
  12682. strm.input = data;
  12683. }
  12684. strm.next_in = 0;
  12685. strm.avail_in = strm.input.length;
  12686. do {
  12687. if (strm.avail_out === 0) {
  12688. strm.output = new utils.Buf8(chunkSize);
  12689. strm.next_out = 0;
  12690. strm.avail_out = chunkSize;
  12691. }
  12692. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  12693. if (status !== Z_STREAM_END && status !== Z_OK) {
  12694. this.onEnd(status);
  12695. this.ended = true;
  12696. return false;
  12697. }
  12698. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  12699. if (this.options.to === 'string') {
  12700. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  12701. } else {
  12702. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  12703. }
  12704. }
  12705. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  12706. // Finalize on the last chunk.
  12707. if (_mode === Z_FINISH) {
  12708. status = zlib_deflate.deflateEnd(this.strm);
  12709. this.onEnd(status);
  12710. this.ended = true;
  12711. return status === Z_OK;
  12712. }
  12713. // callback interim results if Z_SYNC_FLUSH.
  12714. if (_mode === Z_SYNC_FLUSH) {
  12715. this.onEnd(Z_OK);
  12716. strm.avail_out = 0;
  12717. return true;
  12718. }
  12719. return true;
  12720. };
  12721. /**
  12722. * Deflate#onData(chunk) -> Void
  12723. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  12724. * on js engine support. When string output requested, each chunk
  12725. * will be string.
  12726. *
  12727. * By default, stores data blocks in `chunks[]` property and glue
  12728. * those in `onEnd`. Override this handler, if you need another behaviour.
  12729. **/
  12730. Deflate.prototype.onData = function(chunk) {
  12731. this.chunks.push(chunk);
  12732. };
  12733. /**
  12734. * Deflate#onEnd(status) -> Void
  12735. * - status (Number): deflate status. 0 (Z_OK) on success,
  12736. * other if not.
  12737. *
  12738. * Called once after you tell deflate that the input stream is
  12739. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  12740. * or if an error happened. By default - join collected chunks,
  12741. * free memory and fill `results` / `err` properties.
  12742. **/
  12743. Deflate.prototype.onEnd = function(status) {
  12744. // On success - join
  12745. if (status === Z_OK) {
  12746. if (this.options.to === 'string') {
  12747. this.result = this.chunks.join('');
  12748. } else {
  12749. this.result = utils.flattenChunks(this.chunks);
  12750. }
  12751. }
  12752. this.chunks = [];
  12753. this.err = status;
  12754. this.msg = this.strm.msg;
  12755. };
  12756. /**
  12757. * deflate(data[, options]) -> Uint8Array|Array|String
  12758. * - data (Uint8Array|Array|String): input data to compress.
  12759. * - options (Object): zlib deflate options.
  12760. *
  12761. * Compress `data` with deflate alrorythm and `options`.
  12762. *
  12763. * Supported options are:
  12764. *
  12765. * - level
  12766. * - windowBits
  12767. * - memLevel
  12768. * - strategy
  12769. *
  12770. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12771. * for more information on these.
  12772. *
  12773. * Sugar (options):
  12774. *
  12775. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  12776. * negative windowBits implicitly.
  12777. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12778. * (each char code [0..255])
  12779. *
  12780. * ##### Example:
  12781. *
  12782. * ```javascript
  12783. * var pako = require('pako')
  12784. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  12785. *
  12786. * console.log(pako.deflate(data));
  12787. * ```
  12788. **/
  12789. function deflate(input, options) {
  12790. var deflator = new Deflate(options);
  12791. deflator.push(input, true);
  12792. // That will never happens, if you don't cheat with options :)
  12793. if (deflator.err) { throw deflator.msg; }
  12794. return deflator.result;
  12795. }
  12796. /**
  12797. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  12798. * - data (Uint8Array|Array|String): input data to compress.
  12799. * - options (Object): zlib deflate options.
  12800. *
  12801. * The same as [[deflate]], but creates raw data, without wrapper
  12802. * (header and adler32 crc).
  12803. **/
  12804. function deflateRaw(input, options) {
  12805. options = options || {};
  12806. options.raw = true;
  12807. return deflate(input, options);
  12808. }
  12809. /**
  12810. * gzip(data[, options]) -> Uint8Array|Array|String
  12811. * - data (Uint8Array|Array|String): input data to compress.
  12812. * - options (Object): zlib deflate options.
  12813. *
  12814. * The same as [[deflate]], but create gzip wrapper instead of
  12815. * deflate one.
  12816. **/
  12817. function gzip(input, options) {
  12818. options = options || {};
  12819. options.gzip = true;
  12820. return deflate(input, options);
  12821. }
  12822. exports.Deflate = Deflate;
  12823. exports.deflate = deflate;
  12824. exports.deflateRaw = deflateRaw;
  12825. exports.gzip = gzip;
  12826. },{"./utils/common":49,"./utils/strings":50,"./zlib/deflate.js":54,"./zlib/messages":59,"./zlib/zstream":61}],48:[function(require,module,exports){
  12827. 'use strict';
  12828. var zlib_inflate = require('./zlib/inflate.js');
  12829. var utils = require('./utils/common');
  12830. var strings = require('./utils/strings');
  12831. var c = require('./zlib/constants');
  12832. var msg = require('./zlib/messages');
  12833. var zstream = require('./zlib/zstream');
  12834. var gzheader = require('./zlib/gzheader');
  12835. var toString = Object.prototype.toString;
  12836. /**
  12837. * class Inflate
  12838. *
  12839. * Generic JS-style wrapper for zlib calls. If you don't need
  12840. * streaming behaviour - use more simple functions: [[inflate]]
  12841. * and [[inflateRaw]].
  12842. **/
  12843. /* internal
  12844. * inflate.chunks -> Array
  12845. *
  12846. * Chunks of output data, if [[Inflate#onData]] not overriden.
  12847. **/
  12848. /**
  12849. * Inflate.result -> Uint8Array|Array|String
  12850. *
  12851. * Uncompressed result, generated by default [[Inflate#onData]]
  12852. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  12853. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  12854. * push a chunk with explicit flush (call [[Inflate#push]] with
  12855. * `Z_SYNC_FLUSH` param).
  12856. **/
  12857. /**
  12858. * Inflate.err -> Number
  12859. *
  12860. * Error code after inflate finished. 0 (Z_OK) on success.
  12861. * Should be checked if broken data possible.
  12862. **/
  12863. /**
  12864. * Inflate.msg -> String
  12865. *
  12866. * Error message, if [[Inflate.err]] != 0
  12867. **/
  12868. /**
  12869. * new Inflate(options)
  12870. * - options (Object): zlib inflate options.
  12871. *
  12872. * Creates new inflator instance with specified params. Throws exception
  12873. * on bad params. Supported options:
  12874. *
  12875. * - `windowBits`
  12876. *
  12877. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12878. * for more information on these.
  12879. *
  12880. * Additional options, for internal needs:
  12881. *
  12882. * - `chunkSize` - size of generated data chunks (16K by default)
  12883. * - `raw` (Boolean) - do raw inflate
  12884. * - `to` (String) - if equal to 'string', then result will be converted
  12885. * from utf8 to utf16 (javascript) string. When string output requested,
  12886. * chunk length can differ from `chunkSize`, depending on content.
  12887. *
  12888. * By default, when no options set, autodetect deflate/gzip data format via
  12889. * wrapper header.
  12890. *
  12891. * ##### Example:
  12892. *
  12893. * ```javascript
  12894. * var pako = require('pako')
  12895. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12896. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12897. *
  12898. * var inflate = new pako.Inflate({ level: 3});
  12899. *
  12900. * inflate.push(chunk1, false);
  12901. * inflate.push(chunk2, true); // true -> last chunk
  12902. *
  12903. * if (inflate.err) { throw new Error(inflate.err); }
  12904. *
  12905. * console.log(inflate.result);
  12906. * ```
  12907. **/
  12908. var Inflate = function(options) {
  12909. this.options = utils.assign({
  12910. chunkSize: 16384,
  12911. windowBits: 0,
  12912. to: ''
  12913. }, options || {});
  12914. var opt = this.options;
  12915. // Force window size for `raw` data, if not set directly,
  12916. // because we have no header for autodetect.
  12917. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  12918. opt.windowBits = -opt.windowBits;
  12919. if (opt.windowBits === 0) { opt.windowBits = -15; }
  12920. }
  12921. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  12922. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  12923. !(options && options.windowBits)) {
  12924. opt.windowBits += 32;
  12925. }
  12926. // Gzip header has no info about windows size, we can do autodetect only
  12927. // for deflate. So, if window size not set, force it to max when gzip possible
  12928. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  12929. // bit 3 (16) -> gzipped data
  12930. // bit 4 (32) -> autodetect gzip/deflate
  12931. if ((opt.windowBits & 15) === 0) {
  12932. opt.windowBits |= 15;
  12933. }
  12934. }
  12935. this.err = 0; // error code, if happens (0 = Z_OK)
  12936. this.msg = ''; // error message
  12937. this.ended = false; // used to avoid multiple onEnd() calls
  12938. this.chunks = []; // chunks of compressed data
  12939. this.strm = new zstream();
  12940. this.strm.avail_out = 0;
  12941. var status = zlib_inflate.inflateInit2(
  12942. this.strm,
  12943. opt.windowBits
  12944. );
  12945. if (status !== c.Z_OK) {
  12946. throw new Error(msg[status]);
  12947. }
  12948. this.header = new gzheader();
  12949. zlib_inflate.inflateGetHeader(this.strm, this.header);
  12950. };
  12951. /**
  12952. * Inflate#push(data[, mode]) -> Boolean
  12953. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  12954. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12955. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  12956. *
  12957. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  12958. * new output chunks. Returns `true` on success. The last data block must have
  12959. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12960. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12961. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  12962. *
  12963. * On fail call [[Inflate#onEnd]] with error code and return false.
  12964. *
  12965. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12966. * format is detected automatically). Also, don't skip last param and always
  12967. * use the same type in your code (boolean or number). That will improve JS speed.
  12968. *
  12969. * For regular `Array`-s make sure all elements are [0..255].
  12970. *
  12971. * ##### Example
  12972. *
  12973. * ```javascript
  12974. * push(chunk, false); // push one of data chunks
  12975. * ...
  12976. * push(chunk, true); // push last chunk
  12977. * ```
  12978. **/
  12979. Inflate.prototype.push = function(data, mode) {
  12980. var strm = this.strm;
  12981. var chunkSize = this.options.chunkSize;
  12982. var status, _mode;
  12983. var next_out_utf8, tail, utf8str;
  12984. // Flag to properly process Z_BUF_ERROR on testing inflate call
  12985. // when we check that all output data was flushed.
  12986. var allowBufError = false;
  12987. if (this.ended) { return false; }
  12988. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  12989. // Convert data if needed
  12990. if (typeof data === 'string') {
  12991. // Only binary strings can be decompressed on practice
  12992. strm.input = strings.binstring2buf(data);
  12993. } else if (toString.call(data) === '[object ArrayBuffer]') {
  12994. strm.input = new Uint8Array(data);
  12995. } else {
  12996. strm.input = data;
  12997. }
  12998. strm.next_in = 0;
  12999. strm.avail_in = strm.input.length;
  13000. do {
  13001. if (strm.avail_out === 0) {
  13002. strm.output = new utils.Buf8(chunkSize);
  13003. strm.next_out = 0;
  13004. strm.avail_out = chunkSize;
  13005. }
  13006. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13007. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13008. status = c.Z_OK;
  13009. allowBufError = false;
  13010. }
  13011. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13012. this.onEnd(status);
  13013. this.ended = true;
  13014. return false;
  13015. }
  13016. if (strm.next_out) {
  13017. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13018. if (this.options.to === 'string') {
  13019. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13020. tail = strm.next_out - next_out_utf8;
  13021. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13022. // move tail
  13023. strm.next_out = tail;
  13024. strm.avail_out = chunkSize - tail;
  13025. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13026. this.onData(utf8str);
  13027. } else {
  13028. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13029. }
  13030. }
  13031. }
  13032. // When no more input data, we should check that internal inflate buffers
  13033. // are flushed. The only way to do it when avail_out = 0 - run one more
  13034. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13035. // Here we set flag to process this error properly.
  13036. //
  13037. // NOTE. Deflate does not return error in this case and does not needs such
  13038. // logic.
  13039. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13040. allowBufError = true;
  13041. }
  13042. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13043. if (status === c.Z_STREAM_END) {
  13044. _mode = c.Z_FINISH;
  13045. }
  13046. // Finalize on the last chunk.
  13047. if (_mode === c.Z_FINISH) {
  13048. status = zlib_inflate.inflateEnd(this.strm);
  13049. this.onEnd(status);
  13050. this.ended = true;
  13051. return status === c.Z_OK;
  13052. }
  13053. // callback interim results if Z_SYNC_FLUSH.
  13054. if (_mode === c.Z_SYNC_FLUSH) {
  13055. this.onEnd(c.Z_OK);
  13056. strm.avail_out = 0;
  13057. return true;
  13058. }
  13059. return true;
  13060. };
  13061. /**
  13062. * Inflate#onData(chunk) -> Void
  13063. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  13064. * on js engine support. When string output requested, each chunk
  13065. * will be string.
  13066. *
  13067. * By default, stores data blocks in `chunks[]` property and glue
  13068. * those in `onEnd`. Override this handler, if you need another behaviour.
  13069. **/
  13070. Inflate.prototype.onData = function(chunk) {
  13071. this.chunks.push(chunk);
  13072. };
  13073. /**
  13074. * Inflate#onEnd(status) -> Void
  13075. * - status (Number): inflate status. 0 (Z_OK) on success,
  13076. * other if not.
  13077. *
  13078. * Called either after you tell inflate that the input stream is
  13079. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13080. * or if an error happened. By default - join collected chunks,
  13081. * free memory and fill `results` / `err` properties.
  13082. **/
  13083. Inflate.prototype.onEnd = function(status) {
  13084. // On success - join
  13085. if (status === c.Z_OK) {
  13086. if (this.options.to === 'string') {
  13087. // Glue & convert here, until we teach pako to send
  13088. // utf8 alligned strings to onData
  13089. this.result = this.chunks.join('');
  13090. } else {
  13091. this.result = utils.flattenChunks(this.chunks);
  13092. }
  13093. }
  13094. this.chunks = [];
  13095. this.err = status;
  13096. this.msg = this.strm.msg;
  13097. };
  13098. /**
  13099. * inflate(data[, options]) -> Uint8Array|Array|String
  13100. * - data (Uint8Array|Array|String): input data to decompress.
  13101. * - options (Object): zlib inflate options.
  13102. *
  13103. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  13104. * format via wrapper header by default. That's why we don't provide
  13105. * separate `ungzip` method.
  13106. *
  13107. * Supported options are:
  13108. *
  13109. * - windowBits
  13110. *
  13111. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13112. * for more information.
  13113. *
  13114. * Sugar (options):
  13115. *
  13116. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13117. * negative windowBits implicitly.
  13118. * - `to` (String) - if equal to 'string', then result will be converted
  13119. * from utf8 to utf16 (javascript) string. When string output requested,
  13120. * chunk length can differ from `chunkSize`, depending on content.
  13121. *
  13122. *
  13123. * ##### Example:
  13124. *
  13125. * ```javascript
  13126. * var pako = require('pako')
  13127. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  13128. * , output;
  13129. *
  13130. * try {
  13131. * output = pako.inflate(input);
  13132. * } catch (err)
  13133. * console.log(err);
  13134. * }
  13135. * ```
  13136. **/
  13137. function inflate(input, options) {
  13138. var inflator = new Inflate(options);
  13139. inflator.push(input, true);
  13140. // That will never happens, if you don't cheat with options :)
  13141. if (inflator.err) { throw inflator.msg; }
  13142. return inflator.result;
  13143. }
  13144. /**
  13145. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  13146. * - data (Uint8Array|Array|String): input data to decompress.
  13147. * - options (Object): zlib inflate options.
  13148. *
  13149. * The same as [[inflate]], but creates raw data, without wrapper
  13150. * (header and adler32 crc).
  13151. **/
  13152. function inflateRaw(input, options) {
  13153. options = options || {};
  13154. options.raw = true;
  13155. return inflate(input, options);
  13156. }
  13157. /**
  13158. * ungzip(data[, options]) -> Uint8Array|Array|String
  13159. * - data (Uint8Array|Array|String): input data to decompress.
  13160. * - options (Object): zlib inflate options.
  13161. *
  13162. * Just shortcut to [[inflate]], because it autodetects format
  13163. * by header.content. Done for convenience.
  13164. **/
  13165. exports.Inflate = Inflate;
  13166. exports.inflate = inflate;
  13167. exports.inflateRaw = inflateRaw;
  13168. exports.ungzip = inflate;
  13169. },{"./utils/common":49,"./utils/strings":50,"./zlib/constants":52,"./zlib/gzheader":55,"./zlib/inflate.js":57,"./zlib/messages":59,"./zlib/zstream":61}],49:[function(require,module,exports){
  13170. 'use strict';
  13171. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  13172. (typeof Uint16Array !== 'undefined') &&
  13173. (typeof Int32Array !== 'undefined');
  13174. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  13175. var sources = Array.prototype.slice.call(arguments, 1);
  13176. while (sources.length) {
  13177. var source = sources.shift();
  13178. if (!source) { continue; }
  13179. if (typeof source !== 'object') {
  13180. throw new TypeError(source + 'must be non-object');
  13181. }
  13182. for (var p in source) {
  13183. if (source.hasOwnProperty(p)) {
  13184. obj[p] = source[p];
  13185. }
  13186. }
  13187. }
  13188. return obj;
  13189. };
  13190. // reduce buffer size, avoiding mem copy
  13191. exports.shrinkBuf = function (buf, size) {
  13192. if (buf.length === size) { return buf; }
  13193. if (buf.subarray) { return buf.subarray(0, size); }
  13194. buf.length = size;
  13195. return buf;
  13196. };
  13197. var fnTyped = {
  13198. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13199. if (src.subarray && dest.subarray) {
  13200. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  13201. return;
  13202. }
  13203. // Fallback to ordinary array
  13204. for (var i=0; i<len; i++) {
  13205. dest[dest_offs + i] = src[src_offs + i];
  13206. }
  13207. },
  13208. // Join array of chunks to single array.
  13209. flattenChunks: function(chunks) {
  13210. var i, l, len, pos, chunk, result;
  13211. // calculate data length
  13212. len = 0;
  13213. for (i=0, l=chunks.length; i<l; i++) {
  13214. len += chunks[i].length;
  13215. }
  13216. // join chunks
  13217. result = new Uint8Array(len);
  13218. pos = 0;
  13219. for (i=0, l=chunks.length; i<l; i++) {
  13220. chunk = chunks[i];
  13221. result.set(chunk, pos);
  13222. pos += chunk.length;
  13223. }
  13224. return result;
  13225. }
  13226. };
  13227. var fnUntyped = {
  13228. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13229. for (var i=0; i<len; i++) {
  13230. dest[dest_offs + i] = src[src_offs + i];
  13231. }
  13232. },
  13233. // Join array of chunks to single array.
  13234. flattenChunks: function(chunks) {
  13235. return [].concat.apply([], chunks);
  13236. }
  13237. };
  13238. // Enable/Disable typed arrays use, for testing
  13239. //
  13240. exports.setTyped = function (on) {
  13241. if (on) {
  13242. exports.Buf8 = Uint8Array;
  13243. exports.Buf16 = Uint16Array;
  13244. exports.Buf32 = Int32Array;
  13245. exports.assign(exports, fnTyped);
  13246. } else {
  13247. exports.Buf8 = Array;
  13248. exports.Buf16 = Array;
  13249. exports.Buf32 = Array;
  13250. exports.assign(exports, fnUntyped);
  13251. }
  13252. };
  13253. exports.setTyped(TYPED_OK);
  13254. },{}],50:[function(require,module,exports){
  13255. // String encode/decode helpers
  13256. 'use strict';
  13257. var utils = require('./common');
  13258. // Quick check if we can use fast array to bin string conversion
  13259. //
  13260. // - apply(Array) can fail on Android 2.2
  13261. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  13262. //
  13263. var STR_APPLY_OK = true;
  13264. var STR_APPLY_UIA_OK = true;
  13265. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  13266. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  13267. // Table with utf8 lengths (calculated by first byte of sequence)
  13268. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13269. // because max possible codepoint is 0x10ffff
  13270. var _utf8len = new utils.Buf8(256);
  13271. for (var q=0; q<256; q++) {
  13272. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  13273. }
  13274. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  13275. // convert string to array (typed, when possible)
  13276. exports.string2buf = function (str) {
  13277. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13278. // count binary size
  13279. for (m_pos = 0; m_pos < str_len; m_pos++) {
  13280. c = str.charCodeAt(m_pos);
  13281. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13282. c2 = str.charCodeAt(m_pos+1);
  13283. if ((c2 & 0xfc00) === 0xdc00) {
  13284. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13285. m_pos++;
  13286. }
  13287. }
  13288. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  13289. }
  13290. // allocate buffer
  13291. buf = new utils.Buf8(buf_len);
  13292. // convert
  13293. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  13294. c = str.charCodeAt(m_pos);
  13295. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  13296. c2 = str.charCodeAt(m_pos+1);
  13297. if ((c2 & 0xfc00) === 0xdc00) {
  13298. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13299. m_pos++;
  13300. }
  13301. }
  13302. if (c < 0x80) {
  13303. /* one byte */
  13304. buf[i++] = c;
  13305. } else if (c < 0x800) {
  13306. /* two bytes */
  13307. buf[i++] = 0xC0 | (c >>> 6);
  13308. buf[i++] = 0x80 | (c & 0x3f);
  13309. } else if (c < 0x10000) {
  13310. /* three bytes */
  13311. buf[i++] = 0xE0 | (c >>> 12);
  13312. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13313. buf[i++] = 0x80 | (c & 0x3f);
  13314. } else {
  13315. /* four bytes */
  13316. buf[i++] = 0xf0 | (c >>> 18);
  13317. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  13318. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13319. buf[i++] = 0x80 | (c & 0x3f);
  13320. }
  13321. }
  13322. return buf;
  13323. };
  13324. // Helper (used in 2 places)
  13325. function buf2binstring(buf, len) {
  13326. // use fallback for big arrays to avoid stack overflow
  13327. if (len < 65537) {
  13328. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  13329. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  13330. }
  13331. }
  13332. var result = '';
  13333. for (var i=0; i < len; i++) {
  13334. result += String.fromCharCode(buf[i]);
  13335. }
  13336. return result;
  13337. }
  13338. // Convert byte array to binary string
  13339. exports.buf2binstring = function(buf) {
  13340. return buf2binstring(buf, buf.length);
  13341. };
  13342. // Convert binary string (typed, when possible)
  13343. exports.binstring2buf = function(str) {
  13344. var buf = new utils.Buf8(str.length);
  13345. for (var i=0, len=buf.length; i < len; i++) {
  13346. buf[i] = str.charCodeAt(i);
  13347. }
  13348. return buf;
  13349. };
  13350. // convert array to string
  13351. exports.buf2string = function (buf, max) {
  13352. var i, out, c, c_len;
  13353. var len = max || buf.length;
  13354. // Reserve max possible length (2 words per char)
  13355. // NB: by unknown reasons, Array is significantly faster for
  13356. // String.fromCharCode.apply than Uint16Array.
  13357. var utf16buf = new Array(len*2);
  13358. for (out=0, i=0; i<len;) {
  13359. c = buf[i++];
  13360. // quick process ascii
  13361. if (c < 0x80) { utf16buf[out++] = c; continue; }
  13362. c_len = _utf8len[c];
  13363. // skip 5 & 6 byte codes
  13364. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  13365. // apply mask on first byte
  13366. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  13367. // join the rest
  13368. while (c_len > 1 && i < len) {
  13369. c = (c << 6) | (buf[i++] & 0x3f);
  13370. c_len--;
  13371. }
  13372. // terminated by end of string?
  13373. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  13374. if (c < 0x10000) {
  13375. utf16buf[out++] = c;
  13376. } else {
  13377. c -= 0x10000;
  13378. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  13379. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  13380. }
  13381. }
  13382. return buf2binstring(utf16buf, out);
  13383. };
  13384. // Calculate max possible position in utf8 buffer,
  13385. // that will not break sequence. If that's not possible
  13386. // - (very small limits) return max size as is.
  13387. //
  13388. // buf[] - utf8 bytes array
  13389. // max - length limit (mandatory);
  13390. exports.utf8border = function(buf, max) {
  13391. var pos;
  13392. max = max || buf.length;
  13393. if (max > buf.length) { max = buf.length; }
  13394. // go back from last position, until start of sequence found
  13395. pos = max-1;
  13396. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  13397. // Fuckup - very small and broken sequence,
  13398. // return max, because we should return something anyway.
  13399. if (pos < 0) { return max; }
  13400. // If we came to start of buffer - that means vuffer is too small,
  13401. // return max too.
  13402. if (pos === 0) { return max; }
  13403. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  13404. };
  13405. },{"./common":49}],51:[function(require,module,exports){
  13406. 'use strict';
  13407. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  13408. // It doesn't worth to make additional optimizationa as in original.
  13409. // Small size is preferable.
  13410. function adler32(adler, buf, len, pos) {
  13411. var s1 = (adler & 0xffff) |0,
  13412. s2 = ((adler >>> 16) & 0xffff) |0,
  13413. n = 0;
  13414. while (len !== 0) {
  13415. // Set limit ~ twice less than 5552, to keep
  13416. // s2 in 31-bits, because we force signed ints.
  13417. // in other case %= will fail.
  13418. n = len > 2000 ? 2000 : len;
  13419. len -= n;
  13420. do {
  13421. s1 = (s1 + buf[pos++]) |0;
  13422. s2 = (s2 + s1) |0;
  13423. } while (--n);
  13424. s1 %= 65521;
  13425. s2 %= 65521;
  13426. }
  13427. return (s1 | (s2 << 16)) |0;
  13428. }
  13429. module.exports = adler32;
  13430. },{}],52:[function(require,module,exports){
  13431. module.exports = {
  13432. /* Allowed flush values; see deflate() and inflate() below for details */
  13433. Z_NO_FLUSH: 0,
  13434. Z_PARTIAL_FLUSH: 1,
  13435. Z_SYNC_FLUSH: 2,
  13436. Z_FULL_FLUSH: 3,
  13437. Z_FINISH: 4,
  13438. Z_BLOCK: 5,
  13439. Z_TREES: 6,
  13440. /* Return codes for the compression/decompression functions. Negative values
  13441. * are errors, positive values are used for special but normal events.
  13442. */
  13443. Z_OK: 0,
  13444. Z_STREAM_END: 1,
  13445. Z_NEED_DICT: 2,
  13446. Z_ERRNO: -1,
  13447. Z_STREAM_ERROR: -2,
  13448. Z_DATA_ERROR: -3,
  13449. //Z_MEM_ERROR: -4,
  13450. Z_BUF_ERROR: -5,
  13451. //Z_VERSION_ERROR: -6,
  13452. /* compression levels */
  13453. Z_NO_COMPRESSION: 0,
  13454. Z_BEST_SPEED: 1,
  13455. Z_BEST_COMPRESSION: 9,
  13456. Z_DEFAULT_COMPRESSION: -1,
  13457. Z_FILTERED: 1,
  13458. Z_HUFFMAN_ONLY: 2,
  13459. Z_RLE: 3,
  13460. Z_FIXED: 4,
  13461. Z_DEFAULT_STRATEGY: 0,
  13462. /* Possible values of the data_type field (though see inflate()) */
  13463. Z_BINARY: 0,
  13464. Z_TEXT: 1,
  13465. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  13466. Z_UNKNOWN: 2,
  13467. /* The deflate compression method */
  13468. Z_DEFLATED: 8
  13469. //Z_NULL: null // Use -1 or null inline, depending on var type
  13470. };
  13471. },{}],53:[function(require,module,exports){
  13472. 'use strict';
  13473. // Note: we can't get significant speed boost here.
  13474. // So write code to minimize size - no pregenerated tables
  13475. // and array tools dependencies.
  13476. // Use ordinary array, since untyped makes no boost here
  13477. function makeTable() {
  13478. var c, table = [];
  13479. for (var n =0; n < 256; n++) {
  13480. c = n;
  13481. for (var k =0; k < 8; k++) {
  13482. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  13483. }
  13484. table[n] = c;
  13485. }
  13486. return table;
  13487. }
  13488. // Create table on load. Just 255 signed longs. Not a problem.
  13489. var crcTable = makeTable();
  13490. function crc32(crc, buf, len, pos) {
  13491. var t = crcTable,
  13492. end = pos + len;
  13493. crc = crc ^ (-1);
  13494. for (var i = pos; i < end; i++) {
  13495. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  13496. }
  13497. return (crc ^ (-1)); // >>> 0;
  13498. }
  13499. module.exports = crc32;
  13500. },{}],54:[function(require,module,exports){
  13501. 'use strict';
  13502. var utils = require('../utils/common');
  13503. var trees = require('./trees');
  13504. var adler32 = require('./adler32');
  13505. var crc32 = require('./crc32');
  13506. var msg = require('./messages');
  13507. /* Public constants ==========================================================*/
  13508. /* ===========================================================================*/
  13509. /* Allowed flush values; see deflate() and inflate() below for details */
  13510. var Z_NO_FLUSH = 0;
  13511. var Z_PARTIAL_FLUSH = 1;
  13512. //var Z_SYNC_FLUSH = 2;
  13513. var Z_FULL_FLUSH = 3;
  13514. var Z_FINISH = 4;
  13515. var Z_BLOCK = 5;
  13516. //var Z_TREES = 6;
  13517. /* Return codes for the compression/decompression functions. Negative values
  13518. * are errors, positive values are used for special but normal events.
  13519. */
  13520. var Z_OK = 0;
  13521. var Z_STREAM_END = 1;
  13522. //var Z_NEED_DICT = 2;
  13523. //var Z_ERRNO = -1;
  13524. var Z_STREAM_ERROR = -2;
  13525. var Z_DATA_ERROR = -3;
  13526. //var Z_MEM_ERROR = -4;
  13527. var Z_BUF_ERROR = -5;
  13528. //var Z_VERSION_ERROR = -6;
  13529. /* compression levels */
  13530. //var Z_NO_COMPRESSION = 0;
  13531. //var Z_BEST_SPEED = 1;
  13532. //var Z_BEST_COMPRESSION = 9;
  13533. var Z_DEFAULT_COMPRESSION = -1;
  13534. var Z_FILTERED = 1;
  13535. var Z_HUFFMAN_ONLY = 2;
  13536. var Z_RLE = 3;
  13537. var Z_FIXED = 4;
  13538. var Z_DEFAULT_STRATEGY = 0;
  13539. /* Possible values of the data_type field (though see inflate()) */
  13540. //var Z_BINARY = 0;
  13541. //var Z_TEXT = 1;
  13542. //var Z_ASCII = 1; // = Z_TEXT
  13543. var Z_UNKNOWN = 2;
  13544. /* The deflate compression method */
  13545. var Z_DEFLATED = 8;
  13546. /*============================================================================*/
  13547. var MAX_MEM_LEVEL = 9;
  13548. /* Maximum value for memLevel in deflateInit2 */
  13549. var MAX_WBITS = 15;
  13550. /* 32K LZ77 window */
  13551. var DEF_MEM_LEVEL = 8;
  13552. var LENGTH_CODES = 29;
  13553. /* number of length codes, not counting the special END_BLOCK code */
  13554. var LITERALS = 256;
  13555. /* number of literal bytes 0..255 */
  13556. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  13557. /* number of Literal or Length codes, including the END_BLOCK code */
  13558. var D_CODES = 30;
  13559. /* number of distance codes */
  13560. var BL_CODES = 19;
  13561. /* number of codes used to transfer the bit lengths */
  13562. var HEAP_SIZE = 2*L_CODES + 1;
  13563. /* maximum heap size */
  13564. var MAX_BITS = 15;
  13565. /* All codes must not exceed MAX_BITS bits */
  13566. var MIN_MATCH = 3;
  13567. var MAX_MATCH = 258;
  13568. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  13569. var PRESET_DICT = 0x20;
  13570. var INIT_STATE = 42;
  13571. var EXTRA_STATE = 69;
  13572. var NAME_STATE = 73;
  13573. var COMMENT_STATE = 91;
  13574. var HCRC_STATE = 103;
  13575. var BUSY_STATE = 113;
  13576. var FINISH_STATE = 666;
  13577. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  13578. var BS_BLOCK_DONE = 2; /* block flush performed */
  13579. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  13580. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  13581. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  13582. function err(strm, errorCode) {
  13583. strm.msg = msg[errorCode];
  13584. return errorCode;
  13585. }
  13586. function rank(f) {
  13587. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  13588. }
  13589. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  13590. /* =========================================================================
  13591. * Flush as much pending output as possible. All deflate() output goes
  13592. * through this function so some applications may wish to modify it
  13593. * to avoid allocating a large strm->output buffer and copying into it.
  13594. * (See also read_buf()).
  13595. */
  13596. function flush_pending(strm) {
  13597. var s = strm.state;
  13598. //_tr_flush_bits(s);
  13599. var len = s.pending;
  13600. if (len > strm.avail_out) {
  13601. len = strm.avail_out;
  13602. }
  13603. if (len === 0) { return; }
  13604. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  13605. strm.next_out += len;
  13606. s.pending_out += len;
  13607. strm.total_out += len;
  13608. strm.avail_out -= len;
  13609. s.pending -= len;
  13610. if (s.pending === 0) {
  13611. s.pending_out = 0;
  13612. }
  13613. }
  13614. function flush_block_only (s, last) {
  13615. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  13616. s.block_start = s.strstart;
  13617. flush_pending(s.strm);
  13618. }
  13619. function put_byte(s, b) {
  13620. s.pending_buf[s.pending++] = b;
  13621. }
  13622. /* =========================================================================
  13623. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  13624. * IN assertion: the stream state is correct and there is enough room in
  13625. * pending_buf.
  13626. */
  13627. function putShortMSB(s, b) {
  13628. // put_byte(s, (Byte)(b >> 8));
  13629. // put_byte(s, (Byte)(b & 0xff));
  13630. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  13631. s.pending_buf[s.pending++] = b & 0xff;
  13632. }
  13633. /* ===========================================================================
  13634. * Read a new buffer from the current input stream, update the adler32
  13635. * and total number of bytes read. All deflate() input goes through
  13636. * this function so some applications may wish to modify it to avoid
  13637. * allocating a large strm->input buffer and copying from it.
  13638. * (See also flush_pending()).
  13639. */
  13640. function read_buf(strm, buf, start, size) {
  13641. var len = strm.avail_in;
  13642. if (len > size) { len = size; }
  13643. if (len === 0) { return 0; }
  13644. strm.avail_in -= len;
  13645. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  13646. if (strm.state.wrap === 1) {
  13647. strm.adler = adler32(strm.adler, buf, len, start);
  13648. }
  13649. else if (strm.state.wrap === 2) {
  13650. strm.adler = crc32(strm.adler, buf, len, start);
  13651. }
  13652. strm.next_in += len;
  13653. strm.total_in += len;
  13654. return len;
  13655. }
  13656. /* ===========================================================================
  13657. * Set match_start to the longest match starting at the given string and
  13658. * return its length. Matches shorter or equal to prev_length are discarded,
  13659. * in which case the result is equal to prev_length and match_start is
  13660. * garbage.
  13661. * IN assertions: cur_match is the head of the hash chain for the current
  13662. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  13663. * OUT assertion: the match length is not greater than s->lookahead.
  13664. */
  13665. function longest_match(s, cur_match) {
  13666. var chain_length = s.max_chain_length; /* max hash chain length */
  13667. var scan = s.strstart; /* current string */
  13668. var match; /* matched string */
  13669. var len; /* length of current match */
  13670. var best_len = s.prev_length; /* best match length so far */
  13671. var nice_match = s.nice_match; /* stop if match long enough */
  13672. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  13673. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  13674. var _win = s.window; // shortcut
  13675. var wmask = s.w_mask;
  13676. var prev = s.prev;
  13677. /* Stop when cur_match becomes <= limit. To simplify the code,
  13678. * we prevent matches with the string of window index 0.
  13679. */
  13680. var strend = s.strstart + MAX_MATCH;
  13681. var scan_end1 = _win[scan + best_len - 1];
  13682. var scan_end = _win[scan + best_len];
  13683. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  13684. * It is easy to get rid of this optimization if necessary.
  13685. */
  13686. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  13687. /* Do not waste too much time if we already have a good match: */
  13688. if (s.prev_length >= s.good_match) {
  13689. chain_length >>= 2;
  13690. }
  13691. /* Do not look for matches beyond the end of the input. This is necessary
  13692. * to make deflate deterministic.
  13693. */
  13694. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  13695. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  13696. do {
  13697. // Assert(cur_match < s->strstart, "no future");
  13698. match = cur_match;
  13699. /* Skip to next match if the match length cannot increase
  13700. * or if the match length is less than 2. Note that the checks below
  13701. * for insufficient lookahead only occur occasionally for performance
  13702. * reasons. Therefore uninitialized memory will be accessed, and
  13703. * conditional jumps will be made that depend on those values.
  13704. * However the length of the match is limited to the lookahead, so
  13705. * the output of deflate is not affected by the uninitialized values.
  13706. */
  13707. if (_win[match + best_len] !== scan_end ||
  13708. _win[match + best_len - 1] !== scan_end1 ||
  13709. _win[match] !== _win[scan] ||
  13710. _win[++match] !== _win[scan + 1]) {
  13711. continue;
  13712. }
  13713. /* The check at best_len-1 can be removed because it will be made
  13714. * again later. (This heuristic is not always a win.)
  13715. * It is not necessary to compare scan[2] and match[2] since they
  13716. * are always equal when the other bytes match, given that
  13717. * the hash keys are equal and that HASH_BITS >= 8.
  13718. */
  13719. scan += 2;
  13720. match++;
  13721. // Assert(*scan == *match, "match[2]?");
  13722. /* We check for insufficient lookahead only every 8th comparison;
  13723. * the 256th check will be made at strstart+258.
  13724. */
  13725. do {
  13726. /*jshint noempty:false*/
  13727. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13728. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13729. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13730. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13731. scan < strend);
  13732. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  13733. len = MAX_MATCH - (strend - scan);
  13734. scan = strend - MAX_MATCH;
  13735. if (len > best_len) {
  13736. s.match_start = cur_match;
  13737. best_len = len;
  13738. if (len >= nice_match) {
  13739. break;
  13740. }
  13741. scan_end1 = _win[scan + best_len - 1];
  13742. scan_end = _win[scan + best_len];
  13743. }
  13744. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  13745. if (best_len <= s.lookahead) {
  13746. return best_len;
  13747. }
  13748. return s.lookahead;
  13749. }
  13750. /* ===========================================================================
  13751. * Fill the window when the lookahead becomes insufficient.
  13752. * Updates strstart and lookahead.
  13753. *
  13754. * IN assertion: lookahead < MIN_LOOKAHEAD
  13755. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  13756. * At least one byte has been read, or avail_in == 0; reads are
  13757. * performed for at least two bytes (required for the zip translate_eol
  13758. * option -- not supported here).
  13759. */
  13760. function fill_window(s) {
  13761. var _w_size = s.w_size;
  13762. var p, n, m, more, str;
  13763. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  13764. do {
  13765. more = s.window_size - s.lookahead - s.strstart;
  13766. // JS ints have 32 bit, block below not needed
  13767. /* Deal with !@#$% 64K limit: */
  13768. //if (sizeof(int) <= 2) {
  13769. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  13770. // more = wsize;
  13771. //
  13772. // } else if (more == (unsigned)(-1)) {
  13773. // /* Very unlikely, but possible on 16 bit machine if
  13774. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  13775. // */
  13776. // more--;
  13777. // }
  13778. //}
  13779. /* If the window is almost full and there is insufficient lookahead,
  13780. * move the upper half to the lower one to make room in the upper half.
  13781. */
  13782. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  13783. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  13784. s.match_start -= _w_size;
  13785. s.strstart -= _w_size;
  13786. /* we now have strstart >= MAX_DIST */
  13787. s.block_start -= _w_size;
  13788. /* Slide the hash table (could be avoided with 32 bit values
  13789. at the expense of memory usage). We slide even when level == 0
  13790. to keep the hash table consistent if we switch back to level > 0
  13791. later. (Using level 0 permanently is not an optimal usage of
  13792. zlib, so we don't care about this pathological case.)
  13793. */
  13794. n = s.hash_size;
  13795. p = n;
  13796. do {
  13797. m = s.head[--p];
  13798. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  13799. } while (--n);
  13800. n = _w_size;
  13801. p = n;
  13802. do {
  13803. m = s.prev[--p];
  13804. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  13805. /* If n is not on any hash chain, prev[n] is garbage but
  13806. * its value will never be used.
  13807. */
  13808. } while (--n);
  13809. more += _w_size;
  13810. }
  13811. if (s.strm.avail_in === 0) {
  13812. break;
  13813. }
  13814. /* If there was no sliding:
  13815. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  13816. * more == window_size - lookahead - strstart
  13817. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  13818. * => more >= window_size - 2*WSIZE + 2
  13819. * In the BIG_MEM or MMAP case (not yet supported),
  13820. * window_size == input_size + MIN_LOOKAHEAD &&
  13821. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  13822. * Otherwise, window_size == 2*WSIZE so more >= 2.
  13823. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  13824. */
  13825. //Assert(more >= 2, "more < 2");
  13826. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  13827. s.lookahead += n;
  13828. /* Initialize the hash value now that we have some input: */
  13829. if (s.lookahead + s.insert >= MIN_MATCH) {
  13830. str = s.strstart - s.insert;
  13831. s.ins_h = s.window[str];
  13832. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  13833. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  13834. //#if MIN_MATCH != 3
  13835. // Call update_hash() MIN_MATCH-3 more times
  13836. //#endif
  13837. while (s.insert) {
  13838. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  13839. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  13840. s.prev[str & s.w_mask] = s.head[s.ins_h];
  13841. s.head[s.ins_h] = str;
  13842. str++;
  13843. s.insert--;
  13844. if (s.lookahead + s.insert < MIN_MATCH) {
  13845. break;
  13846. }
  13847. }
  13848. }
  13849. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  13850. * but this is not important since only literal bytes will be emitted.
  13851. */
  13852. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  13853. /* If the WIN_INIT bytes after the end of the current data have never been
  13854. * written, then zero those bytes in order to avoid memory check reports of
  13855. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  13856. * the longest match routines. Update the high water mark for the next
  13857. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  13858. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  13859. */
  13860. // if (s.high_water < s.window_size) {
  13861. // var curr = s.strstart + s.lookahead;
  13862. // var init = 0;
  13863. //
  13864. // if (s.high_water < curr) {
  13865. // /* Previous high water mark below current data -- zero WIN_INIT
  13866. // * bytes or up to end of window, whichever is less.
  13867. // */
  13868. // init = s.window_size - curr;
  13869. // if (init > WIN_INIT)
  13870. // init = WIN_INIT;
  13871. // zmemzero(s->window + curr, (unsigned)init);
  13872. // s->high_water = curr + init;
  13873. // }
  13874. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  13875. // /* High water mark at or above current data, but below current data
  13876. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  13877. // * to end of window, whichever is less.
  13878. // */
  13879. // init = (ulg)curr + WIN_INIT - s->high_water;
  13880. // if (init > s->window_size - s->high_water)
  13881. // init = s->window_size - s->high_water;
  13882. // zmemzero(s->window + s->high_water, (unsigned)init);
  13883. // s->high_water += init;
  13884. // }
  13885. // }
  13886. //
  13887. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  13888. // "not enough room for search");
  13889. }
  13890. /* ===========================================================================
  13891. * Copy without compression as much as possible from the input stream, return
  13892. * the current block state.
  13893. * This function does not insert new strings in the dictionary since
  13894. * uncompressible data is probably not useful. This function is used
  13895. * only for the level=0 compression option.
  13896. * NOTE: this function should be optimized to avoid extra copying from
  13897. * window to pending_buf.
  13898. */
  13899. function deflate_stored(s, flush) {
  13900. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  13901. * to pending_buf_size, and each stored block has a 5 byte header:
  13902. */
  13903. var max_block_size = 0xffff;
  13904. if (max_block_size > s.pending_buf_size - 5) {
  13905. max_block_size = s.pending_buf_size - 5;
  13906. }
  13907. /* Copy as much as possible from input to output: */
  13908. for (;;) {
  13909. /* Fill the window as much as possible: */
  13910. if (s.lookahead <= 1) {
  13911. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  13912. // s->block_start >= (long)s->w_size, "slide too late");
  13913. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  13914. // s.block_start >= s.w_size)) {
  13915. // throw new Error("slide too late");
  13916. // }
  13917. fill_window(s);
  13918. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  13919. return BS_NEED_MORE;
  13920. }
  13921. if (s.lookahead === 0) {
  13922. break;
  13923. }
  13924. /* flush the current block */
  13925. }
  13926. //Assert(s->block_start >= 0L, "block gone");
  13927. // if (s.block_start < 0) throw new Error("block gone");
  13928. s.strstart += s.lookahead;
  13929. s.lookahead = 0;
  13930. /* Emit a stored block if pending_buf will be full: */
  13931. var max_start = s.block_start + max_block_size;
  13932. if (s.strstart === 0 || s.strstart >= max_start) {
  13933. /* strstart == 0 is possible when wraparound on 16-bit machine */
  13934. s.lookahead = s.strstart - max_start;
  13935. s.strstart = max_start;
  13936. /*** FLUSH_BLOCK(s, 0); ***/
  13937. flush_block_only(s, false);
  13938. if (s.strm.avail_out === 0) {
  13939. return BS_NEED_MORE;
  13940. }
  13941. /***/
  13942. }
  13943. /* Flush if we may have to slide, otherwise block_start may become
  13944. * negative and the data will be gone:
  13945. */
  13946. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  13947. /*** FLUSH_BLOCK(s, 0); ***/
  13948. flush_block_only(s, false);
  13949. if (s.strm.avail_out === 0) {
  13950. return BS_NEED_MORE;
  13951. }
  13952. /***/
  13953. }
  13954. }
  13955. s.insert = 0;
  13956. if (flush === Z_FINISH) {
  13957. /*** FLUSH_BLOCK(s, 1); ***/
  13958. flush_block_only(s, true);
  13959. if (s.strm.avail_out === 0) {
  13960. return BS_FINISH_STARTED;
  13961. }
  13962. /***/
  13963. return BS_FINISH_DONE;
  13964. }
  13965. if (s.strstart > s.block_start) {
  13966. /*** FLUSH_BLOCK(s, 0); ***/
  13967. flush_block_only(s, false);
  13968. if (s.strm.avail_out === 0) {
  13969. return BS_NEED_MORE;
  13970. }
  13971. /***/
  13972. }
  13973. return BS_NEED_MORE;
  13974. }
  13975. /* ===========================================================================
  13976. * Compress as much as possible from the input stream, return the current
  13977. * block state.
  13978. * This function does not perform lazy evaluation of matches and inserts
  13979. * new strings in the dictionary only for unmatched strings or for short
  13980. * matches. It is used only for the fast compression options.
  13981. */
  13982. function deflate_fast(s, flush) {
  13983. var hash_head; /* head of the hash chain */
  13984. var bflush; /* set if current block must be flushed */
  13985. for (;;) {
  13986. /* Make sure that we always have enough lookahead, except
  13987. * at the end of the input file. We need MAX_MATCH bytes
  13988. * for the next match, plus MIN_MATCH bytes to insert the
  13989. * string following the next match.
  13990. */
  13991. if (s.lookahead < MIN_LOOKAHEAD) {
  13992. fill_window(s);
  13993. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  13994. return BS_NEED_MORE;
  13995. }
  13996. if (s.lookahead === 0) {
  13997. break; /* flush the current block */
  13998. }
  13999. }
  14000. /* Insert the string window[strstart .. strstart+2] in the
  14001. * dictionary, and set hash_head to the head of the hash chain:
  14002. */
  14003. hash_head = 0/*NIL*/;
  14004. if (s.lookahead >= MIN_MATCH) {
  14005. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14006. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14007. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14008. s.head[s.ins_h] = s.strstart;
  14009. /***/
  14010. }
  14011. /* Find the longest match, discarding those <= prev_length.
  14012. * At this point we have always match_length < MIN_MATCH
  14013. */
  14014. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14015. /* To simplify the code, we prevent matches with the string
  14016. * of window index 0 (in particular we have to avoid a match
  14017. * of the string with itself at the start of the input file).
  14018. */
  14019. s.match_length = longest_match(s, hash_head);
  14020. /* longest_match() sets match_start */
  14021. }
  14022. if (s.match_length >= MIN_MATCH) {
  14023. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14024. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14025. s.match_length - MIN_MATCH, bflush); ***/
  14026. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14027. s.lookahead -= s.match_length;
  14028. /* Insert new strings in the hash table only if the match length
  14029. * is not too large. This saves time but degrades compression.
  14030. */
  14031. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14032. s.match_length--; /* string at strstart already in table */
  14033. do {
  14034. s.strstart++;
  14035. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14036. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14037. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14038. s.head[s.ins_h] = s.strstart;
  14039. /***/
  14040. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14041. * always MIN_MATCH bytes ahead.
  14042. */
  14043. } while (--s.match_length !== 0);
  14044. s.strstart++;
  14045. } else
  14046. {
  14047. s.strstart += s.match_length;
  14048. s.match_length = 0;
  14049. s.ins_h = s.window[s.strstart];
  14050. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14051. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14052. //#if MIN_MATCH != 3
  14053. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14054. //#endif
  14055. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14056. * matter since it will be recomputed at next deflate call.
  14057. */
  14058. }
  14059. } else {
  14060. /* No match, output a literal byte */
  14061. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14062. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14063. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14064. s.lookahead--;
  14065. s.strstart++;
  14066. }
  14067. if (bflush) {
  14068. /*** FLUSH_BLOCK(s, 0); ***/
  14069. flush_block_only(s, false);
  14070. if (s.strm.avail_out === 0) {
  14071. return BS_NEED_MORE;
  14072. }
  14073. /***/
  14074. }
  14075. }
  14076. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  14077. if (flush === Z_FINISH) {
  14078. /*** FLUSH_BLOCK(s, 1); ***/
  14079. flush_block_only(s, true);
  14080. if (s.strm.avail_out === 0) {
  14081. return BS_FINISH_STARTED;
  14082. }
  14083. /***/
  14084. return BS_FINISH_DONE;
  14085. }
  14086. if (s.last_lit) {
  14087. /*** FLUSH_BLOCK(s, 0); ***/
  14088. flush_block_only(s, false);
  14089. if (s.strm.avail_out === 0) {
  14090. return BS_NEED_MORE;
  14091. }
  14092. /***/
  14093. }
  14094. return BS_BLOCK_DONE;
  14095. }
  14096. /* ===========================================================================
  14097. * Same as above, but achieves better compression. We use a lazy
  14098. * evaluation for matches: a match is finally adopted only if there is
  14099. * no better match at the next window position.
  14100. */
  14101. function deflate_slow(s, flush) {
  14102. var hash_head; /* head of hash chain */
  14103. var bflush; /* set if current block must be flushed */
  14104. var max_insert;
  14105. /* Process the input block. */
  14106. for (;;) {
  14107. /* Make sure that we always have enough lookahead, except
  14108. * at the end of the input file. We need MAX_MATCH bytes
  14109. * for the next match, plus MIN_MATCH bytes to insert the
  14110. * string following the next match.
  14111. */
  14112. if (s.lookahead < MIN_LOOKAHEAD) {
  14113. fill_window(s);
  14114. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14115. return BS_NEED_MORE;
  14116. }
  14117. if (s.lookahead === 0) { break; } /* flush the current block */
  14118. }
  14119. /* Insert the string window[strstart .. strstart+2] in the
  14120. * dictionary, and set hash_head to the head of the hash chain:
  14121. */
  14122. hash_head = 0/*NIL*/;
  14123. if (s.lookahead >= MIN_MATCH) {
  14124. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14125. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14126. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14127. s.head[s.ins_h] = s.strstart;
  14128. /***/
  14129. }
  14130. /* Find the longest match, discarding those <= prev_length.
  14131. */
  14132. s.prev_length = s.match_length;
  14133. s.prev_match = s.match_start;
  14134. s.match_length = MIN_MATCH-1;
  14135. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  14136. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  14137. /* To simplify the code, we prevent matches with the string
  14138. * of window index 0 (in particular we have to avoid a match
  14139. * of the string with itself at the start of the input file).
  14140. */
  14141. s.match_length = longest_match(s, hash_head);
  14142. /* longest_match() sets match_start */
  14143. if (s.match_length <= 5 &&
  14144. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  14145. /* If prev_match is also MIN_MATCH, match_start is garbage
  14146. * but we will ignore the current match anyway.
  14147. */
  14148. s.match_length = MIN_MATCH-1;
  14149. }
  14150. }
  14151. /* If there was a match at the previous step and the current
  14152. * match is not better, output the previous match:
  14153. */
  14154. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  14155. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  14156. /* Do not insert strings in hash table beyond this. */
  14157. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  14158. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  14159. s.prev_length - MIN_MATCH, bflush);***/
  14160. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  14161. /* Insert in hash table all strings up to the end of the match.
  14162. * strstart-1 and strstart are already inserted. If there is not
  14163. * enough lookahead, the last two strings are not inserted in
  14164. * the hash table.
  14165. */
  14166. s.lookahead -= s.prev_length-1;
  14167. s.prev_length -= 2;
  14168. do {
  14169. if (++s.strstart <= max_insert) {
  14170. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14171. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14172. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14173. s.head[s.ins_h] = s.strstart;
  14174. /***/
  14175. }
  14176. } while (--s.prev_length !== 0);
  14177. s.match_available = 0;
  14178. s.match_length = MIN_MATCH-1;
  14179. s.strstart++;
  14180. if (bflush) {
  14181. /*** FLUSH_BLOCK(s, 0); ***/
  14182. flush_block_only(s, false);
  14183. if (s.strm.avail_out === 0) {
  14184. return BS_NEED_MORE;
  14185. }
  14186. /***/
  14187. }
  14188. } else if (s.match_available) {
  14189. /* If there was no match at the previous position, output a
  14190. * single literal. If there was a match but the current match
  14191. * is longer, truncate the previous match to a single literal.
  14192. */
  14193. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14194. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14195. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14196. if (bflush) {
  14197. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  14198. flush_block_only(s, false);
  14199. /***/
  14200. }
  14201. s.strstart++;
  14202. s.lookahead--;
  14203. if (s.strm.avail_out === 0) {
  14204. return BS_NEED_MORE;
  14205. }
  14206. } else {
  14207. /* There is no previous match to compare with, wait for
  14208. * the next step to decide.
  14209. */
  14210. s.match_available = 1;
  14211. s.strstart++;
  14212. s.lookahead--;
  14213. }
  14214. }
  14215. //Assert (flush != Z_NO_FLUSH, "no flush?");
  14216. if (s.match_available) {
  14217. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14218. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14219. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  14220. s.match_available = 0;
  14221. }
  14222. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  14223. if (flush === Z_FINISH) {
  14224. /*** FLUSH_BLOCK(s, 1); ***/
  14225. flush_block_only(s, true);
  14226. if (s.strm.avail_out === 0) {
  14227. return BS_FINISH_STARTED;
  14228. }
  14229. /***/
  14230. return BS_FINISH_DONE;
  14231. }
  14232. if (s.last_lit) {
  14233. /*** FLUSH_BLOCK(s, 0); ***/
  14234. flush_block_only(s, false);
  14235. if (s.strm.avail_out === 0) {
  14236. return BS_NEED_MORE;
  14237. }
  14238. /***/
  14239. }
  14240. return BS_BLOCK_DONE;
  14241. }
  14242. /* ===========================================================================
  14243. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  14244. * one. Do not maintain a hash table. (It will be regenerated if this run of
  14245. * deflate switches away from Z_RLE.)
  14246. */
  14247. function deflate_rle(s, flush) {
  14248. var bflush; /* set if current block must be flushed */
  14249. var prev; /* byte at distance one to match */
  14250. var scan, strend; /* scan goes up to strend for length of run */
  14251. var _win = s.window;
  14252. for (;;) {
  14253. /* Make sure that we always have enough lookahead, except
  14254. * at the end of the input file. We need MAX_MATCH bytes
  14255. * for the longest run, plus one for the unrolled loop.
  14256. */
  14257. if (s.lookahead <= MAX_MATCH) {
  14258. fill_window(s);
  14259. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  14260. return BS_NEED_MORE;
  14261. }
  14262. if (s.lookahead === 0) { break; } /* flush the current block */
  14263. }
  14264. /* See how many times the previous byte repeats */
  14265. s.match_length = 0;
  14266. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  14267. scan = s.strstart - 1;
  14268. prev = _win[scan];
  14269. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  14270. strend = s.strstart + MAX_MATCH;
  14271. do {
  14272. /*jshint noempty:false*/
  14273. } while (prev === _win[++scan] && prev === _win[++scan] &&
  14274. prev === _win[++scan] && prev === _win[++scan] &&
  14275. prev === _win[++scan] && prev === _win[++scan] &&
  14276. prev === _win[++scan] && prev === _win[++scan] &&
  14277. scan < strend);
  14278. s.match_length = MAX_MATCH - (strend - scan);
  14279. if (s.match_length > s.lookahead) {
  14280. s.match_length = s.lookahead;
  14281. }
  14282. }
  14283. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  14284. }
  14285. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  14286. if (s.match_length >= MIN_MATCH) {
  14287. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  14288. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  14289. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  14290. s.lookahead -= s.match_length;
  14291. s.strstart += s.match_length;
  14292. s.match_length = 0;
  14293. } else {
  14294. /* No match, output a literal byte */
  14295. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14296. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14297. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14298. s.lookahead--;
  14299. s.strstart++;
  14300. }
  14301. if (bflush) {
  14302. /*** FLUSH_BLOCK(s, 0); ***/
  14303. flush_block_only(s, false);
  14304. if (s.strm.avail_out === 0) {
  14305. return BS_NEED_MORE;
  14306. }
  14307. /***/
  14308. }
  14309. }
  14310. s.insert = 0;
  14311. if (flush === Z_FINISH) {
  14312. /*** FLUSH_BLOCK(s, 1); ***/
  14313. flush_block_only(s, true);
  14314. if (s.strm.avail_out === 0) {
  14315. return BS_FINISH_STARTED;
  14316. }
  14317. /***/
  14318. return BS_FINISH_DONE;
  14319. }
  14320. if (s.last_lit) {
  14321. /*** FLUSH_BLOCK(s, 0); ***/
  14322. flush_block_only(s, false);
  14323. if (s.strm.avail_out === 0) {
  14324. return BS_NEED_MORE;
  14325. }
  14326. /***/
  14327. }
  14328. return BS_BLOCK_DONE;
  14329. }
  14330. /* ===========================================================================
  14331. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  14332. * (It will be regenerated if this run of deflate switches away from Huffman.)
  14333. */
  14334. function deflate_huff(s, flush) {
  14335. var bflush; /* set if current block must be flushed */
  14336. for (;;) {
  14337. /* Make sure that we have a literal to write. */
  14338. if (s.lookahead === 0) {
  14339. fill_window(s);
  14340. if (s.lookahead === 0) {
  14341. if (flush === Z_NO_FLUSH) {
  14342. return BS_NEED_MORE;
  14343. }
  14344. break; /* flush the current block */
  14345. }
  14346. }
  14347. /* Output a literal byte */
  14348. s.match_length = 0;
  14349. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14350. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14351. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14352. s.lookahead--;
  14353. s.strstart++;
  14354. if (bflush) {
  14355. /*** FLUSH_BLOCK(s, 0); ***/
  14356. flush_block_only(s, false);
  14357. if (s.strm.avail_out === 0) {
  14358. return BS_NEED_MORE;
  14359. }
  14360. /***/
  14361. }
  14362. }
  14363. s.insert = 0;
  14364. if (flush === Z_FINISH) {
  14365. /*** FLUSH_BLOCK(s, 1); ***/
  14366. flush_block_only(s, true);
  14367. if (s.strm.avail_out === 0) {
  14368. return BS_FINISH_STARTED;
  14369. }
  14370. /***/
  14371. return BS_FINISH_DONE;
  14372. }
  14373. if (s.last_lit) {
  14374. /*** FLUSH_BLOCK(s, 0); ***/
  14375. flush_block_only(s, false);
  14376. if (s.strm.avail_out === 0) {
  14377. return BS_NEED_MORE;
  14378. }
  14379. /***/
  14380. }
  14381. return BS_BLOCK_DONE;
  14382. }
  14383. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  14384. * the desired pack level (0..9). The values given below have been tuned to
  14385. * exclude worst case performance for pathological files. Better values may be
  14386. * found for specific files.
  14387. */
  14388. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  14389. this.good_length = good_length;
  14390. this.max_lazy = max_lazy;
  14391. this.nice_length = nice_length;
  14392. this.max_chain = max_chain;
  14393. this.func = func;
  14394. };
  14395. var configuration_table;
  14396. configuration_table = [
  14397. /* good lazy nice chain */
  14398. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  14399. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  14400. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  14401. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  14402. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  14403. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  14404. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  14405. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  14406. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  14407. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  14408. ];
  14409. /* ===========================================================================
  14410. * Initialize the "longest match" routines for a new zlib stream
  14411. */
  14412. function lm_init(s) {
  14413. s.window_size = 2 * s.w_size;
  14414. /*** CLEAR_HASH(s); ***/
  14415. zero(s.head); // Fill with NIL (= 0);
  14416. /* Set the default configuration parameters:
  14417. */
  14418. s.max_lazy_match = configuration_table[s.level].max_lazy;
  14419. s.good_match = configuration_table[s.level].good_length;
  14420. s.nice_match = configuration_table[s.level].nice_length;
  14421. s.max_chain_length = configuration_table[s.level].max_chain;
  14422. s.strstart = 0;
  14423. s.block_start = 0;
  14424. s.lookahead = 0;
  14425. s.insert = 0;
  14426. s.match_length = s.prev_length = MIN_MATCH - 1;
  14427. s.match_available = 0;
  14428. s.ins_h = 0;
  14429. }
  14430. function DeflateState() {
  14431. this.strm = null; /* pointer back to this zlib stream */
  14432. this.status = 0; /* as the name implies */
  14433. this.pending_buf = null; /* output still pending */
  14434. this.pending_buf_size = 0; /* size of pending_buf */
  14435. this.pending_out = 0; /* next pending byte to output to the stream */
  14436. this.pending = 0; /* nb of bytes in the pending buffer */
  14437. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14438. this.gzhead = null; /* gzip header information to write */
  14439. this.gzindex = 0; /* where in extra, name, or comment */
  14440. this.method = Z_DEFLATED; /* can only be DEFLATED */
  14441. this.last_flush = -1; /* value of flush param for previous deflate call */
  14442. this.w_size = 0; /* LZ77 window size (32K by default) */
  14443. this.w_bits = 0; /* log2(w_size) (8..16) */
  14444. this.w_mask = 0; /* w_size - 1 */
  14445. this.window = null;
  14446. /* Sliding window. Input bytes are read into the second half of the window,
  14447. * and move to the first half later to keep a dictionary of at least wSize
  14448. * bytes. With this organization, matches are limited to a distance of
  14449. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  14450. * performed with a length multiple of the block size.
  14451. */
  14452. this.window_size = 0;
  14453. /* Actual size of window: 2*wSize, except when the user input buffer
  14454. * is directly used as sliding window.
  14455. */
  14456. this.prev = null;
  14457. /* Link to older string with same hash index. To limit the size of this
  14458. * array to 64K, this link is maintained only for the last 32K strings.
  14459. * An index in this array is thus a window index modulo 32K.
  14460. */
  14461. this.head = null; /* Heads of the hash chains or NIL. */
  14462. this.ins_h = 0; /* hash index of string to be inserted */
  14463. this.hash_size = 0; /* number of elements in hash table */
  14464. this.hash_bits = 0; /* log2(hash_size) */
  14465. this.hash_mask = 0; /* hash_size-1 */
  14466. this.hash_shift = 0;
  14467. /* Number of bits by which ins_h must be shifted at each input
  14468. * step. It must be such that after MIN_MATCH steps, the oldest
  14469. * byte no longer takes part in the hash key, that is:
  14470. * hash_shift * MIN_MATCH >= hash_bits
  14471. */
  14472. this.block_start = 0;
  14473. /* Window position at the beginning of the current output block. Gets
  14474. * negative when the window is moved backwards.
  14475. */
  14476. this.match_length = 0; /* length of best match */
  14477. this.prev_match = 0; /* previous match */
  14478. this.match_available = 0; /* set if previous match exists */
  14479. this.strstart = 0; /* start of string to insert */
  14480. this.match_start = 0; /* start of matching string */
  14481. this.lookahead = 0; /* number of valid bytes ahead in window */
  14482. this.prev_length = 0;
  14483. /* Length of the best match at previous step. Matches not greater than this
  14484. * are discarded. This is used in the lazy match evaluation.
  14485. */
  14486. this.max_chain_length = 0;
  14487. /* To speed up deflation, hash chains are never searched beyond this
  14488. * length. A higher limit improves compression ratio but degrades the
  14489. * speed.
  14490. */
  14491. this.max_lazy_match = 0;
  14492. /* Attempt to find a better match only when the current match is strictly
  14493. * smaller than this value. This mechanism is used only for compression
  14494. * levels >= 4.
  14495. */
  14496. // That's alias to max_lazy_match, don't use directly
  14497. //this.max_insert_length = 0;
  14498. /* Insert new strings in the hash table only if the match length is not
  14499. * greater than this length. This saves time but degrades compression.
  14500. * max_insert_length is used only for compression levels <= 3.
  14501. */
  14502. this.level = 0; /* compression level (1..9) */
  14503. this.strategy = 0; /* favor or force Huffman coding*/
  14504. this.good_match = 0;
  14505. /* Use a faster search when the previous match is longer than this */
  14506. this.nice_match = 0; /* Stop searching when current match exceeds this */
  14507. /* used by trees.c: */
  14508. /* Didn't use ct_data typedef below to suppress compiler warning */
  14509. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  14510. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  14511. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  14512. // Use flat array of DOUBLE size, with interleaved fata,
  14513. // because JS does not support effective
  14514. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  14515. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  14516. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  14517. zero(this.dyn_ltree);
  14518. zero(this.dyn_dtree);
  14519. zero(this.bl_tree);
  14520. this.l_desc = null; /* desc. for literal tree */
  14521. this.d_desc = null; /* desc. for distance tree */
  14522. this.bl_desc = null; /* desc. for bit length tree */
  14523. //ush bl_count[MAX_BITS+1];
  14524. this.bl_count = new utils.Buf16(MAX_BITS+1);
  14525. /* number of codes at each bit length for an optimal tree */
  14526. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  14527. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  14528. zero(this.heap);
  14529. this.heap_len = 0; /* number of elements in the heap */
  14530. this.heap_max = 0; /* element of largest frequency */
  14531. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  14532. * The same heap array is used to build all trees.
  14533. */
  14534. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  14535. zero(this.depth);
  14536. /* Depth of each subtree used as tie breaker for trees of equal frequency
  14537. */
  14538. this.l_buf = 0; /* buffer index for literals or lengths */
  14539. this.lit_bufsize = 0;
  14540. /* Size of match buffer for literals/lengths. There are 4 reasons for
  14541. * limiting lit_bufsize to 64K:
  14542. * - frequencies can be kept in 16 bit counters
  14543. * - if compression is not successful for the first block, all input
  14544. * data is still in the window so we can still emit a stored block even
  14545. * when input comes from standard input. (This can also be done for
  14546. * all blocks if lit_bufsize is not greater than 32K.)
  14547. * - if compression is not successful for a file smaller than 64K, we can
  14548. * even emit a stored file instead of a stored block (saving 5 bytes).
  14549. * This is applicable only for zip (not gzip or zlib).
  14550. * - creating new Huffman trees less frequently may not provide fast
  14551. * adaptation to changes in the input data statistics. (Take for
  14552. * example a binary file with poorly compressible code followed by
  14553. * a highly compressible string table.) Smaller buffer sizes give
  14554. * fast adaptation but have of course the overhead of transmitting
  14555. * trees more frequently.
  14556. * - I can't count above 4
  14557. */
  14558. this.last_lit = 0; /* running index in l_buf */
  14559. this.d_buf = 0;
  14560. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  14561. * the same number of elements. To use different lengths, an extra flag
  14562. * array would be necessary.
  14563. */
  14564. this.opt_len = 0; /* bit length of current block with optimal trees */
  14565. this.static_len = 0; /* bit length of current block with static trees */
  14566. this.matches = 0; /* number of string matches in current block */
  14567. this.insert = 0; /* bytes at end of window left to insert */
  14568. this.bi_buf = 0;
  14569. /* Output buffer. bits are inserted starting at the bottom (least
  14570. * significant bits).
  14571. */
  14572. this.bi_valid = 0;
  14573. /* Number of valid bits in bi_buf. All bits above the last valid bit
  14574. * are always zero.
  14575. */
  14576. // Used for window memory init. We safely ignore it for JS. That makes
  14577. // sense only for pointers and memory check tools.
  14578. //this.high_water = 0;
  14579. /* High water mark offset in window for initialized bytes -- bytes above
  14580. * this are set to zero in order to avoid memory check warnings when
  14581. * longest match routines access bytes past the input. This is then
  14582. * updated to the new high water mark.
  14583. */
  14584. }
  14585. function deflateResetKeep(strm) {
  14586. var s;
  14587. if (!strm || !strm.state) {
  14588. return err(strm, Z_STREAM_ERROR);
  14589. }
  14590. strm.total_in = strm.total_out = 0;
  14591. strm.data_type = Z_UNKNOWN;
  14592. s = strm.state;
  14593. s.pending = 0;
  14594. s.pending_out = 0;
  14595. if (s.wrap < 0) {
  14596. s.wrap = -s.wrap;
  14597. /* was made negative by deflate(..., Z_FINISH); */
  14598. }
  14599. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  14600. strm.adler = (s.wrap === 2) ?
  14601. 0 // crc32(0, Z_NULL, 0)
  14602. :
  14603. 1; // adler32(0, Z_NULL, 0)
  14604. s.last_flush = Z_NO_FLUSH;
  14605. trees._tr_init(s);
  14606. return Z_OK;
  14607. }
  14608. function deflateReset(strm) {
  14609. var ret = deflateResetKeep(strm);
  14610. if (ret === Z_OK) {
  14611. lm_init(strm.state);
  14612. }
  14613. return ret;
  14614. }
  14615. function deflateSetHeader(strm, head) {
  14616. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14617. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  14618. strm.state.gzhead = head;
  14619. return Z_OK;
  14620. }
  14621. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  14622. if (!strm) { // === Z_NULL
  14623. return Z_STREAM_ERROR;
  14624. }
  14625. var wrap = 1;
  14626. if (level === Z_DEFAULT_COMPRESSION) {
  14627. level = 6;
  14628. }
  14629. if (windowBits < 0) { /* suppress zlib wrapper */
  14630. wrap = 0;
  14631. windowBits = -windowBits;
  14632. }
  14633. else if (windowBits > 15) {
  14634. wrap = 2; /* write gzip wrapper instead */
  14635. windowBits -= 16;
  14636. }
  14637. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  14638. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  14639. strategy < 0 || strategy > Z_FIXED) {
  14640. return err(strm, Z_STREAM_ERROR);
  14641. }
  14642. if (windowBits === 8) {
  14643. windowBits = 9;
  14644. }
  14645. /* until 256-byte window bug fixed */
  14646. var s = new DeflateState();
  14647. strm.state = s;
  14648. s.strm = strm;
  14649. s.wrap = wrap;
  14650. s.gzhead = null;
  14651. s.w_bits = windowBits;
  14652. s.w_size = 1 << s.w_bits;
  14653. s.w_mask = s.w_size - 1;
  14654. s.hash_bits = memLevel + 7;
  14655. s.hash_size = 1 << s.hash_bits;
  14656. s.hash_mask = s.hash_size - 1;
  14657. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  14658. s.window = new utils.Buf8(s.w_size * 2);
  14659. s.head = new utils.Buf16(s.hash_size);
  14660. s.prev = new utils.Buf16(s.w_size);
  14661. // Don't need mem init magic for JS.
  14662. //s.high_water = 0; /* nothing written to s->window yet */
  14663. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  14664. s.pending_buf_size = s.lit_bufsize * 4;
  14665. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  14666. s.d_buf = s.lit_bufsize >> 1;
  14667. s.l_buf = (1 + 2) * s.lit_bufsize;
  14668. s.level = level;
  14669. s.strategy = strategy;
  14670. s.method = method;
  14671. return deflateReset(strm);
  14672. }
  14673. function deflateInit(strm, level) {
  14674. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  14675. }
  14676. function deflate(strm, flush) {
  14677. var old_flush, s;
  14678. var beg, val; // for gzip header write only
  14679. if (!strm || !strm.state ||
  14680. flush > Z_BLOCK || flush < 0) {
  14681. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  14682. }
  14683. s = strm.state;
  14684. if (!strm.output ||
  14685. (!strm.input && strm.avail_in !== 0) ||
  14686. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  14687. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  14688. }
  14689. s.strm = strm; /* just in case */
  14690. old_flush = s.last_flush;
  14691. s.last_flush = flush;
  14692. /* Write the header */
  14693. if (s.status === INIT_STATE) {
  14694. if (s.wrap === 2) { // GZIP header
  14695. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14696. put_byte(s, 31);
  14697. put_byte(s, 139);
  14698. put_byte(s, 8);
  14699. if (!s.gzhead) { // s->gzhead == Z_NULL
  14700. put_byte(s, 0);
  14701. put_byte(s, 0);
  14702. put_byte(s, 0);
  14703. put_byte(s, 0);
  14704. put_byte(s, 0);
  14705. put_byte(s, s.level === 9 ? 2 :
  14706. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14707. 4 : 0));
  14708. put_byte(s, OS_CODE);
  14709. s.status = BUSY_STATE;
  14710. }
  14711. else {
  14712. put_byte(s, (s.gzhead.text ? 1 : 0) +
  14713. (s.gzhead.hcrc ? 2 : 0) +
  14714. (!s.gzhead.extra ? 0 : 4) +
  14715. (!s.gzhead.name ? 0 : 8) +
  14716. (!s.gzhead.comment ? 0 : 16)
  14717. );
  14718. put_byte(s, s.gzhead.time & 0xff);
  14719. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  14720. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  14721. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  14722. put_byte(s, s.level === 9 ? 2 :
  14723. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14724. 4 : 0));
  14725. put_byte(s, s.gzhead.os & 0xff);
  14726. if (s.gzhead.extra && s.gzhead.extra.length) {
  14727. put_byte(s, s.gzhead.extra.length & 0xff);
  14728. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  14729. }
  14730. if (s.gzhead.hcrc) {
  14731. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  14732. }
  14733. s.gzindex = 0;
  14734. s.status = EXTRA_STATE;
  14735. }
  14736. }
  14737. else // DEFLATE header
  14738. {
  14739. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  14740. var level_flags = -1;
  14741. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  14742. level_flags = 0;
  14743. } else if (s.level < 6) {
  14744. level_flags = 1;
  14745. } else if (s.level === 6) {
  14746. level_flags = 2;
  14747. } else {
  14748. level_flags = 3;
  14749. }
  14750. header |= (level_flags << 6);
  14751. if (s.strstart !== 0) { header |= PRESET_DICT; }
  14752. header += 31 - (header % 31);
  14753. s.status = BUSY_STATE;
  14754. putShortMSB(s, header);
  14755. /* Save the adler32 of the preset dictionary: */
  14756. if (s.strstart !== 0) {
  14757. putShortMSB(s, strm.adler >>> 16);
  14758. putShortMSB(s, strm.adler & 0xffff);
  14759. }
  14760. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  14761. }
  14762. }
  14763. //#ifdef GZIP
  14764. if (s.status === EXTRA_STATE) {
  14765. if (s.gzhead.extra/* != Z_NULL*/) {
  14766. beg = s.pending; /* start of bytes to update crc */
  14767. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  14768. if (s.pending === s.pending_buf_size) {
  14769. if (s.gzhead.hcrc && s.pending > beg) {
  14770. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14771. }
  14772. flush_pending(strm);
  14773. beg = s.pending;
  14774. if (s.pending === s.pending_buf_size) {
  14775. break;
  14776. }
  14777. }
  14778. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  14779. s.gzindex++;
  14780. }
  14781. if (s.gzhead.hcrc && s.pending > beg) {
  14782. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14783. }
  14784. if (s.gzindex === s.gzhead.extra.length) {
  14785. s.gzindex = 0;
  14786. s.status = NAME_STATE;
  14787. }
  14788. }
  14789. else {
  14790. s.status = NAME_STATE;
  14791. }
  14792. }
  14793. if (s.status === NAME_STATE) {
  14794. if (s.gzhead.name/* != Z_NULL*/) {
  14795. beg = s.pending; /* start of bytes to update crc */
  14796. //int val;
  14797. do {
  14798. if (s.pending === s.pending_buf_size) {
  14799. if (s.gzhead.hcrc && s.pending > beg) {
  14800. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14801. }
  14802. flush_pending(strm);
  14803. beg = s.pending;
  14804. if (s.pending === s.pending_buf_size) {
  14805. val = 1;
  14806. break;
  14807. }
  14808. }
  14809. // JS specific: little magic to add zero terminator to end of string
  14810. if (s.gzindex < s.gzhead.name.length) {
  14811. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  14812. } else {
  14813. val = 0;
  14814. }
  14815. put_byte(s, val);
  14816. } while (val !== 0);
  14817. if (s.gzhead.hcrc && s.pending > beg) {
  14818. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14819. }
  14820. if (val === 0) {
  14821. s.gzindex = 0;
  14822. s.status = COMMENT_STATE;
  14823. }
  14824. }
  14825. else {
  14826. s.status = COMMENT_STATE;
  14827. }
  14828. }
  14829. if (s.status === COMMENT_STATE) {
  14830. if (s.gzhead.comment/* != Z_NULL*/) {
  14831. beg = s.pending; /* start of bytes to update crc */
  14832. //int val;
  14833. do {
  14834. if (s.pending === s.pending_buf_size) {
  14835. if (s.gzhead.hcrc && s.pending > beg) {
  14836. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14837. }
  14838. flush_pending(strm);
  14839. beg = s.pending;
  14840. if (s.pending === s.pending_buf_size) {
  14841. val = 1;
  14842. break;
  14843. }
  14844. }
  14845. // JS specific: little magic to add zero terminator to end of string
  14846. if (s.gzindex < s.gzhead.comment.length) {
  14847. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  14848. } else {
  14849. val = 0;
  14850. }
  14851. put_byte(s, val);
  14852. } while (val !== 0);
  14853. if (s.gzhead.hcrc && s.pending > beg) {
  14854. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  14855. }
  14856. if (val === 0) {
  14857. s.status = HCRC_STATE;
  14858. }
  14859. }
  14860. else {
  14861. s.status = HCRC_STATE;
  14862. }
  14863. }
  14864. if (s.status === HCRC_STATE) {
  14865. if (s.gzhead.hcrc) {
  14866. if (s.pending + 2 > s.pending_buf_size) {
  14867. flush_pending(strm);
  14868. }
  14869. if (s.pending + 2 <= s.pending_buf_size) {
  14870. put_byte(s, strm.adler & 0xff);
  14871. put_byte(s, (strm.adler >> 8) & 0xff);
  14872. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14873. s.status = BUSY_STATE;
  14874. }
  14875. }
  14876. else {
  14877. s.status = BUSY_STATE;
  14878. }
  14879. }
  14880. //#endif
  14881. /* Flush as much pending output as possible */
  14882. if (s.pending !== 0) {
  14883. flush_pending(strm);
  14884. if (strm.avail_out === 0) {
  14885. /* Since avail_out is 0, deflate will be called again with
  14886. * more output space, but possibly with both pending and
  14887. * avail_in equal to zero. There won't be anything to do,
  14888. * but this is not an error situation so make sure we
  14889. * return OK instead of BUF_ERROR at next call of deflate:
  14890. */
  14891. s.last_flush = -1;
  14892. return Z_OK;
  14893. }
  14894. /* Make sure there is something to do and avoid duplicate consecutive
  14895. * flushes. For repeated and useless calls with Z_FINISH, we keep
  14896. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  14897. */
  14898. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  14899. flush !== Z_FINISH) {
  14900. return err(strm, Z_BUF_ERROR);
  14901. }
  14902. /* User must not provide more input after the first FINISH: */
  14903. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  14904. return err(strm, Z_BUF_ERROR);
  14905. }
  14906. /* Start a new block or continue the current one.
  14907. */
  14908. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  14909. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  14910. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  14911. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  14912. configuration_table[s.level].func(s, flush));
  14913. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  14914. s.status = FINISH_STATE;
  14915. }
  14916. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  14917. if (strm.avail_out === 0) {
  14918. s.last_flush = -1;
  14919. /* avoid BUF_ERROR next call, see above */
  14920. }
  14921. return Z_OK;
  14922. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  14923. * of deflate should use the same flush parameter to make sure
  14924. * that the flush is complete. So we don't have to output an
  14925. * empty block here, this will be done at next call. This also
  14926. * ensures that for a very small output buffer, we emit at most
  14927. * one empty block.
  14928. */
  14929. }
  14930. if (bstate === BS_BLOCK_DONE) {
  14931. if (flush === Z_PARTIAL_FLUSH) {
  14932. trees._tr_align(s);
  14933. }
  14934. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  14935. trees._tr_stored_block(s, 0, 0, false);
  14936. /* For a full flush, this empty block will be recognized
  14937. * as a special marker by inflate_sync().
  14938. */
  14939. if (flush === Z_FULL_FLUSH) {
  14940. /*** CLEAR_HASH(s); ***/ /* forget history */
  14941. zero(s.head); // Fill with NIL (= 0);
  14942. if (s.lookahead === 0) {
  14943. s.strstart = 0;
  14944. s.block_start = 0;
  14945. s.insert = 0;
  14946. }
  14947. }
  14948. }
  14949. flush_pending(strm);
  14950. if (strm.avail_out === 0) {
  14951. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  14952. return Z_OK;
  14953. }
  14954. }
  14955. }
  14956. //Assert(strm->avail_out > 0, "bug2");
  14957. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  14958. if (flush !== Z_FINISH) { return Z_OK; }
  14959. if (s.wrap <= 0) { return Z_STREAM_END; }
  14960. /* Write the trailer */
  14961. if (s.wrap === 2) {
  14962. put_byte(s, strm.adler & 0xff);
  14963. put_byte(s, (strm.adler >> 8) & 0xff);
  14964. put_byte(s, (strm.adler >> 16) & 0xff);
  14965. put_byte(s, (strm.adler >> 24) & 0xff);
  14966. put_byte(s, strm.total_in & 0xff);
  14967. put_byte(s, (strm.total_in >> 8) & 0xff);
  14968. put_byte(s, (strm.total_in >> 16) & 0xff);
  14969. put_byte(s, (strm.total_in >> 24) & 0xff);
  14970. }
  14971. else
  14972. {
  14973. putShortMSB(s, strm.adler >>> 16);
  14974. putShortMSB(s, strm.adler & 0xffff);
  14975. }
  14976. flush_pending(strm);
  14977. /* If avail_out is zero, the application will call deflate again
  14978. * to flush the rest.
  14979. */
  14980. if (s.wrap > 0) { s.wrap = -s.wrap; }
  14981. /* write the trailer only once! */
  14982. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  14983. }
  14984. function deflateEnd(strm) {
  14985. var status;
  14986. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  14987. return Z_STREAM_ERROR;
  14988. }
  14989. status = strm.state.status;
  14990. if (status !== INIT_STATE &&
  14991. status !== EXTRA_STATE &&
  14992. status !== NAME_STATE &&
  14993. status !== COMMENT_STATE &&
  14994. status !== HCRC_STATE &&
  14995. status !== BUSY_STATE &&
  14996. status !== FINISH_STATE
  14997. ) {
  14998. return err(strm, Z_STREAM_ERROR);
  14999. }
  15000. strm.state = null;
  15001. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15002. }
  15003. /* =========================================================================
  15004. * Copy the source state to the destination state
  15005. */
  15006. //function deflateCopy(dest, source) {
  15007. //
  15008. //}
  15009. exports.deflateInit = deflateInit;
  15010. exports.deflateInit2 = deflateInit2;
  15011. exports.deflateReset = deflateReset;
  15012. exports.deflateResetKeep = deflateResetKeep;
  15013. exports.deflateSetHeader = deflateSetHeader;
  15014. exports.deflate = deflate;
  15015. exports.deflateEnd = deflateEnd;
  15016. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15017. /* Not implemented
  15018. exports.deflateBound = deflateBound;
  15019. exports.deflateCopy = deflateCopy;
  15020. exports.deflateSetDictionary = deflateSetDictionary;
  15021. exports.deflateParams = deflateParams;
  15022. exports.deflatePending = deflatePending;
  15023. exports.deflatePrime = deflatePrime;
  15024. exports.deflateTune = deflateTune;
  15025. */
  15026. },{"../utils/common":49,"./adler32":51,"./crc32":53,"./messages":59,"./trees":60}],55:[function(require,module,exports){
  15027. 'use strict';
  15028. function GZheader() {
  15029. /* true if compressed data believed to be text */
  15030. this.text = 0;
  15031. /* modification time */
  15032. this.time = 0;
  15033. /* extra flags (not used when writing a gzip file) */
  15034. this.xflags = 0;
  15035. /* operating system */
  15036. this.os = 0;
  15037. /* pointer to extra field or Z_NULL if none */
  15038. this.extra = null;
  15039. /* extra field length (valid if extra != Z_NULL) */
  15040. this.extra_len = 0; // Actually, we don't need it in JS,
  15041. // but leave for few code modifications
  15042. //
  15043. // Setup limits is not necessary because in js we should not preallocate memory
  15044. // for inflate use constant limit in 65536 bytes
  15045. //
  15046. /* space at extra (only when reading header) */
  15047. // this.extra_max = 0;
  15048. /* pointer to zero-terminated file name or Z_NULL */
  15049. this.name = '';
  15050. /* space at name (only when reading header) */
  15051. // this.name_max = 0;
  15052. /* pointer to zero-terminated comment or Z_NULL */
  15053. this.comment = '';
  15054. /* space at comment (only when reading header) */
  15055. // this.comm_max = 0;
  15056. /* true if there was or will be a header crc */
  15057. this.hcrc = 0;
  15058. /* true when done reading gzip header (not used when writing a gzip file) */
  15059. this.done = false;
  15060. }
  15061. module.exports = GZheader;
  15062. },{}],56:[function(require,module,exports){
  15063. 'use strict';
  15064. // See state defs from inflate.js
  15065. var BAD = 30; /* got a data error -- remain here until reset */
  15066. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15067. /*
  15068. Decode literal, length, and distance codes and write out the resulting
  15069. literal and match bytes until either not enough input or output is
  15070. available, an end-of-block is encountered, or a data error is encountered.
  15071. When large enough input and output buffers are supplied to inflate(), for
  15072. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  15073. inflate execution time is spent in this routine.
  15074. Entry assumptions:
  15075. state.mode === LEN
  15076. strm.avail_in >= 6
  15077. strm.avail_out >= 258
  15078. start >= strm.avail_out
  15079. state.bits < 8
  15080. On return, state.mode is one of:
  15081. LEN -- ran out of enough output space or enough available input
  15082. TYPE -- reached end of block code, inflate() to interpret next block
  15083. BAD -- error in block data
  15084. Notes:
  15085. - The maximum input bits used by a length/distance pair is 15 bits for the
  15086. length code, 5 bits for the length extra, 15 bits for the distance code,
  15087. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  15088. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  15089. checking for available input while decoding.
  15090. - The maximum bytes that a single length/distance pair can output is 258
  15091. bytes, which is the maximum length that can be coded. inflate_fast()
  15092. requires strm.avail_out >= 258 for each loop to avoid checking for
  15093. output space.
  15094. */
  15095. module.exports = function inflate_fast(strm, start) {
  15096. var state;
  15097. var _in; /* local strm.input */
  15098. var last; /* have enough input while in < last */
  15099. var _out; /* local strm.output */
  15100. var beg; /* inflate()'s initial strm.output */
  15101. var end; /* while out < end, enough space available */
  15102. //#ifdef INFLATE_STRICT
  15103. var dmax; /* maximum distance from zlib header */
  15104. //#endif
  15105. var wsize; /* window size or zero if not using window */
  15106. var whave; /* valid bytes in the window */
  15107. var wnext; /* window write index */
  15108. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  15109. var s_window; /* allocated sliding window, if wsize != 0 */
  15110. var hold; /* local strm.hold */
  15111. var bits; /* local strm.bits */
  15112. var lcode; /* local strm.lencode */
  15113. var dcode; /* local strm.distcode */
  15114. var lmask; /* mask for first level of length codes */
  15115. var dmask; /* mask for first level of distance codes */
  15116. var here; /* retrieved table entry */
  15117. var op; /* code bits, operation, extra bits, or */
  15118. /* window position, window bytes to copy */
  15119. var len; /* match length, unused bytes */
  15120. var dist; /* match distance */
  15121. var from; /* where to copy match from */
  15122. var from_source;
  15123. var input, output; // JS specific, because we have no pointers
  15124. /* copy state to local variables */
  15125. state = strm.state;
  15126. //here = state.here;
  15127. _in = strm.next_in;
  15128. input = strm.input;
  15129. last = _in + (strm.avail_in - 5);
  15130. _out = strm.next_out;
  15131. output = strm.output;
  15132. beg = _out - (start - strm.avail_out);
  15133. end = _out + (strm.avail_out - 257);
  15134. //#ifdef INFLATE_STRICT
  15135. dmax = state.dmax;
  15136. //#endif
  15137. wsize = state.wsize;
  15138. whave = state.whave;
  15139. wnext = state.wnext;
  15140. s_window = state.window;
  15141. hold = state.hold;
  15142. bits = state.bits;
  15143. lcode = state.lencode;
  15144. dcode = state.distcode;
  15145. lmask = (1 << state.lenbits) - 1;
  15146. dmask = (1 << state.distbits) - 1;
  15147. /* decode literals and length/distances until end-of-block or not enough
  15148. input data or output space */
  15149. top:
  15150. do {
  15151. if (bits < 15) {
  15152. hold += input[_in++] << bits;
  15153. bits += 8;
  15154. hold += input[_in++] << bits;
  15155. bits += 8;
  15156. }
  15157. here = lcode[hold & lmask];
  15158. dolen:
  15159. for (;;) { // Goto emulation
  15160. op = here >>> 24/*here.bits*/;
  15161. hold >>>= op;
  15162. bits -= op;
  15163. op = (here >>> 16) & 0xff/*here.op*/;
  15164. if (op === 0) { /* literal */
  15165. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15166. // "inflate: literal '%c'\n" :
  15167. // "inflate: literal 0x%02x\n", here.val));
  15168. output[_out++] = here & 0xffff/*here.val*/;
  15169. }
  15170. else if (op & 16) { /* length base */
  15171. len = here & 0xffff/*here.val*/;
  15172. op &= 15; /* number of extra bits */
  15173. if (op) {
  15174. if (bits < op) {
  15175. hold += input[_in++] << bits;
  15176. bits += 8;
  15177. }
  15178. len += hold & ((1 << op) - 1);
  15179. hold >>>= op;
  15180. bits -= op;
  15181. }
  15182. //Tracevv((stderr, "inflate: length %u\n", len));
  15183. if (bits < 15) {
  15184. hold += input[_in++] << bits;
  15185. bits += 8;
  15186. hold += input[_in++] << bits;
  15187. bits += 8;
  15188. }
  15189. here = dcode[hold & dmask];
  15190. dodist:
  15191. for (;;) { // goto emulation
  15192. op = here >>> 24/*here.bits*/;
  15193. hold >>>= op;
  15194. bits -= op;
  15195. op = (here >>> 16) & 0xff/*here.op*/;
  15196. if (op & 16) { /* distance base */
  15197. dist = here & 0xffff/*here.val*/;
  15198. op &= 15; /* number of extra bits */
  15199. if (bits < op) {
  15200. hold += input[_in++] << bits;
  15201. bits += 8;
  15202. if (bits < op) {
  15203. hold += input[_in++] << bits;
  15204. bits += 8;
  15205. }
  15206. }
  15207. dist += hold & ((1 << op) - 1);
  15208. //#ifdef INFLATE_STRICT
  15209. if (dist > dmax) {
  15210. strm.msg = 'invalid distance too far back';
  15211. state.mode = BAD;
  15212. break top;
  15213. }
  15214. //#endif
  15215. hold >>>= op;
  15216. bits -= op;
  15217. //Tracevv((stderr, "inflate: distance %u\n", dist));
  15218. op = _out - beg; /* max distance in output */
  15219. if (dist > op) { /* see if copy from window */
  15220. op = dist - op; /* distance back in window */
  15221. if (op > whave) {
  15222. if (state.sane) {
  15223. strm.msg = 'invalid distance too far back';
  15224. state.mode = BAD;
  15225. break top;
  15226. }
  15227. // (!) This block is disabled in zlib defailts,
  15228. // don't enable it for binary compatibility
  15229. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15230. // if (len <= op - whave) {
  15231. // do {
  15232. // output[_out++] = 0;
  15233. // } while (--len);
  15234. // continue top;
  15235. // }
  15236. // len -= op - whave;
  15237. // do {
  15238. // output[_out++] = 0;
  15239. // } while (--op > whave);
  15240. // if (op === 0) {
  15241. // from = _out - dist;
  15242. // do {
  15243. // output[_out++] = output[from++];
  15244. // } while (--len);
  15245. // continue top;
  15246. // }
  15247. //#endif
  15248. }
  15249. from = 0; // window index
  15250. from_source = s_window;
  15251. if (wnext === 0) { /* very common case */
  15252. from += wsize - op;
  15253. if (op < len) { /* some from window */
  15254. len -= op;
  15255. do {
  15256. output[_out++] = s_window[from++];
  15257. } while (--op);
  15258. from = _out - dist; /* rest from output */
  15259. from_source = output;
  15260. }
  15261. }
  15262. else if (wnext < op) { /* wrap around window */
  15263. from += wsize + wnext - op;
  15264. op -= wnext;
  15265. if (op < len) { /* some from end of window */
  15266. len -= op;
  15267. do {
  15268. output[_out++] = s_window[from++];
  15269. } while (--op);
  15270. from = 0;
  15271. if (wnext < len) { /* some from start of window */
  15272. op = wnext;
  15273. len -= op;
  15274. do {
  15275. output[_out++] = s_window[from++];
  15276. } while (--op);
  15277. from = _out - dist; /* rest from output */
  15278. from_source = output;
  15279. }
  15280. }
  15281. }
  15282. else { /* contiguous in window */
  15283. from += wnext - op;
  15284. if (op < len) { /* some from window */
  15285. len -= op;
  15286. do {
  15287. output[_out++] = s_window[from++];
  15288. } while (--op);
  15289. from = _out - dist; /* rest from output */
  15290. from_source = output;
  15291. }
  15292. }
  15293. while (len > 2) {
  15294. output[_out++] = from_source[from++];
  15295. output[_out++] = from_source[from++];
  15296. output[_out++] = from_source[from++];
  15297. len -= 3;
  15298. }
  15299. if (len) {
  15300. output[_out++] = from_source[from++];
  15301. if (len > 1) {
  15302. output[_out++] = from_source[from++];
  15303. }
  15304. }
  15305. }
  15306. else {
  15307. from = _out - dist; /* copy direct from output */
  15308. do { /* minimum length is three */
  15309. output[_out++] = output[from++];
  15310. output[_out++] = output[from++];
  15311. output[_out++] = output[from++];
  15312. len -= 3;
  15313. } while (len > 2);
  15314. if (len) {
  15315. output[_out++] = output[from++];
  15316. if (len > 1) {
  15317. output[_out++] = output[from++];
  15318. }
  15319. }
  15320. }
  15321. }
  15322. else if ((op & 64) === 0) { /* 2nd level distance code */
  15323. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15324. continue dodist;
  15325. }
  15326. else {
  15327. strm.msg = 'invalid distance code';
  15328. state.mode = BAD;
  15329. break top;
  15330. }
  15331. break; // need to emulate goto via "continue"
  15332. }
  15333. }
  15334. else if ((op & 64) === 0) { /* 2nd level length code */
  15335. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15336. continue dolen;
  15337. }
  15338. else if (op & 32) { /* end-of-block */
  15339. //Tracevv((stderr, "inflate: end of block\n"));
  15340. state.mode = TYPE;
  15341. break top;
  15342. }
  15343. else {
  15344. strm.msg = 'invalid literal/length code';
  15345. state.mode = BAD;
  15346. break top;
  15347. }
  15348. break; // need to emulate goto via "continue"
  15349. }
  15350. } while (_in < last && _out < end);
  15351. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  15352. len = bits >> 3;
  15353. _in -= len;
  15354. bits -= len << 3;
  15355. hold &= (1 << bits) - 1;
  15356. /* update state and return */
  15357. strm.next_in = _in;
  15358. strm.next_out = _out;
  15359. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  15360. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  15361. state.hold = hold;
  15362. state.bits = bits;
  15363. return;
  15364. };
  15365. },{}],57:[function(require,module,exports){
  15366. 'use strict';
  15367. var utils = require('../utils/common');
  15368. var adler32 = require('./adler32');
  15369. var crc32 = require('./crc32');
  15370. var inflate_fast = require('./inffast');
  15371. var inflate_table = require('./inftrees');
  15372. var CODES = 0;
  15373. var LENS = 1;
  15374. var DISTS = 2;
  15375. /* Public constants ==========================================================*/
  15376. /* ===========================================================================*/
  15377. /* Allowed flush values; see deflate() and inflate() below for details */
  15378. //var Z_NO_FLUSH = 0;
  15379. //var Z_PARTIAL_FLUSH = 1;
  15380. //var Z_SYNC_FLUSH = 2;
  15381. //var Z_FULL_FLUSH = 3;
  15382. var Z_FINISH = 4;
  15383. var Z_BLOCK = 5;
  15384. var Z_TREES = 6;
  15385. /* Return codes for the compression/decompression functions. Negative values
  15386. * are errors, positive values are used for special but normal events.
  15387. */
  15388. var Z_OK = 0;
  15389. var Z_STREAM_END = 1;
  15390. var Z_NEED_DICT = 2;
  15391. //var Z_ERRNO = -1;
  15392. var Z_STREAM_ERROR = -2;
  15393. var Z_DATA_ERROR = -3;
  15394. var Z_MEM_ERROR = -4;
  15395. var Z_BUF_ERROR = -5;
  15396. //var Z_VERSION_ERROR = -6;
  15397. /* The deflate compression method */
  15398. var Z_DEFLATED = 8;
  15399. /* STATES ====================================================================*/
  15400. /* ===========================================================================*/
  15401. var HEAD = 1; /* i: waiting for magic header */
  15402. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  15403. var TIME = 3; /* i: waiting for modification time (gzip) */
  15404. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  15405. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  15406. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  15407. var NAME = 7; /* i: waiting for end of file name (gzip) */
  15408. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  15409. var HCRC = 9; /* i: waiting for header crc (gzip) */
  15410. var DICTID = 10; /* i: waiting for dictionary check value */
  15411. var DICT = 11; /* waiting for inflateSetDictionary() call */
  15412. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15413. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  15414. var STORED = 14; /* i: waiting for stored size (length and complement) */
  15415. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  15416. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  15417. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  15418. var LENLENS = 18; /* i: waiting for code length code lengths */
  15419. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  15420. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  15421. var LEN = 21; /* i: waiting for length/lit/eob code */
  15422. var LENEXT = 22; /* i: waiting for length extra bits */
  15423. var DIST = 23; /* i: waiting for distance code */
  15424. var DISTEXT = 24; /* i: waiting for distance extra bits */
  15425. var MATCH = 25; /* o: waiting for output space to copy string */
  15426. var LIT = 26; /* o: waiting for output space to write literal */
  15427. var CHECK = 27; /* i: waiting for 32-bit check value */
  15428. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  15429. var DONE = 29; /* finished check, done -- remain here until reset */
  15430. var BAD = 30; /* got a data error -- remain here until reset */
  15431. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  15432. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  15433. /* ===========================================================================*/
  15434. var ENOUGH_LENS = 852;
  15435. var ENOUGH_DISTS = 592;
  15436. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15437. var MAX_WBITS = 15;
  15438. /* 32K LZ77 window */
  15439. var DEF_WBITS = MAX_WBITS;
  15440. function ZSWAP32(q) {
  15441. return (((q >>> 24) & 0xff) +
  15442. ((q >>> 8) & 0xff00) +
  15443. ((q & 0xff00) << 8) +
  15444. ((q & 0xff) << 24));
  15445. }
  15446. function InflateState() {
  15447. this.mode = 0; /* current inflate mode */
  15448. this.last = false; /* true if processing last block */
  15449. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15450. this.havedict = false; /* true if dictionary provided */
  15451. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  15452. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  15453. this.check = 0; /* protected copy of check value */
  15454. this.total = 0; /* protected copy of output count */
  15455. // TODO: may be {}
  15456. this.head = null; /* where to save gzip header information */
  15457. /* sliding window */
  15458. this.wbits = 0; /* log base 2 of requested window size */
  15459. this.wsize = 0; /* window size or zero if not using window */
  15460. this.whave = 0; /* valid bytes in the window */
  15461. this.wnext = 0; /* window write index */
  15462. this.window = null; /* allocated sliding window, if needed */
  15463. /* bit accumulator */
  15464. this.hold = 0; /* input bit accumulator */
  15465. this.bits = 0; /* number of bits in "in" */
  15466. /* for string and stored block copying */
  15467. this.length = 0; /* literal or length of data to copy */
  15468. this.offset = 0; /* distance back to copy string from */
  15469. /* for table and code decoding */
  15470. this.extra = 0; /* extra bits needed */
  15471. /* fixed and dynamic code tables */
  15472. this.lencode = null; /* starting table for length/literal codes */
  15473. this.distcode = null; /* starting table for distance codes */
  15474. this.lenbits = 0; /* index bits for lencode */
  15475. this.distbits = 0; /* index bits for distcode */
  15476. /* dynamic table building */
  15477. this.ncode = 0; /* number of code length code lengths */
  15478. this.nlen = 0; /* number of length code lengths */
  15479. this.ndist = 0; /* number of distance code lengths */
  15480. this.have = 0; /* number of code lengths in lens[] */
  15481. this.next = null; /* next available space in codes[] */
  15482. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  15483. this.work = new utils.Buf16(288); /* work area for code table building */
  15484. /*
  15485. because we don't have pointers in js, we use lencode and distcode directly
  15486. as buffers so we don't need codes
  15487. */
  15488. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  15489. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  15490. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  15491. this.sane = 0; /* if false, allow invalid distance too far */
  15492. this.back = 0; /* bits back of last unprocessed length/lit */
  15493. this.was = 0; /* initial length of match */
  15494. }
  15495. function inflateResetKeep(strm) {
  15496. var state;
  15497. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15498. state = strm.state;
  15499. strm.total_in = strm.total_out = state.total = 0;
  15500. strm.msg = ''; /*Z_NULL*/
  15501. if (state.wrap) { /* to support ill-conceived Java test suite */
  15502. strm.adler = state.wrap & 1;
  15503. }
  15504. state.mode = HEAD;
  15505. state.last = 0;
  15506. state.havedict = 0;
  15507. state.dmax = 32768;
  15508. state.head = null/*Z_NULL*/;
  15509. state.hold = 0;
  15510. state.bits = 0;
  15511. //state.lencode = state.distcode = state.next = state.codes;
  15512. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  15513. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  15514. state.sane = 1;
  15515. state.back = -1;
  15516. //Tracev((stderr, "inflate: reset\n"));
  15517. return Z_OK;
  15518. }
  15519. function inflateReset(strm) {
  15520. var state;
  15521. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15522. state = strm.state;
  15523. state.wsize = 0;
  15524. state.whave = 0;
  15525. state.wnext = 0;
  15526. return inflateResetKeep(strm);
  15527. }
  15528. function inflateReset2(strm, windowBits) {
  15529. var wrap;
  15530. var state;
  15531. /* get the state */
  15532. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15533. state = strm.state;
  15534. /* extract wrap request from windowBits parameter */
  15535. if (windowBits < 0) {
  15536. wrap = 0;
  15537. windowBits = -windowBits;
  15538. }
  15539. else {
  15540. wrap = (windowBits >> 4) + 1;
  15541. if (windowBits < 48) {
  15542. windowBits &= 15;
  15543. }
  15544. }
  15545. /* set number of window bits, free window if different */
  15546. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  15547. return Z_STREAM_ERROR;
  15548. }
  15549. if (state.window !== null && state.wbits !== windowBits) {
  15550. state.window = null;
  15551. }
  15552. /* update state and reset the rest of it */
  15553. state.wrap = wrap;
  15554. state.wbits = windowBits;
  15555. return inflateReset(strm);
  15556. }
  15557. function inflateInit2(strm, windowBits) {
  15558. var ret;
  15559. var state;
  15560. if (!strm) { return Z_STREAM_ERROR; }
  15561. //strm.msg = Z_NULL; /* in case we return an error */
  15562. state = new InflateState();
  15563. //if (state === Z_NULL) return Z_MEM_ERROR;
  15564. //Tracev((stderr, "inflate: allocated\n"));
  15565. strm.state = state;
  15566. state.window = null/*Z_NULL*/;
  15567. ret = inflateReset2(strm, windowBits);
  15568. if (ret !== Z_OK) {
  15569. strm.state = null/*Z_NULL*/;
  15570. }
  15571. return ret;
  15572. }
  15573. function inflateInit(strm) {
  15574. return inflateInit2(strm, DEF_WBITS);
  15575. }
  15576. /*
  15577. Return state with length and distance decoding tables and index sizes set to
  15578. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  15579. If BUILDFIXED is defined, then instead this routine builds the tables the
  15580. first time it's called, and returns those tables the first time and
  15581. thereafter. This reduces the size of the code by about 2K bytes, in
  15582. exchange for a little execution time. However, BUILDFIXED should not be
  15583. used for threaded applications, since the rewriting of the tables and virgin
  15584. may not be thread-safe.
  15585. */
  15586. var virgin = true;
  15587. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  15588. function fixedtables(state) {
  15589. /* build fixed huffman tables if first call (may not be thread safe) */
  15590. if (virgin) {
  15591. var sym;
  15592. lenfix = new utils.Buf32(512);
  15593. distfix = new utils.Buf32(32);
  15594. /* literal/length table */
  15595. sym = 0;
  15596. while (sym < 144) { state.lens[sym++] = 8; }
  15597. while (sym < 256) { state.lens[sym++] = 9; }
  15598. while (sym < 280) { state.lens[sym++] = 7; }
  15599. while (sym < 288) { state.lens[sym++] = 8; }
  15600. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  15601. /* distance table */
  15602. sym = 0;
  15603. while (sym < 32) { state.lens[sym++] = 5; }
  15604. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  15605. /* do this just once */
  15606. virgin = false;
  15607. }
  15608. state.lencode = lenfix;
  15609. state.lenbits = 9;
  15610. state.distcode = distfix;
  15611. state.distbits = 5;
  15612. }
  15613. /*
  15614. Update the window with the last wsize (normally 32K) bytes written before
  15615. returning. If window does not exist yet, create it. This is only called
  15616. when a window is already in use, or when output has been written during this
  15617. inflate call, but the end of the deflate stream has not been reached yet.
  15618. It is also called to create a window for dictionary data when a dictionary
  15619. is loaded.
  15620. Providing output buffers larger than 32K to inflate() should provide a speed
  15621. advantage, since only the last 32K of output is copied to the sliding window
  15622. upon return from inflate(), and since all distances after the first 32K of
  15623. output will fall in the output data, making match copies simpler and faster.
  15624. The advantage may be dependent on the size of the processor's data caches.
  15625. */
  15626. function updatewindow(strm, src, end, copy) {
  15627. var dist;
  15628. var state = strm.state;
  15629. /* if it hasn't been done already, allocate space for the window */
  15630. if (state.window === null) {
  15631. state.wsize = 1 << state.wbits;
  15632. state.wnext = 0;
  15633. state.whave = 0;
  15634. state.window = new utils.Buf8(state.wsize);
  15635. }
  15636. /* copy state->wsize or less output bytes into the circular window */
  15637. if (copy >= state.wsize) {
  15638. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  15639. state.wnext = 0;
  15640. state.whave = state.wsize;
  15641. }
  15642. else {
  15643. dist = state.wsize - state.wnext;
  15644. if (dist > copy) {
  15645. dist = copy;
  15646. }
  15647. //zmemcpy(state->window + state->wnext, end - copy, dist);
  15648. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  15649. copy -= dist;
  15650. if (copy) {
  15651. //zmemcpy(state->window, end - copy, copy);
  15652. utils.arraySet(state.window,src, end - copy, copy, 0);
  15653. state.wnext = copy;
  15654. state.whave = state.wsize;
  15655. }
  15656. else {
  15657. state.wnext += dist;
  15658. if (state.wnext === state.wsize) { state.wnext = 0; }
  15659. if (state.whave < state.wsize) { state.whave += dist; }
  15660. }
  15661. }
  15662. return 0;
  15663. }
  15664. function inflate(strm, flush) {
  15665. var state;
  15666. var input, output; // input/output buffers
  15667. var next; /* next input INDEX */
  15668. var put; /* next output INDEX */
  15669. var have, left; /* available input and output */
  15670. var hold; /* bit buffer */
  15671. var bits; /* bits in bit buffer */
  15672. var _in, _out; /* save starting available input and output */
  15673. var copy; /* number of stored or match bytes to copy */
  15674. var from; /* where to copy match bytes from */
  15675. var from_source;
  15676. var here = 0; /* current decoding table entry */
  15677. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  15678. //var last; /* parent table entry */
  15679. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  15680. var len; /* length to copy for repeats, bits to drop */
  15681. var ret; /* return code */
  15682. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  15683. var opts;
  15684. var n; // temporary var for NEED_BITS
  15685. var order = /* permutation of code lengths */
  15686. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  15687. if (!strm || !strm.state || !strm.output ||
  15688. (!strm.input && strm.avail_in !== 0)) {
  15689. return Z_STREAM_ERROR;
  15690. }
  15691. state = strm.state;
  15692. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  15693. //--- LOAD() ---
  15694. put = strm.next_out;
  15695. output = strm.output;
  15696. left = strm.avail_out;
  15697. next = strm.next_in;
  15698. input = strm.input;
  15699. have = strm.avail_in;
  15700. hold = state.hold;
  15701. bits = state.bits;
  15702. //---
  15703. _in = have;
  15704. _out = left;
  15705. ret = Z_OK;
  15706. inf_leave: // goto emulation
  15707. for (;;) {
  15708. switch (state.mode) {
  15709. case HEAD:
  15710. if (state.wrap === 0) {
  15711. state.mode = TYPEDO;
  15712. break;
  15713. }
  15714. //=== NEEDBITS(16);
  15715. while (bits < 16) {
  15716. if (have === 0) { break inf_leave; }
  15717. have--;
  15718. hold += input[next++] << bits;
  15719. bits += 8;
  15720. }
  15721. //===//
  15722. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  15723. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  15724. //=== CRC2(state.check, hold);
  15725. hbuf[0] = hold & 0xff;
  15726. hbuf[1] = (hold >>> 8) & 0xff;
  15727. state.check = crc32(state.check, hbuf, 2, 0);
  15728. //===//
  15729. //=== INITBITS();
  15730. hold = 0;
  15731. bits = 0;
  15732. //===//
  15733. state.mode = FLAGS;
  15734. break;
  15735. }
  15736. state.flags = 0; /* expect zlib header */
  15737. if (state.head) {
  15738. state.head.done = false;
  15739. }
  15740. if (!(state.wrap & 1) || /* check if zlib header allowed */
  15741. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  15742. strm.msg = 'incorrect header check';
  15743. state.mode = BAD;
  15744. break;
  15745. }
  15746. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  15747. strm.msg = 'unknown compression method';
  15748. state.mode = BAD;
  15749. break;
  15750. }
  15751. //--- DROPBITS(4) ---//
  15752. hold >>>= 4;
  15753. bits -= 4;
  15754. //---//
  15755. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  15756. if (state.wbits === 0) {
  15757. state.wbits = len;
  15758. }
  15759. else if (len > state.wbits) {
  15760. strm.msg = 'invalid window size';
  15761. state.mode = BAD;
  15762. break;
  15763. }
  15764. state.dmax = 1 << len;
  15765. //Tracev((stderr, "inflate: zlib header ok\n"));
  15766. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  15767. state.mode = hold & 0x200 ? DICTID : TYPE;
  15768. //=== INITBITS();
  15769. hold = 0;
  15770. bits = 0;
  15771. //===//
  15772. break;
  15773. case FLAGS:
  15774. //=== NEEDBITS(16); */
  15775. while (bits < 16) {
  15776. if (have === 0) { break inf_leave; }
  15777. have--;
  15778. hold += input[next++] << bits;
  15779. bits += 8;
  15780. }
  15781. //===//
  15782. state.flags = hold;
  15783. if ((state.flags & 0xff) !== Z_DEFLATED) {
  15784. strm.msg = 'unknown compression method';
  15785. state.mode = BAD;
  15786. break;
  15787. }
  15788. if (state.flags & 0xe000) {
  15789. strm.msg = 'unknown header flags set';
  15790. state.mode = BAD;
  15791. break;
  15792. }
  15793. if (state.head) {
  15794. state.head.text = ((hold >> 8) & 1);
  15795. }
  15796. if (state.flags & 0x0200) {
  15797. //=== CRC2(state.check, hold);
  15798. hbuf[0] = hold & 0xff;
  15799. hbuf[1] = (hold >>> 8) & 0xff;
  15800. state.check = crc32(state.check, hbuf, 2, 0);
  15801. //===//
  15802. }
  15803. //=== INITBITS();
  15804. hold = 0;
  15805. bits = 0;
  15806. //===//
  15807. state.mode = TIME;
  15808. /* falls through */
  15809. case TIME:
  15810. //=== NEEDBITS(32); */
  15811. while (bits < 32) {
  15812. if (have === 0) { break inf_leave; }
  15813. have--;
  15814. hold += input[next++] << bits;
  15815. bits += 8;
  15816. }
  15817. //===//
  15818. if (state.head) {
  15819. state.head.time = hold;
  15820. }
  15821. if (state.flags & 0x0200) {
  15822. //=== CRC4(state.check, hold)
  15823. hbuf[0] = hold & 0xff;
  15824. hbuf[1] = (hold >>> 8) & 0xff;
  15825. hbuf[2] = (hold >>> 16) & 0xff;
  15826. hbuf[3] = (hold >>> 24) & 0xff;
  15827. state.check = crc32(state.check, hbuf, 4, 0);
  15828. //===
  15829. }
  15830. //=== INITBITS();
  15831. hold = 0;
  15832. bits = 0;
  15833. //===//
  15834. state.mode = OS;
  15835. /* falls through */
  15836. case OS:
  15837. //=== NEEDBITS(16); */
  15838. while (bits < 16) {
  15839. if (have === 0) { break inf_leave; }
  15840. have--;
  15841. hold += input[next++] << bits;
  15842. bits += 8;
  15843. }
  15844. //===//
  15845. if (state.head) {
  15846. state.head.xflags = (hold & 0xff);
  15847. state.head.os = (hold >> 8);
  15848. }
  15849. if (state.flags & 0x0200) {
  15850. //=== CRC2(state.check, hold);
  15851. hbuf[0] = hold & 0xff;
  15852. hbuf[1] = (hold >>> 8) & 0xff;
  15853. state.check = crc32(state.check, hbuf, 2, 0);
  15854. //===//
  15855. }
  15856. //=== INITBITS();
  15857. hold = 0;
  15858. bits = 0;
  15859. //===//
  15860. state.mode = EXLEN;
  15861. /* falls through */
  15862. case EXLEN:
  15863. if (state.flags & 0x0400) {
  15864. //=== NEEDBITS(16); */
  15865. while (bits < 16) {
  15866. if (have === 0) { break inf_leave; }
  15867. have--;
  15868. hold += input[next++] << bits;
  15869. bits += 8;
  15870. }
  15871. //===//
  15872. state.length = hold;
  15873. if (state.head) {
  15874. state.head.extra_len = hold;
  15875. }
  15876. if (state.flags & 0x0200) {
  15877. //=== CRC2(state.check, hold);
  15878. hbuf[0] = hold & 0xff;
  15879. hbuf[1] = (hold >>> 8) & 0xff;
  15880. state.check = crc32(state.check, hbuf, 2, 0);
  15881. //===//
  15882. }
  15883. //=== INITBITS();
  15884. hold = 0;
  15885. bits = 0;
  15886. //===//
  15887. }
  15888. else if (state.head) {
  15889. state.head.extra = null/*Z_NULL*/;
  15890. }
  15891. state.mode = EXTRA;
  15892. /* falls through */
  15893. case EXTRA:
  15894. if (state.flags & 0x0400) {
  15895. copy = state.length;
  15896. if (copy > have) { copy = have; }
  15897. if (copy) {
  15898. if (state.head) {
  15899. len = state.head.extra_len - state.length;
  15900. if (!state.head.extra) {
  15901. // Use untyped array for more conveniend processing later
  15902. state.head.extra = new Array(state.head.extra_len);
  15903. }
  15904. utils.arraySet(
  15905. state.head.extra,
  15906. input,
  15907. next,
  15908. // extra field is limited to 65536 bytes
  15909. // - no need for additional size check
  15910. copy,
  15911. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  15912. len
  15913. );
  15914. //zmemcpy(state.head.extra + len, next,
  15915. // len + copy > state.head.extra_max ?
  15916. // state.head.extra_max - len : copy);
  15917. }
  15918. if (state.flags & 0x0200) {
  15919. state.check = crc32(state.check, input, copy, next);
  15920. }
  15921. have -= copy;
  15922. next += copy;
  15923. state.length -= copy;
  15924. }
  15925. if (state.length) { break inf_leave; }
  15926. }
  15927. state.length = 0;
  15928. state.mode = NAME;
  15929. /* falls through */
  15930. case NAME:
  15931. if (state.flags & 0x0800) {
  15932. if (have === 0) { break inf_leave; }
  15933. copy = 0;
  15934. do {
  15935. // TODO: 2 or 1 bytes?
  15936. len = input[next + copy++];
  15937. /* use constant limit because in js we should not preallocate memory */
  15938. if (state.head && len &&
  15939. (state.length < 65536 /*state.head.name_max*/)) {
  15940. state.head.name += String.fromCharCode(len);
  15941. }
  15942. } while (len && copy < have);
  15943. if (state.flags & 0x0200) {
  15944. state.check = crc32(state.check, input, copy, next);
  15945. }
  15946. have -= copy;
  15947. next += copy;
  15948. if (len) { break inf_leave; }
  15949. }
  15950. else if (state.head) {
  15951. state.head.name = null;
  15952. }
  15953. state.length = 0;
  15954. state.mode = COMMENT;
  15955. /* falls through */
  15956. case COMMENT:
  15957. if (state.flags & 0x1000) {
  15958. if (have === 0) { break inf_leave; }
  15959. copy = 0;
  15960. do {
  15961. len = input[next + copy++];
  15962. /* use constant limit because in js we should not preallocate memory */
  15963. if (state.head && len &&
  15964. (state.length < 65536 /*state.head.comm_max*/)) {
  15965. state.head.comment += String.fromCharCode(len);
  15966. }
  15967. } while (len && copy < have);
  15968. if (state.flags & 0x0200) {
  15969. state.check = crc32(state.check, input, copy, next);
  15970. }
  15971. have -= copy;
  15972. next += copy;
  15973. if (len) { break inf_leave; }
  15974. }
  15975. else if (state.head) {
  15976. state.head.comment = null;
  15977. }
  15978. state.mode = HCRC;
  15979. /* falls through */
  15980. case HCRC:
  15981. if (state.flags & 0x0200) {
  15982. //=== NEEDBITS(16); */
  15983. while (bits < 16) {
  15984. if (have === 0) { break inf_leave; }
  15985. have--;
  15986. hold += input[next++] << bits;
  15987. bits += 8;
  15988. }
  15989. //===//
  15990. if (hold !== (state.check & 0xffff)) {
  15991. strm.msg = 'header crc mismatch';
  15992. state.mode = BAD;
  15993. break;
  15994. }
  15995. //=== INITBITS();
  15996. hold = 0;
  15997. bits = 0;
  15998. //===//
  15999. }
  16000. if (state.head) {
  16001. state.head.hcrc = ((state.flags >> 9) & 1);
  16002. state.head.done = true;
  16003. }
  16004. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  16005. state.mode = TYPE;
  16006. break;
  16007. case DICTID:
  16008. //=== NEEDBITS(32); */
  16009. while (bits < 32) {
  16010. if (have === 0) { break inf_leave; }
  16011. have--;
  16012. hold += input[next++] << bits;
  16013. bits += 8;
  16014. }
  16015. //===//
  16016. strm.adler = state.check = ZSWAP32(hold);
  16017. //=== INITBITS();
  16018. hold = 0;
  16019. bits = 0;
  16020. //===//
  16021. state.mode = DICT;
  16022. /* falls through */
  16023. case DICT:
  16024. if (state.havedict === 0) {
  16025. //--- RESTORE() ---
  16026. strm.next_out = put;
  16027. strm.avail_out = left;
  16028. strm.next_in = next;
  16029. strm.avail_in = have;
  16030. state.hold = hold;
  16031. state.bits = bits;
  16032. //---
  16033. return Z_NEED_DICT;
  16034. }
  16035. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16036. state.mode = TYPE;
  16037. /* falls through */
  16038. case TYPE:
  16039. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16040. /* falls through */
  16041. case TYPEDO:
  16042. if (state.last) {
  16043. //--- BYTEBITS() ---//
  16044. hold >>>= bits & 7;
  16045. bits -= bits & 7;
  16046. //---//
  16047. state.mode = CHECK;
  16048. break;
  16049. }
  16050. //=== NEEDBITS(3); */
  16051. while (bits < 3) {
  16052. if (have === 0) { break inf_leave; }
  16053. have--;
  16054. hold += input[next++] << bits;
  16055. bits += 8;
  16056. }
  16057. //===//
  16058. state.last = (hold & 0x01)/*BITS(1)*/;
  16059. //--- DROPBITS(1) ---//
  16060. hold >>>= 1;
  16061. bits -= 1;
  16062. //---//
  16063. switch ((hold & 0x03)/*BITS(2)*/) {
  16064. case 0: /* stored block */
  16065. //Tracev((stderr, "inflate: stored block%s\n",
  16066. // state.last ? " (last)" : ""));
  16067. state.mode = STORED;
  16068. break;
  16069. case 1: /* fixed block */
  16070. fixedtables(state);
  16071. //Tracev((stderr, "inflate: fixed codes block%s\n",
  16072. // state.last ? " (last)" : ""));
  16073. state.mode = LEN_; /* decode codes */
  16074. if (flush === Z_TREES) {
  16075. //--- DROPBITS(2) ---//
  16076. hold >>>= 2;
  16077. bits -= 2;
  16078. //---//
  16079. break inf_leave;
  16080. }
  16081. break;
  16082. case 2: /* dynamic block */
  16083. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  16084. // state.last ? " (last)" : ""));
  16085. state.mode = TABLE;
  16086. break;
  16087. case 3:
  16088. strm.msg = 'invalid block type';
  16089. state.mode = BAD;
  16090. }
  16091. //--- DROPBITS(2) ---//
  16092. hold >>>= 2;
  16093. bits -= 2;
  16094. //---//
  16095. break;
  16096. case STORED:
  16097. //--- BYTEBITS() ---// /* go to byte boundary */
  16098. hold >>>= bits & 7;
  16099. bits -= bits & 7;
  16100. //---//
  16101. //=== NEEDBITS(32); */
  16102. while (bits < 32) {
  16103. if (have === 0) { break inf_leave; }
  16104. have--;
  16105. hold += input[next++] << bits;
  16106. bits += 8;
  16107. }
  16108. //===//
  16109. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  16110. strm.msg = 'invalid stored block lengths';
  16111. state.mode = BAD;
  16112. break;
  16113. }
  16114. state.length = hold & 0xffff;
  16115. //Tracev((stderr, "inflate: stored length %u\n",
  16116. // state.length));
  16117. //=== INITBITS();
  16118. hold = 0;
  16119. bits = 0;
  16120. //===//
  16121. state.mode = COPY_;
  16122. if (flush === Z_TREES) { break inf_leave; }
  16123. /* falls through */
  16124. case COPY_:
  16125. state.mode = COPY;
  16126. /* falls through */
  16127. case COPY:
  16128. copy = state.length;
  16129. if (copy) {
  16130. if (copy > have) { copy = have; }
  16131. if (copy > left) { copy = left; }
  16132. if (copy === 0) { break inf_leave; }
  16133. //--- zmemcpy(put, next, copy); ---
  16134. utils.arraySet(output, input, next, copy, put);
  16135. //---//
  16136. have -= copy;
  16137. next += copy;
  16138. left -= copy;
  16139. put += copy;
  16140. state.length -= copy;
  16141. break;
  16142. }
  16143. //Tracev((stderr, "inflate: stored end\n"));
  16144. state.mode = TYPE;
  16145. break;
  16146. case TABLE:
  16147. //=== NEEDBITS(14); */
  16148. while (bits < 14) {
  16149. if (have === 0) { break inf_leave; }
  16150. have--;
  16151. hold += input[next++] << bits;
  16152. bits += 8;
  16153. }
  16154. //===//
  16155. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  16156. //--- DROPBITS(5) ---//
  16157. hold >>>= 5;
  16158. bits -= 5;
  16159. //---//
  16160. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  16161. //--- DROPBITS(5) ---//
  16162. hold >>>= 5;
  16163. bits -= 5;
  16164. //---//
  16165. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  16166. //--- DROPBITS(4) ---//
  16167. hold >>>= 4;
  16168. bits -= 4;
  16169. //---//
  16170. //#ifndef PKZIP_BUG_WORKAROUND
  16171. if (state.nlen > 286 || state.ndist > 30) {
  16172. strm.msg = 'too many length or distance symbols';
  16173. state.mode = BAD;
  16174. break;
  16175. }
  16176. //#endif
  16177. //Tracev((stderr, "inflate: table sizes ok\n"));
  16178. state.have = 0;
  16179. state.mode = LENLENS;
  16180. /* falls through */
  16181. case LENLENS:
  16182. while (state.have < state.ncode) {
  16183. //=== NEEDBITS(3);
  16184. while (bits < 3) {
  16185. if (have === 0) { break inf_leave; }
  16186. have--;
  16187. hold += input[next++] << bits;
  16188. bits += 8;
  16189. }
  16190. //===//
  16191. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  16192. //--- DROPBITS(3) ---//
  16193. hold >>>= 3;
  16194. bits -= 3;
  16195. //---//
  16196. }
  16197. while (state.have < 19) {
  16198. state.lens[order[state.have++]] = 0;
  16199. }
  16200. // We have separate tables & no pointers. 2 commented lines below not needed.
  16201. //state.next = state.codes;
  16202. //state.lencode = state.next;
  16203. // Switch to use dynamic table
  16204. state.lencode = state.lendyn;
  16205. state.lenbits = 7;
  16206. opts = {bits: state.lenbits};
  16207. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  16208. state.lenbits = opts.bits;
  16209. if (ret) {
  16210. strm.msg = 'invalid code lengths set';
  16211. state.mode = BAD;
  16212. break;
  16213. }
  16214. //Tracev((stderr, "inflate: code lengths ok\n"));
  16215. state.have = 0;
  16216. state.mode = CODELENS;
  16217. /* falls through */
  16218. case CODELENS:
  16219. while (state.have < state.nlen + state.ndist) {
  16220. for (;;) {
  16221. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  16222. here_bits = here >>> 24;
  16223. here_op = (here >>> 16) & 0xff;
  16224. here_val = here & 0xffff;
  16225. if ((here_bits) <= bits) { break; }
  16226. //--- PULLBYTE() ---//
  16227. if (have === 0) { break inf_leave; }
  16228. have--;
  16229. hold += input[next++] << bits;
  16230. bits += 8;
  16231. //---//
  16232. }
  16233. if (here_val < 16) {
  16234. //--- DROPBITS(here.bits) ---//
  16235. hold >>>= here_bits;
  16236. bits -= here_bits;
  16237. //---//
  16238. state.lens[state.have++] = here_val;
  16239. }
  16240. else {
  16241. if (here_val === 16) {
  16242. //=== NEEDBITS(here.bits + 2);
  16243. n = here_bits + 2;
  16244. while (bits < n) {
  16245. if (have === 0) { break inf_leave; }
  16246. have--;
  16247. hold += input[next++] << bits;
  16248. bits += 8;
  16249. }
  16250. //===//
  16251. //--- DROPBITS(here.bits) ---//
  16252. hold >>>= here_bits;
  16253. bits -= here_bits;
  16254. //---//
  16255. if (state.have === 0) {
  16256. strm.msg = 'invalid bit length repeat';
  16257. state.mode = BAD;
  16258. break;
  16259. }
  16260. len = state.lens[state.have - 1];
  16261. copy = 3 + (hold & 0x03);//BITS(2);
  16262. //--- DROPBITS(2) ---//
  16263. hold >>>= 2;
  16264. bits -= 2;
  16265. //---//
  16266. }
  16267. else if (here_val === 17) {
  16268. //=== NEEDBITS(here.bits + 3);
  16269. n = here_bits + 3;
  16270. while (bits < n) {
  16271. if (have === 0) { break inf_leave; }
  16272. have--;
  16273. hold += input[next++] << bits;
  16274. bits += 8;
  16275. }
  16276. //===//
  16277. //--- DROPBITS(here.bits) ---//
  16278. hold >>>= here_bits;
  16279. bits -= here_bits;
  16280. //---//
  16281. len = 0;
  16282. copy = 3 + (hold & 0x07);//BITS(3);
  16283. //--- DROPBITS(3) ---//
  16284. hold >>>= 3;
  16285. bits -= 3;
  16286. //---//
  16287. }
  16288. else {
  16289. //=== NEEDBITS(here.bits + 7);
  16290. n = here_bits + 7;
  16291. while (bits < n) {
  16292. if (have === 0) { break inf_leave; }
  16293. have--;
  16294. hold += input[next++] << bits;
  16295. bits += 8;
  16296. }
  16297. //===//
  16298. //--- DROPBITS(here.bits) ---//
  16299. hold >>>= here_bits;
  16300. bits -= here_bits;
  16301. //---//
  16302. len = 0;
  16303. copy = 11 + (hold & 0x7f);//BITS(7);
  16304. //--- DROPBITS(7) ---//
  16305. hold >>>= 7;
  16306. bits -= 7;
  16307. //---//
  16308. }
  16309. if (state.have + copy > state.nlen + state.ndist) {
  16310. strm.msg = 'invalid bit length repeat';
  16311. state.mode = BAD;
  16312. break;
  16313. }
  16314. while (copy--) {
  16315. state.lens[state.have++] = len;
  16316. }
  16317. }
  16318. }
  16319. /* handle error breaks in while */
  16320. if (state.mode === BAD) { break; }
  16321. /* check for end-of-block code (better have one) */
  16322. if (state.lens[256] === 0) {
  16323. strm.msg = 'invalid code -- missing end-of-block';
  16324. state.mode = BAD;
  16325. break;
  16326. }
  16327. /* build code tables -- note: do not change the lenbits or distbits
  16328. values here (9 and 6) without reading the comments in inftrees.h
  16329. concerning the ENOUGH constants, which depend on those values */
  16330. state.lenbits = 9;
  16331. opts = {bits: state.lenbits};
  16332. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  16333. // We have separate tables & no pointers. 2 commented lines below not needed.
  16334. // state.next_index = opts.table_index;
  16335. state.lenbits = opts.bits;
  16336. // state.lencode = state.next;
  16337. if (ret) {
  16338. strm.msg = 'invalid literal/lengths set';
  16339. state.mode = BAD;
  16340. break;
  16341. }
  16342. state.distbits = 6;
  16343. //state.distcode.copy(state.codes);
  16344. // Switch to use dynamic table
  16345. state.distcode = state.distdyn;
  16346. opts = {bits: state.distbits};
  16347. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  16348. // We have separate tables & no pointers. 2 commented lines below not needed.
  16349. // state.next_index = opts.table_index;
  16350. state.distbits = opts.bits;
  16351. // state.distcode = state.next;
  16352. if (ret) {
  16353. strm.msg = 'invalid distances set';
  16354. state.mode = BAD;
  16355. break;
  16356. }
  16357. //Tracev((stderr, 'inflate: codes ok\n'));
  16358. state.mode = LEN_;
  16359. if (flush === Z_TREES) { break inf_leave; }
  16360. /* falls through */
  16361. case LEN_:
  16362. state.mode = LEN;
  16363. /* falls through */
  16364. case LEN:
  16365. if (have >= 6 && left >= 258) {
  16366. //--- RESTORE() ---
  16367. strm.next_out = put;
  16368. strm.avail_out = left;
  16369. strm.next_in = next;
  16370. strm.avail_in = have;
  16371. state.hold = hold;
  16372. state.bits = bits;
  16373. //---
  16374. inflate_fast(strm, _out);
  16375. //--- LOAD() ---
  16376. put = strm.next_out;
  16377. output = strm.output;
  16378. left = strm.avail_out;
  16379. next = strm.next_in;
  16380. input = strm.input;
  16381. have = strm.avail_in;
  16382. hold = state.hold;
  16383. bits = state.bits;
  16384. //---
  16385. if (state.mode === TYPE) {
  16386. state.back = -1;
  16387. }
  16388. break;
  16389. }
  16390. state.back = 0;
  16391. for (;;) {
  16392. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  16393. here_bits = here >>> 24;
  16394. here_op = (here >>> 16) & 0xff;
  16395. here_val = here & 0xffff;
  16396. if (here_bits <= bits) { break; }
  16397. //--- PULLBYTE() ---//
  16398. if (have === 0) { break inf_leave; }
  16399. have--;
  16400. hold += input[next++] << bits;
  16401. bits += 8;
  16402. //---//
  16403. }
  16404. if (here_op && (here_op & 0xf0) === 0) {
  16405. last_bits = here_bits;
  16406. last_op = here_op;
  16407. last_val = here_val;
  16408. for (;;) {
  16409. here = state.lencode[last_val +
  16410. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16411. here_bits = here >>> 24;
  16412. here_op = (here >>> 16) & 0xff;
  16413. here_val = here & 0xffff;
  16414. if ((last_bits + here_bits) <= bits) { break; }
  16415. //--- PULLBYTE() ---//
  16416. if (have === 0) { break inf_leave; }
  16417. have--;
  16418. hold += input[next++] << bits;
  16419. bits += 8;
  16420. //---//
  16421. }
  16422. //--- DROPBITS(last.bits) ---//
  16423. hold >>>= last_bits;
  16424. bits -= last_bits;
  16425. //---//
  16426. state.back += last_bits;
  16427. }
  16428. //--- DROPBITS(here.bits) ---//
  16429. hold >>>= here_bits;
  16430. bits -= here_bits;
  16431. //---//
  16432. state.back += here_bits;
  16433. state.length = here_val;
  16434. if (here_op === 0) {
  16435. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16436. // "inflate: literal '%c'\n" :
  16437. // "inflate: literal 0x%02x\n", here.val));
  16438. state.mode = LIT;
  16439. break;
  16440. }
  16441. if (here_op & 32) {
  16442. //Tracevv((stderr, "inflate: end of block\n"));
  16443. state.back = -1;
  16444. state.mode = TYPE;
  16445. break;
  16446. }
  16447. if (here_op & 64) {
  16448. strm.msg = 'invalid literal/length code';
  16449. state.mode = BAD;
  16450. break;
  16451. }
  16452. state.extra = here_op & 15;
  16453. state.mode = LENEXT;
  16454. /* falls through */
  16455. case LENEXT:
  16456. if (state.extra) {
  16457. //=== NEEDBITS(state.extra);
  16458. n = state.extra;
  16459. while (bits < n) {
  16460. if (have === 0) { break inf_leave; }
  16461. have--;
  16462. hold += input[next++] << bits;
  16463. bits += 8;
  16464. }
  16465. //===//
  16466. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16467. //--- DROPBITS(state.extra) ---//
  16468. hold >>>= state.extra;
  16469. bits -= state.extra;
  16470. //---//
  16471. state.back += state.extra;
  16472. }
  16473. //Tracevv((stderr, "inflate: length %u\n", state.length));
  16474. state.was = state.length;
  16475. state.mode = DIST;
  16476. /* falls through */
  16477. case DIST:
  16478. for (;;) {
  16479. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  16480. here_bits = here >>> 24;
  16481. here_op = (here >>> 16) & 0xff;
  16482. here_val = here & 0xffff;
  16483. if ((here_bits) <= bits) { break; }
  16484. //--- PULLBYTE() ---//
  16485. if (have === 0) { break inf_leave; }
  16486. have--;
  16487. hold += input[next++] << bits;
  16488. bits += 8;
  16489. //---//
  16490. }
  16491. if ((here_op & 0xf0) === 0) {
  16492. last_bits = here_bits;
  16493. last_op = here_op;
  16494. last_val = here_val;
  16495. for (;;) {
  16496. here = state.distcode[last_val +
  16497. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16498. here_bits = here >>> 24;
  16499. here_op = (here >>> 16) & 0xff;
  16500. here_val = here & 0xffff;
  16501. if ((last_bits + here_bits) <= bits) { break; }
  16502. //--- PULLBYTE() ---//
  16503. if (have === 0) { break inf_leave; }
  16504. have--;
  16505. hold += input[next++] << bits;
  16506. bits += 8;
  16507. //---//
  16508. }
  16509. //--- DROPBITS(last.bits) ---//
  16510. hold >>>= last_bits;
  16511. bits -= last_bits;
  16512. //---//
  16513. state.back += last_bits;
  16514. }
  16515. //--- DROPBITS(here.bits) ---//
  16516. hold >>>= here_bits;
  16517. bits -= here_bits;
  16518. //---//
  16519. state.back += here_bits;
  16520. if (here_op & 64) {
  16521. strm.msg = 'invalid distance code';
  16522. state.mode = BAD;
  16523. break;
  16524. }
  16525. state.offset = here_val;
  16526. state.extra = (here_op) & 15;
  16527. state.mode = DISTEXT;
  16528. /* falls through */
  16529. case DISTEXT:
  16530. if (state.extra) {
  16531. //=== NEEDBITS(state.extra);
  16532. n = state.extra;
  16533. while (bits < n) {
  16534. if (have === 0) { break inf_leave; }
  16535. have--;
  16536. hold += input[next++] << bits;
  16537. bits += 8;
  16538. }
  16539. //===//
  16540. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  16541. //--- DROPBITS(state.extra) ---//
  16542. hold >>>= state.extra;
  16543. bits -= state.extra;
  16544. //---//
  16545. state.back += state.extra;
  16546. }
  16547. //#ifdef INFLATE_STRICT
  16548. if (state.offset > state.dmax) {
  16549. strm.msg = 'invalid distance too far back';
  16550. state.mode = BAD;
  16551. break;
  16552. }
  16553. //#endif
  16554. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  16555. state.mode = MATCH;
  16556. /* falls through */
  16557. case MATCH:
  16558. if (left === 0) { break inf_leave; }
  16559. copy = _out - left;
  16560. if (state.offset > copy) { /* copy from window */
  16561. copy = state.offset - copy;
  16562. if (copy > state.whave) {
  16563. if (state.sane) {
  16564. strm.msg = 'invalid distance too far back';
  16565. state.mode = BAD;
  16566. break;
  16567. }
  16568. // (!) This block is disabled in zlib defailts,
  16569. // don't enable it for binary compatibility
  16570. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16571. // Trace((stderr, "inflate.c too far\n"));
  16572. // copy -= state.whave;
  16573. // if (copy > state.length) { copy = state.length; }
  16574. // if (copy > left) { copy = left; }
  16575. // left -= copy;
  16576. // state.length -= copy;
  16577. // do {
  16578. // output[put++] = 0;
  16579. // } while (--copy);
  16580. // if (state.length === 0) { state.mode = LEN; }
  16581. // break;
  16582. //#endif
  16583. }
  16584. if (copy > state.wnext) {
  16585. copy -= state.wnext;
  16586. from = state.wsize - copy;
  16587. }
  16588. else {
  16589. from = state.wnext - copy;
  16590. }
  16591. if (copy > state.length) { copy = state.length; }
  16592. from_source = state.window;
  16593. }
  16594. else { /* copy from output */
  16595. from_source = output;
  16596. from = put - state.offset;
  16597. copy = state.length;
  16598. }
  16599. if (copy > left) { copy = left; }
  16600. left -= copy;
  16601. state.length -= copy;
  16602. do {
  16603. output[put++] = from_source[from++];
  16604. } while (--copy);
  16605. if (state.length === 0) { state.mode = LEN; }
  16606. break;
  16607. case LIT:
  16608. if (left === 0) { break inf_leave; }
  16609. output[put++] = state.length;
  16610. left--;
  16611. state.mode = LEN;
  16612. break;
  16613. case CHECK:
  16614. if (state.wrap) {
  16615. //=== NEEDBITS(32);
  16616. while (bits < 32) {
  16617. if (have === 0) { break inf_leave; }
  16618. have--;
  16619. // Use '|' insdead of '+' to make sure that result is signed
  16620. hold |= input[next++] << bits;
  16621. bits += 8;
  16622. }
  16623. //===//
  16624. _out -= left;
  16625. strm.total_out += _out;
  16626. state.total += _out;
  16627. if (_out) {
  16628. strm.adler = state.check =
  16629. /*UPDATE(state.check, put - _out, _out);*/
  16630. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  16631. }
  16632. _out = left;
  16633. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  16634. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  16635. strm.msg = 'incorrect data check';
  16636. state.mode = BAD;
  16637. break;
  16638. }
  16639. //=== INITBITS();
  16640. hold = 0;
  16641. bits = 0;
  16642. //===//
  16643. //Tracev((stderr, "inflate: check matches trailer\n"));
  16644. }
  16645. state.mode = LENGTH;
  16646. /* falls through */
  16647. case LENGTH:
  16648. if (state.wrap && state.flags) {
  16649. //=== NEEDBITS(32);
  16650. while (bits < 32) {
  16651. if (have === 0) { break inf_leave; }
  16652. have--;
  16653. hold += input[next++] << bits;
  16654. bits += 8;
  16655. }
  16656. //===//
  16657. if (hold !== (state.total & 0xffffffff)) {
  16658. strm.msg = 'incorrect length check';
  16659. state.mode = BAD;
  16660. break;
  16661. }
  16662. //=== INITBITS();
  16663. hold = 0;
  16664. bits = 0;
  16665. //===//
  16666. //Tracev((stderr, "inflate: length matches trailer\n"));
  16667. }
  16668. state.mode = DONE;
  16669. /* falls through */
  16670. case DONE:
  16671. ret = Z_STREAM_END;
  16672. break inf_leave;
  16673. case BAD:
  16674. ret = Z_DATA_ERROR;
  16675. break inf_leave;
  16676. case MEM:
  16677. return Z_MEM_ERROR;
  16678. case SYNC:
  16679. /* falls through */
  16680. default:
  16681. return Z_STREAM_ERROR;
  16682. }
  16683. }
  16684. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  16685. /*
  16686. Return from inflate(), updating the total counts and the check value.
  16687. If there was no progress during the inflate() call, return a buffer
  16688. error. Call updatewindow() to create and/or update the window state.
  16689. Note: a memory error from inflate() is non-recoverable.
  16690. */
  16691. //--- RESTORE() ---
  16692. strm.next_out = put;
  16693. strm.avail_out = left;
  16694. strm.next_in = next;
  16695. strm.avail_in = have;
  16696. state.hold = hold;
  16697. state.bits = bits;
  16698. //---
  16699. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  16700. (state.mode < CHECK || flush !== Z_FINISH))) {
  16701. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  16702. state.mode = MEM;
  16703. return Z_MEM_ERROR;
  16704. }
  16705. }
  16706. _in -= strm.avail_in;
  16707. _out -= strm.avail_out;
  16708. strm.total_in += _in;
  16709. strm.total_out += _out;
  16710. state.total += _out;
  16711. if (state.wrap && _out) {
  16712. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  16713. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  16714. }
  16715. strm.data_type = state.bits + (state.last ? 64 : 0) +
  16716. (state.mode === TYPE ? 128 : 0) +
  16717. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  16718. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  16719. ret = Z_BUF_ERROR;
  16720. }
  16721. return ret;
  16722. }
  16723. function inflateEnd(strm) {
  16724. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  16725. return Z_STREAM_ERROR;
  16726. }
  16727. var state = strm.state;
  16728. if (state.window) {
  16729. state.window = null;
  16730. }
  16731. strm.state = null;
  16732. return Z_OK;
  16733. }
  16734. function inflateGetHeader(strm, head) {
  16735. var state;
  16736. /* check state */
  16737. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16738. state = strm.state;
  16739. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  16740. /* save header structure */
  16741. state.head = head;
  16742. head.done = false;
  16743. return Z_OK;
  16744. }
  16745. exports.inflateReset = inflateReset;
  16746. exports.inflateReset2 = inflateReset2;
  16747. exports.inflateResetKeep = inflateResetKeep;
  16748. exports.inflateInit = inflateInit;
  16749. exports.inflateInit2 = inflateInit2;
  16750. exports.inflate = inflate;
  16751. exports.inflateEnd = inflateEnd;
  16752. exports.inflateGetHeader = inflateGetHeader;
  16753. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  16754. /* Not implemented
  16755. exports.inflateCopy = inflateCopy;
  16756. exports.inflateGetDictionary = inflateGetDictionary;
  16757. exports.inflateMark = inflateMark;
  16758. exports.inflatePrime = inflatePrime;
  16759. exports.inflateSetDictionary = inflateSetDictionary;
  16760. exports.inflateSync = inflateSync;
  16761. exports.inflateSyncPoint = inflateSyncPoint;
  16762. exports.inflateUndermine = inflateUndermine;
  16763. */
  16764. },{"../utils/common":49,"./adler32":51,"./crc32":53,"./inffast":56,"./inftrees":58}],58:[function(require,module,exports){
  16765. 'use strict';
  16766. var utils = require('../utils/common');
  16767. var MAXBITS = 15;
  16768. var ENOUGH_LENS = 852;
  16769. var ENOUGH_DISTS = 592;
  16770. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  16771. var CODES = 0;
  16772. var LENS = 1;
  16773. var DISTS = 2;
  16774. var lbase = [ /* Length codes 257..285 base */
  16775. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  16776. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  16777. ];
  16778. var lext = [ /* Length codes 257..285 extra */
  16779. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  16780. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  16781. ];
  16782. var dbase = [ /* Distance codes 0..29 base */
  16783. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  16784. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  16785. 8193, 12289, 16385, 24577, 0, 0
  16786. ];
  16787. var dext = [ /* Distance codes 0..29 extra */
  16788. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  16789. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  16790. 28, 28, 29, 29, 64, 64
  16791. ];
  16792. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  16793. {
  16794. var bits = opts.bits;
  16795. //here = opts.here; /* table entry for duplication */
  16796. var len = 0; /* a code's length in bits */
  16797. var sym = 0; /* index of code symbols */
  16798. var min = 0, max = 0; /* minimum and maximum code lengths */
  16799. var root = 0; /* number of index bits for root table */
  16800. var curr = 0; /* number of index bits for current table */
  16801. var drop = 0; /* code bits to drop for sub-table */
  16802. var left = 0; /* number of prefix codes available */
  16803. var used = 0; /* code entries in table used */
  16804. var huff = 0; /* Huffman code */
  16805. var incr; /* for incrementing code, index */
  16806. var fill; /* index for replicating entries */
  16807. var low; /* low bits for current root entry */
  16808. var mask; /* mask for low root bits */
  16809. var next; /* next available space in table */
  16810. var base = null; /* base value table to use */
  16811. var base_index = 0;
  16812. // var shoextra; /* extra bits table to use */
  16813. var end; /* use base and extra for symbol > end */
  16814. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  16815. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  16816. var extra = null;
  16817. var extra_index = 0;
  16818. var here_bits, here_op, here_val;
  16819. /*
  16820. Process a set of code lengths to create a canonical Huffman code. The
  16821. code lengths are lens[0..codes-1]. Each length corresponds to the
  16822. symbols 0..codes-1. The Huffman code is generated by first sorting the
  16823. symbols by length from short to long, and retaining the symbol order
  16824. for codes with equal lengths. Then the code starts with all zero bits
  16825. for the first code of the shortest length, and the codes are integer
  16826. increments for the same length, and zeros are appended as the length
  16827. increases. For the deflate format, these bits are stored backwards
  16828. from their more natural integer increment ordering, and so when the
  16829. decoding tables are built in the large loop below, the integer codes
  16830. are incremented backwards.
  16831. This routine assumes, but does not check, that all of the entries in
  16832. lens[] are in the range 0..MAXBITS. The caller must assure this.
  16833. 1..MAXBITS is interpreted as that code length. zero means that that
  16834. symbol does not occur in this code.
  16835. The codes are sorted by computing a count of codes for each length,
  16836. creating from that a table of starting indices for each length in the
  16837. sorted table, and then entering the symbols in order in the sorted
  16838. table. The sorted table is work[], with that space being provided by
  16839. the caller.
  16840. The length counts are used for other purposes as well, i.e. finding
  16841. the minimum and maximum length codes, determining if there are any
  16842. codes at all, checking for a valid set of lengths, and looking ahead
  16843. at length counts to determine sub-table sizes when building the
  16844. decoding tables.
  16845. */
  16846. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  16847. for (len = 0; len <= MAXBITS; len++) {
  16848. count[len] = 0;
  16849. }
  16850. for (sym = 0; sym < codes; sym++) {
  16851. count[lens[lens_index + sym]]++;
  16852. }
  16853. /* bound code lengths, force root to be within code lengths */
  16854. root = bits;
  16855. for (max = MAXBITS; max >= 1; max--) {
  16856. if (count[max] !== 0) { break; }
  16857. }
  16858. if (root > max) {
  16859. root = max;
  16860. }
  16861. if (max === 0) { /* no symbols to code at all */
  16862. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  16863. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  16864. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  16865. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  16866. //table.op[opts.table_index] = 64;
  16867. //table.bits[opts.table_index] = 1;
  16868. //table.val[opts.table_index++] = 0;
  16869. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  16870. opts.bits = 1;
  16871. return 0; /* no symbols, but wait for decoding to report error */
  16872. }
  16873. for (min = 1; min < max; min++) {
  16874. if (count[min] !== 0) { break; }
  16875. }
  16876. if (root < min) {
  16877. root = min;
  16878. }
  16879. /* check for an over-subscribed or incomplete set of lengths */
  16880. left = 1;
  16881. for (len = 1; len <= MAXBITS; len++) {
  16882. left <<= 1;
  16883. left -= count[len];
  16884. if (left < 0) {
  16885. return -1;
  16886. } /* over-subscribed */
  16887. }
  16888. if (left > 0 && (type === CODES || max !== 1)) {
  16889. return -1; /* incomplete set */
  16890. }
  16891. /* generate offsets into symbol table for each length for sorting */
  16892. offs[1] = 0;
  16893. for (len = 1; len < MAXBITS; len++) {
  16894. offs[len + 1] = offs[len] + count[len];
  16895. }
  16896. /* sort symbols by length, by symbol order within each length */
  16897. for (sym = 0; sym < codes; sym++) {
  16898. if (lens[lens_index + sym] !== 0) {
  16899. work[offs[lens[lens_index + sym]]++] = sym;
  16900. }
  16901. }
  16902. /*
  16903. Create and fill in decoding tables. In this loop, the table being
  16904. filled is at next and has curr index bits. The code being used is huff
  16905. with length len. That code is converted to an index by dropping drop
  16906. bits off of the bottom. For codes where len is less than drop + curr,
  16907. those top drop + curr - len bits are incremented through all values to
  16908. fill the table with replicated entries.
  16909. root is the number of index bits for the root table. When len exceeds
  16910. root, sub-tables are created pointed to by the root entry with an index
  16911. of the low root bits of huff. This is saved in low to check for when a
  16912. new sub-table should be started. drop is zero when the root table is
  16913. being filled, and drop is root when sub-tables are being filled.
  16914. When a new sub-table is needed, it is necessary to look ahead in the
  16915. code lengths to determine what size sub-table is needed. The length
  16916. counts are used for this, and so count[] is decremented as codes are
  16917. entered in the tables.
  16918. used keeps track of how many table entries have been allocated from the
  16919. provided *table space. It is checked for LENS and DIST tables against
  16920. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  16921. the initial root table size constants. See the comments in inftrees.h
  16922. for more information.
  16923. sym increments through all symbols, and the loop terminates when
  16924. all codes of length max, i.e. all codes, have been processed. This
  16925. routine permits incomplete codes, so another loop after this one fills
  16926. in the rest of the decoding tables with invalid code markers.
  16927. */
  16928. /* set up for code type */
  16929. // poor man optimization - use if-else instead of switch,
  16930. // to avoid deopts in old v8
  16931. if (type === CODES) {
  16932. base = extra = work; /* dummy value--not used */
  16933. end = 19;
  16934. } else if (type === LENS) {
  16935. base = lbase;
  16936. base_index -= 257;
  16937. extra = lext;
  16938. extra_index -= 257;
  16939. end = 256;
  16940. } else { /* DISTS */
  16941. base = dbase;
  16942. extra = dext;
  16943. end = -1;
  16944. }
  16945. /* initialize opts for loop */
  16946. huff = 0; /* starting code */
  16947. sym = 0; /* starting code symbol */
  16948. len = min; /* starting code length */
  16949. next = table_index; /* current table to fill in */
  16950. curr = root; /* current table index bits */
  16951. drop = 0; /* current bits to drop from code for index */
  16952. low = -1; /* trigger new sub-table when len > root */
  16953. used = 1 << root; /* use root table entries */
  16954. mask = used - 1; /* mask for comparing low */
  16955. /* check available table space */
  16956. if ((type === LENS && used > ENOUGH_LENS) ||
  16957. (type === DISTS && used > ENOUGH_DISTS)) {
  16958. return 1;
  16959. }
  16960. var i=0;
  16961. /* process all codes and make table entries */
  16962. for (;;) {
  16963. i++;
  16964. /* create table entry */
  16965. here_bits = len - drop;
  16966. if (work[sym] < end) {
  16967. here_op = 0;
  16968. here_val = work[sym];
  16969. }
  16970. else if (work[sym] > end) {
  16971. here_op = extra[extra_index + work[sym]];
  16972. here_val = base[base_index + work[sym]];
  16973. }
  16974. else {
  16975. here_op = 32 + 64; /* end of block */
  16976. here_val = 0;
  16977. }
  16978. /* replicate for those indices with low len bits equal to huff */
  16979. incr = 1 << (len - drop);
  16980. fill = 1 << curr;
  16981. min = fill; /* save offset to next table */
  16982. do {
  16983. fill -= incr;
  16984. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  16985. } while (fill !== 0);
  16986. /* backwards increment the len-bit code huff */
  16987. incr = 1 << (len - 1);
  16988. while (huff & incr) {
  16989. incr >>= 1;
  16990. }
  16991. if (incr !== 0) {
  16992. huff &= incr - 1;
  16993. huff += incr;
  16994. } else {
  16995. huff = 0;
  16996. }
  16997. /* go to next symbol, update count, len */
  16998. sym++;
  16999. if (--count[len] === 0) {
  17000. if (len === max) { break; }
  17001. len = lens[lens_index + work[sym]];
  17002. }
  17003. /* create new sub-table if needed */
  17004. if (len > root && (huff & mask) !== low) {
  17005. /* if first time, transition to sub-tables */
  17006. if (drop === 0) {
  17007. drop = root;
  17008. }
  17009. /* increment past last table */
  17010. next += min; /* here min is 1 << curr */
  17011. /* determine length of next table */
  17012. curr = len - drop;
  17013. left = 1 << curr;
  17014. while (curr + drop < max) {
  17015. left -= count[curr + drop];
  17016. if (left <= 0) { break; }
  17017. curr++;
  17018. left <<= 1;
  17019. }
  17020. /* check for enough space */
  17021. used += 1 << curr;
  17022. if ((type === LENS && used > ENOUGH_LENS) ||
  17023. (type === DISTS && used > ENOUGH_DISTS)) {
  17024. return 1;
  17025. }
  17026. /* point entry in root table to sub-table */
  17027. low = huff & mask;
  17028. /*table.op[low] = curr;
  17029. table.bits[low] = root;
  17030. table.val[low] = next - opts.table_index;*/
  17031. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17032. }
  17033. }
  17034. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17035. at most one remaining entry, since if the code is incomplete, the
  17036. maximum code length that was allowed to get this far is one bit) */
  17037. if (huff !== 0) {
  17038. //table.op[next + huff] = 64; /* invalid code marker */
  17039. //table.bits[next + huff] = len - drop;
  17040. //table.val[next + huff] = 0;
  17041. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17042. }
  17043. /* set return parameters */
  17044. //opts.table_index += used;
  17045. opts.bits = root;
  17046. return 0;
  17047. };
  17048. },{"../utils/common":49}],59:[function(require,module,exports){
  17049. 'use strict';
  17050. module.exports = {
  17051. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  17052. '1': 'stream end', /* Z_STREAM_END 1 */
  17053. '0': '', /* Z_OK 0 */
  17054. '-1': 'file error', /* Z_ERRNO (-1) */
  17055. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17056. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17057. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17058. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17059. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17060. };
  17061. },{}],60:[function(require,module,exports){
  17062. 'use strict';
  17063. var utils = require('../utils/common');
  17064. /* Public constants ==========================================================*/
  17065. /* ===========================================================================*/
  17066. //var Z_FILTERED = 1;
  17067. //var Z_HUFFMAN_ONLY = 2;
  17068. //var Z_RLE = 3;
  17069. var Z_FIXED = 4;
  17070. //var Z_DEFAULT_STRATEGY = 0;
  17071. /* Possible values of the data_type field (though see inflate()) */
  17072. var Z_BINARY = 0;
  17073. var Z_TEXT = 1;
  17074. //var Z_ASCII = 1; // = Z_TEXT
  17075. var Z_UNKNOWN = 2;
  17076. /*============================================================================*/
  17077. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17078. // From zutil.h
  17079. var STORED_BLOCK = 0;
  17080. var STATIC_TREES = 1;
  17081. var DYN_TREES = 2;
  17082. /* The three kinds of block type */
  17083. var MIN_MATCH = 3;
  17084. var MAX_MATCH = 258;
  17085. /* The minimum and maximum match lengths */
  17086. // From deflate.h
  17087. /* ===========================================================================
  17088. * Internal compression state.
  17089. */
  17090. var LENGTH_CODES = 29;
  17091. /* number of length codes, not counting the special END_BLOCK code */
  17092. var LITERALS = 256;
  17093. /* number of literal bytes 0..255 */
  17094. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17095. /* number of Literal or Length codes, including the END_BLOCK code */
  17096. var D_CODES = 30;
  17097. /* number of distance codes */
  17098. var BL_CODES = 19;
  17099. /* number of codes used to transfer the bit lengths */
  17100. var HEAP_SIZE = 2*L_CODES + 1;
  17101. /* maximum heap size */
  17102. var MAX_BITS = 15;
  17103. /* All codes must not exceed MAX_BITS bits */
  17104. var Buf_size = 16;
  17105. /* size of bit buffer in bi_buf */
  17106. /* ===========================================================================
  17107. * Constants
  17108. */
  17109. var MAX_BL_BITS = 7;
  17110. /* Bit length codes must not exceed MAX_BL_BITS bits */
  17111. var END_BLOCK = 256;
  17112. /* end of block literal code */
  17113. var REP_3_6 = 16;
  17114. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  17115. var REPZ_3_10 = 17;
  17116. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  17117. var REPZ_11_138 = 18;
  17118. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  17119. var extra_lbits = /* extra bits for each length code */
  17120. [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];
  17121. var extra_dbits = /* extra bits for each distance code */
  17122. [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];
  17123. var extra_blbits = /* extra bits for each bit length code */
  17124. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  17125. var bl_order =
  17126. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  17127. /* The lengths of the bit length codes are sent in order of decreasing
  17128. * probability, to avoid transmitting the lengths for unused bit length codes.
  17129. */
  17130. /* ===========================================================================
  17131. * Local data. These are initialized only once.
  17132. */
  17133. // We pre-fill arrays with 0 to avoid uninitialized gaps
  17134. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  17135. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  17136. var static_ltree = new Array((L_CODES+2) * 2);
  17137. zero(static_ltree);
  17138. /* The static literal tree. Since the bit lengths are imposed, there is no
  17139. * need for the L_CODES extra codes used during heap construction. However
  17140. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  17141. * below).
  17142. */
  17143. var static_dtree = new Array(D_CODES * 2);
  17144. zero(static_dtree);
  17145. /* The static distance tree. (Actually a trivial tree since all codes use
  17146. * 5 bits.)
  17147. */
  17148. var _dist_code = new Array(DIST_CODE_LEN);
  17149. zero(_dist_code);
  17150. /* Distance codes. The first 256 values correspond to the distances
  17151. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  17152. * the 15 bit distances.
  17153. */
  17154. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  17155. zero(_length_code);
  17156. /* length code for each normalized match length (0 == MIN_MATCH) */
  17157. var base_length = new Array(LENGTH_CODES);
  17158. zero(base_length);
  17159. /* First normalized length for each code (0 = MIN_MATCH) */
  17160. var base_dist = new Array(D_CODES);
  17161. zero(base_dist);
  17162. /* First normalized distance for each code (0 = distance of 1) */
  17163. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  17164. this.static_tree = static_tree; /* static tree or NULL */
  17165. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  17166. this.extra_base = extra_base; /* base index for extra_bits */
  17167. this.elems = elems; /* max number of elements in the tree */
  17168. this.max_length = max_length; /* max bit length for the codes */
  17169. // show if `static_tree` has data or dummy - needed for monomorphic objects
  17170. this.has_stree = static_tree && static_tree.length;
  17171. };
  17172. var static_l_desc;
  17173. var static_d_desc;
  17174. var static_bl_desc;
  17175. var TreeDesc = function(dyn_tree, stat_desc) {
  17176. this.dyn_tree = dyn_tree; /* the dynamic tree */
  17177. this.max_code = 0; /* largest code with non zero frequency */
  17178. this.stat_desc = stat_desc; /* the corresponding static tree */
  17179. };
  17180. function d_code(dist) {
  17181. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17182. }
  17183. /* ===========================================================================
  17184. * Output a short LSB first on the stream.
  17185. * IN assertion: there is enough room in pendingBuf.
  17186. */
  17187. function put_short (s, w) {
  17188. // put_byte(s, (uch)((w) & 0xff));
  17189. // put_byte(s, (uch)((ush)(w) >> 8));
  17190. s.pending_buf[s.pending++] = (w) & 0xff;
  17191. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  17192. }
  17193. /* ===========================================================================
  17194. * Send a value on a given number of bits.
  17195. * IN assertion: length <= 16 and value fits in length bits.
  17196. */
  17197. function send_bits(s, value, length) {
  17198. if (s.bi_valid > (Buf_size - length)) {
  17199. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17200. put_short(s, s.bi_buf);
  17201. s.bi_buf = value >> (Buf_size - s.bi_valid);
  17202. s.bi_valid += length - Buf_size;
  17203. } else {
  17204. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17205. s.bi_valid += length;
  17206. }
  17207. }
  17208. function send_code(s, c, tree) {
  17209. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  17210. }
  17211. /* ===========================================================================
  17212. * Reverse the first len bits of a code, using straightforward code (a faster
  17213. * method would use a table)
  17214. * IN assertion: 1 <= len <= 15
  17215. */
  17216. function bi_reverse(code, len) {
  17217. var res = 0;
  17218. do {
  17219. res |= code & 1;
  17220. code >>>= 1;
  17221. res <<= 1;
  17222. } while (--len > 0);
  17223. return res >>> 1;
  17224. }
  17225. /* ===========================================================================
  17226. * Flush the bit buffer, keeping at most 7 bits in it.
  17227. */
  17228. function bi_flush(s) {
  17229. if (s.bi_valid === 16) {
  17230. put_short(s, s.bi_buf);
  17231. s.bi_buf = 0;
  17232. s.bi_valid = 0;
  17233. } else if (s.bi_valid >= 8) {
  17234. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  17235. s.bi_buf >>= 8;
  17236. s.bi_valid -= 8;
  17237. }
  17238. }
  17239. /* ===========================================================================
  17240. * Compute the optimal bit lengths for a tree and update the total bit length
  17241. * for the current block.
  17242. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  17243. * above are the tree nodes sorted by increasing frequency.
  17244. * OUT assertions: the field len is set to the optimal bit length, the
  17245. * array bl_count contains the frequencies for each bit length.
  17246. * The length opt_len is updated; static_len is also updated if stree is
  17247. * not null.
  17248. */
  17249. function gen_bitlen(s, desc)
  17250. // deflate_state *s;
  17251. // tree_desc *desc; /* the tree descriptor */
  17252. {
  17253. var tree = desc.dyn_tree;
  17254. var max_code = desc.max_code;
  17255. var stree = desc.stat_desc.static_tree;
  17256. var has_stree = desc.stat_desc.has_stree;
  17257. var extra = desc.stat_desc.extra_bits;
  17258. var base = desc.stat_desc.extra_base;
  17259. var max_length = desc.stat_desc.max_length;
  17260. var h; /* heap index */
  17261. var n, m; /* iterate over the tree elements */
  17262. var bits; /* bit length */
  17263. var xbits; /* extra bits */
  17264. var f; /* frequency */
  17265. var overflow = 0; /* number of elements with bit length too large */
  17266. for (bits = 0; bits <= MAX_BITS; bits++) {
  17267. s.bl_count[bits] = 0;
  17268. }
  17269. /* In a first pass, compute the optimal bit lengths (which may
  17270. * overflow in the case of the bit length tree).
  17271. */
  17272. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  17273. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  17274. n = s.heap[h];
  17275. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  17276. if (bits > max_length) {
  17277. bits = max_length;
  17278. overflow++;
  17279. }
  17280. tree[n*2 + 1]/*.Len*/ = bits;
  17281. /* We overwrite tree[n].Dad which is no longer needed */
  17282. if (n > max_code) { continue; } /* not a leaf node */
  17283. s.bl_count[bits]++;
  17284. xbits = 0;
  17285. if (n >= base) {
  17286. xbits = extra[n-base];
  17287. }
  17288. f = tree[n * 2]/*.Freq*/;
  17289. s.opt_len += f * (bits + xbits);
  17290. if (has_stree) {
  17291. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  17292. }
  17293. }
  17294. if (overflow === 0) { return; }
  17295. // Trace((stderr,"\nbit length overflow\n"));
  17296. /* This happens for example on obj2 and pic of the Calgary corpus */
  17297. /* Find the first bit length which could increase: */
  17298. do {
  17299. bits = max_length-1;
  17300. while (s.bl_count[bits] === 0) { bits--; }
  17301. s.bl_count[bits]--; /* move one leaf down the tree */
  17302. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  17303. s.bl_count[max_length]--;
  17304. /* The brother of the overflow item also moves one step up,
  17305. * but this does not affect bl_count[max_length]
  17306. */
  17307. overflow -= 2;
  17308. } while (overflow > 0);
  17309. /* Now recompute all bit lengths, scanning in increasing frequency.
  17310. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  17311. * lengths instead of fixing only the wrong ones. This idea is taken
  17312. * from 'ar' written by Haruhiko Okumura.)
  17313. */
  17314. for (bits = max_length; bits !== 0; bits--) {
  17315. n = s.bl_count[bits];
  17316. while (n !== 0) {
  17317. m = s.heap[--h];
  17318. if (m > max_code) { continue; }
  17319. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  17320. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  17321. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  17322. tree[m*2 + 1]/*.Len*/ = bits;
  17323. }
  17324. n--;
  17325. }
  17326. }
  17327. }
  17328. /* ===========================================================================
  17329. * Generate the codes for a given tree and bit counts (which need not be
  17330. * optimal).
  17331. * IN assertion: the array bl_count contains the bit length statistics for
  17332. * the given tree and the field len is set for all tree elements.
  17333. * OUT assertion: the field code is set for all tree elements of non
  17334. * zero code length.
  17335. */
  17336. function gen_codes(tree, max_code, bl_count)
  17337. // ct_data *tree; /* the tree to decorate */
  17338. // int max_code; /* largest code with non zero frequency */
  17339. // ushf *bl_count; /* number of codes at each bit length */
  17340. {
  17341. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  17342. var code = 0; /* running code value */
  17343. var bits; /* bit index */
  17344. var n; /* code index */
  17345. /* The distribution counts are first used to generate the code values
  17346. * without bit reversal.
  17347. */
  17348. for (bits = 1; bits <= MAX_BITS; bits++) {
  17349. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  17350. }
  17351. /* Check that the bit counts in bl_count are consistent. The last code
  17352. * must be all ones.
  17353. */
  17354. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17355. // "inconsistent bit counts");
  17356. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17357. for (n = 0; n <= max_code; n++) {
  17358. var len = tree[n*2 + 1]/*.Len*/;
  17359. if (len === 0) { continue; }
  17360. /* Now reverse the bits */
  17361. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  17362. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  17363. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  17364. }
  17365. }
  17366. /* ===========================================================================
  17367. * Initialize the various 'constant' tables.
  17368. */
  17369. function tr_static_init() {
  17370. var n; /* iterates over tree elements */
  17371. var bits; /* bit counter */
  17372. var length; /* length value */
  17373. var code; /* code value */
  17374. var dist; /* distance index */
  17375. var bl_count = new Array(MAX_BITS+1);
  17376. /* number of codes at each bit length for an optimal tree */
  17377. // do check in _tr_init()
  17378. //if (static_init_done) return;
  17379. /* For some embedded targets, global variables are not initialized: */
  17380. /*#ifdef NO_INIT_GLOBAL_POINTERS
  17381. static_l_desc.static_tree = static_ltree;
  17382. static_l_desc.extra_bits = extra_lbits;
  17383. static_d_desc.static_tree = static_dtree;
  17384. static_d_desc.extra_bits = extra_dbits;
  17385. static_bl_desc.extra_bits = extra_blbits;
  17386. #endif*/
  17387. /* Initialize the mapping length (0..255) -> length code (0..28) */
  17388. length = 0;
  17389. for (code = 0; code < LENGTH_CODES-1; code++) {
  17390. base_length[code] = length;
  17391. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  17392. _length_code[length++] = code;
  17393. }
  17394. }
  17395. //Assert (length == 256, "tr_static_init: length != 256");
  17396. /* Note that the length 255 (match length 258) can be represented
  17397. * in two different ways: code 284 + 5 bits or code 285, so we
  17398. * overwrite length_code[255] to use the best encoding:
  17399. */
  17400. _length_code[length-1] = code;
  17401. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  17402. dist = 0;
  17403. for (code = 0 ; code < 16; code++) {
  17404. base_dist[code] = dist;
  17405. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  17406. _dist_code[dist++] = code;
  17407. }
  17408. }
  17409. //Assert (dist == 256, "tr_static_init: dist != 256");
  17410. dist >>= 7; /* from now on, all distances are divided by 128 */
  17411. for (; code < D_CODES; code++) {
  17412. base_dist[code] = dist << 7;
  17413. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  17414. _dist_code[256 + dist++] = code;
  17415. }
  17416. }
  17417. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  17418. /* Construct the codes of the static literal tree */
  17419. for (bits = 0; bits <= MAX_BITS; bits++) {
  17420. bl_count[bits] = 0;
  17421. }
  17422. n = 0;
  17423. while (n <= 143) {
  17424. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17425. n++;
  17426. bl_count[8]++;
  17427. }
  17428. while (n <= 255) {
  17429. static_ltree[n*2 + 1]/*.Len*/ = 9;
  17430. n++;
  17431. bl_count[9]++;
  17432. }
  17433. while (n <= 279) {
  17434. static_ltree[n*2 + 1]/*.Len*/ = 7;
  17435. n++;
  17436. bl_count[7]++;
  17437. }
  17438. while (n <= 287) {
  17439. static_ltree[n*2 + 1]/*.Len*/ = 8;
  17440. n++;
  17441. bl_count[8]++;
  17442. }
  17443. /* Codes 286 and 287 do not exist, but we must include them in the
  17444. * tree construction to get a canonical Huffman tree (longest code
  17445. * all ones)
  17446. */
  17447. gen_codes(static_ltree, L_CODES+1, bl_count);
  17448. /* The static distance tree is trivial: */
  17449. for (n = 0; n < D_CODES; n++) {
  17450. static_dtree[n*2 + 1]/*.Len*/ = 5;
  17451. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  17452. }
  17453. // Now data ready and we can init static trees
  17454. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  17455. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  17456. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  17457. //static_init_done = true;
  17458. }
  17459. /* ===========================================================================
  17460. * Initialize a new block.
  17461. */
  17462. function init_block(s) {
  17463. var n; /* iterates over tree elements */
  17464. /* Initialize the trees. */
  17465. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  17466. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  17467. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  17468. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  17469. s.opt_len = s.static_len = 0;
  17470. s.last_lit = s.matches = 0;
  17471. }
  17472. /* ===========================================================================
  17473. * Flush the bit buffer and align the output on a byte boundary
  17474. */
  17475. function bi_windup(s)
  17476. {
  17477. if (s.bi_valid > 8) {
  17478. put_short(s, s.bi_buf);
  17479. } else if (s.bi_valid > 0) {
  17480. //put_byte(s, (Byte)s->bi_buf);
  17481. s.pending_buf[s.pending++] = s.bi_buf;
  17482. }
  17483. s.bi_buf = 0;
  17484. s.bi_valid = 0;
  17485. }
  17486. /* ===========================================================================
  17487. * Copy a stored block, storing first the length and its
  17488. * one's complement if requested.
  17489. */
  17490. function copy_block(s, buf, len, header)
  17491. //DeflateState *s;
  17492. //charf *buf; /* the input data */
  17493. //unsigned len; /* its length */
  17494. //int header; /* true if block header must be written */
  17495. {
  17496. bi_windup(s); /* align on byte boundary */
  17497. if (header) {
  17498. put_short(s, len);
  17499. put_short(s, ~len);
  17500. }
  17501. // while (len--) {
  17502. // put_byte(s, *buf++);
  17503. // }
  17504. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  17505. s.pending += len;
  17506. }
  17507. /* ===========================================================================
  17508. * Compares to subtrees, using the tree depth as tie breaker when
  17509. * the subtrees have equal frequency. This minimizes the worst case length.
  17510. */
  17511. function smaller(tree, n, m, depth) {
  17512. var _n2 = n*2;
  17513. var _m2 = m*2;
  17514. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  17515. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  17516. }
  17517. /* ===========================================================================
  17518. * Restore the heap property by moving down the tree starting at node k,
  17519. * exchanging a node with the smallest of its two sons if necessary, stopping
  17520. * when the heap property is re-established (each father smaller than its
  17521. * two sons).
  17522. */
  17523. function pqdownheap(s, tree, k)
  17524. // deflate_state *s;
  17525. // ct_data *tree; /* the tree to restore */
  17526. // int k; /* node to move down */
  17527. {
  17528. var v = s.heap[k];
  17529. var j = k << 1; /* left son of k */
  17530. while (j <= s.heap_len) {
  17531. /* Set j to the smallest of the two sons: */
  17532. if (j < s.heap_len &&
  17533. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  17534. j++;
  17535. }
  17536. /* Exit if v is smaller than both sons */
  17537. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  17538. /* Exchange v with the smallest son */
  17539. s.heap[k] = s.heap[j];
  17540. k = j;
  17541. /* And continue down the tree, setting j to the left son of k */
  17542. j <<= 1;
  17543. }
  17544. s.heap[k] = v;
  17545. }
  17546. // inlined manually
  17547. // var SMALLEST = 1;
  17548. /* ===========================================================================
  17549. * Send the block data compressed using the given Huffman trees
  17550. */
  17551. function compress_block(s, ltree, dtree)
  17552. // deflate_state *s;
  17553. // const ct_data *ltree; /* literal tree */
  17554. // const ct_data *dtree; /* distance tree */
  17555. {
  17556. var dist; /* distance of matched string */
  17557. var lc; /* match length or unmatched char (if dist == 0) */
  17558. var lx = 0; /* running index in l_buf */
  17559. var code; /* the code to send */
  17560. var extra; /* number of extra bits to send */
  17561. if (s.last_lit !== 0) {
  17562. do {
  17563. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  17564. lc = s.pending_buf[s.l_buf + lx];
  17565. lx++;
  17566. if (dist === 0) {
  17567. send_code(s, lc, ltree); /* send a literal byte */
  17568. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  17569. } else {
  17570. /* Here, lc is the match length - MIN_MATCH */
  17571. code = _length_code[lc];
  17572. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  17573. extra = extra_lbits[code];
  17574. if (extra !== 0) {
  17575. lc -= base_length[code];
  17576. send_bits(s, lc, extra); /* send the extra length bits */
  17577. }
  17578. dist--; /* dist is now the match distance - 1 */
  17579. code = d_code(dist);
  17580. //Assert (code < D_CODES, "bad d_code");
  17581. send_code(s, code, dtree); /* send the distance code */
  17582. extra = extra_dbits[code];
  17583. if (extra !== 0) {
  17584. dist -= base_dist[code];
  17585. send_bits(s, dist, extra); /* send the extra distance bits */
  17586. }
  17587. } /* literal or match pair ? */
  17588. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  17589. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  17590. // "pendingBuf overflow");
  17591. } while (lx < s.last_lit);
  17592. }
  17593. send_code(s, END_BLOCK, ltree);
  17594. }
  17595. /* ===========================================================================
  17596. * Construct one Huffman tree and assigns the code bit strings and lengths.
  17597. * Update the total bit length for the current block.
  17598. * IN assertion: the field freq is set for all tree elements.
  17599. * OUT assertions: the fields len and code are set to the optimal bit length
  17600. * and corresponding code. The length opt_len is updated; static_len is
  17601. * also updated if stree is not null. The field max_code is set.
  17602. */
  17603. function build_tree(s, desc)
  17604. // deflate_state *s;
  17605. // tree_desc *desc; /* the tree descriptor */
  17606. {
  17607. var tree = desc.dyn_tree;
  17608. var stree = desc.stat_desc.static_tree;
  17609. var has_stree = desc.stat_desc.has_stree;
  17610. var elems = desc.stat_desc.elems;
  17611. var n, m; /* iterate over heap elements */
  17612. var max_code = -1; /* largest code with non zero frequency */
  17613. var node; /* new node being created */
  17614. /* Construct the initial heap, with least frequent element in
  17615. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  17616. * heap[0] is not used.
  17617. */
  17618. s.heap_len = 0;
  17619. s.heap_max = HEAP_SIZE;
  17620. for (n = 0; n < elems; n++) {
  17621. if (tree[n * 2]/*.Freq*/ !== 0) {
  17622. s.heap[++s.heap_len] = max_code = n;
  17623. s.depth[n] = 0;
  17624. } else {
  17625. tree[n*2 + 1]/*.Len*/ = 0;
  17626. }
  17627. }
  17628. /* The pkzip format requires that at least one distance code exists,
  17629. * and that at least one bit should be sent even if there is only one
  17630. * possible code. So to avoid special checks later on we force at least
  17631. * two codes of non zero frequency.
  17632. */
  17633. while (s.heap_len < 2) {
  17634. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  17635. tree[node * 2]/*.Freq*/ = 1;
  17636. s.depth[node] = 0;
  17637. s.opt_len--;
  17638. if (has_stree) {
  17639. s.static_len -= stree[node*2 + 1]/*.Len*/;
  17640. }
  17641. /* node is 0 or 1 so it does not have extra bits */
  17642. }
  17643. desc.max_code = max_code;
  17644. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  17645. * establish sub-heaps of increasing lengths:
  17646. */
  17647. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  17648. /* Construct the Huffman tree by repeatedly combining the least two
  17649. * frequent nodes.
  17650. */
  17651. node = elems; /* next internal node of the tree */
  17652. do {
  17653. //pqremove(s, tree, n); /* n = node of least frequency */
  17654. /*** pqremove ***/
  17655. n = s.heap[1/*SMALLEST*/];
  17656. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  17657. pqdownheap(s, tree, 1/*SMALLEST*/);
  17658. /***/
  17659. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  17660. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  17661. s.heap[--s.heap_max] = m;
  17662. /* Create a new node father of n and m */
  17663. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  17664. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  17665. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  17666. /* and insert the new node in the heap */
  17667. s.heap[1/*SMALLEST*/] = node++;
  17668. pqdownheap(s, tree, 1/*SMALLEST*/);
  17669. } while (s.heap_len >= 2);
  17670. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  17671. /* At this point, the fields freq and dad are set. We can now
  17672. * generate the bit lengths.
  17673. */
  17674. gen_bitlen(s, desc);
  17675. /* The field len is now set, we can generate the bit codes */
  17676. gen_codes(tree, max_code, s.bl_count);
  17677. }
  17678. /* ===========================================================================
  17679. * Scan a literal or distance tree to determine the frequencies of the codes
  17680. * in the bit length tree.
  17681. */
  17682. function scan_tree(s, tree, max_code)
  17683. // deflate_state *s;
  17684. // ct_data *tree; /* the tree to be scanned */
  17685. // int max_code; /* and its largest code of non zero frequency */
  17686. {
  17687. var n; /* iterates over all tree elements */
  17688. var prevlen = -1; /* last emitted length */
  17689. var curlen; /* length of current code */
  17690. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17691. var count = 0; /* repeat count of the current code */
  17692. var max_count = 7; /* max repeat count */
  17693. var min_count = 4; /* min repeat count */
  17694. if (nextlen === 0) {
  17695. max_count = 138;
  17696. min_count = 3;
  17697. }
  17698. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  17699. for (n = 0; n <= max_code; n++) {
  17700. curlen = nextlen;
  17701. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17702. if (++count < max_count && curlen === nextlen) {
  17703. continue;
  17704. } else if (count < min_count) {
  17705. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  17706. } else if (curlen !== 0) {
  17707. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  17708. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  17709. } else if (count <= 10) {
  17710. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  17711. } else {
  17712. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  17713. }
  17714. count = 0;
  17715. prevlen = curlen;
  17716. if (nextlen === 0) {
  17717. max_count = 138;
  17718. min_count = 3;
  17719. } else if (curlen === nextlen) {
  17720. max_count = 6;
  17721. min_count = 3;
  17722. } else {
  17723. max_count = 7;
  17724. min_count = 4;
  17725. }
  17726. }
  17727. }
  17728. /* ===========================================================================
  17729. * Send a literal or distance tree in compressed form, using the codes in
  17730. * bl_tree.
  17731. */
  17732. function send_tree(s, tree, max_code)
  17733. // deflate_state *s;
  17734. // ct_data *tree; /* the tree to be scanned */
  17735. // int max_code; /* and its largest code of non zero frequency */
  17736. {
  17737. var n; /* iterates over all tree elements */
  17738. var prevlen = -1; /* last emitted length */
  17739. var curlen; /* length of current code */
  17740. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  17741. var count = 0; /* repeat count of the current code */
  17742. var max_count = 7; /* max repeat count */
  17743. var min_count = 4; /* min repeat count */
  17744. /* tree[max_code+1].Len = -1; */ /* guard already set */
  17745. if (nextlen === 0) {
  17746. max_count = 138;
  17747. min_count = 3;
  17748. }
  17749. for (n = 0; n <= max_code; n++) {
  17750. curlen = nextlen;
  17751. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  17752. if (++count < max_count && curlen === nextlen) {
  17753. continue;
  17754. } else if (count < min_count) {
  17755. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  17756. } else if (curlen !== 0) {
  17757. if (curlen !== prevlen) {
  17758. send_code(s, curlen, s.bl_tree);
  17759. count--;
  17760. }
  17761. //Assert(count >= 3 && count <= 6, " 3_6?");
  17762. send_code(s, REP_3_6, s.bl_tree);
  17763. send_bits(s, count-3, 2);
  17764. } else if (count <= 10) {
  17765. send_code(s, REPZ_3_10, s.bl_tree);
  17766. send_bits(s, count-3, 3);
  17767. } else {
  17768. send_code(s, REPZ_11_138, s.bl_tree);
  17769. send_bits(s, count-11, 7);
  17770. }
  17771. count = 0;
  17772. prevlen = curlen;
  17773. if (nextlen === 0) {
  17774. max_count = 138;
  17775. min_count = 3;
  17776. } else if (curlen === nextlen) {
  17777. max_count = 6;
  17778. min_count = 3;
  17779. } else {
  17780. max_count = 7;
  17781. min_count = 4;
  17782. }
  17783. }
  17784. }
  17785. /* ===========================================================================
  17786. * Construct the Huffman tree for the bit lengths and return the index in
  17787. * bl_order of the last bit length code to send.
  17788. */
  17789. function build_bl_tree(s) {
  17790. var max_blindex; /* index of last bit length code of non zero freq */
  17791. /* Determine the bit length frequencies for literal and distance trees */
  17792. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  17793. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  17794. /* Build the bit length tree: */
  17795. build_tree(s, s.bl_desc);
  17796. /* opt_len now includes the length of the tree representations, except
  17797. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  17798. */
  17799. /* Determine the number of bit length codes to send. The pkzip format
  17800. * requires that at least 4 bit length codes be sent. (appnote.txt says
  17801. * 3 but the actual value used is 4.)
  17802. */
  17803. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  17804. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  17805. break;
  17806. }
  17807. }
  17808. /* Update opt_len to include the bit length tree and counts */
  17809. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  17810. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  17811. // s->opt_len, s->static_len));
  17812. return max_blindex;
  17813. }
  17814. /* ===========================================================================
  17815. * Send the header for a block using dynamic Huffman trees: the counts, the
  17816. * lengths of the bit length codes, the literal tree and the distance tree.
  17817. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  17818. */
  17819. function send_all_trees(s, lcodes, dcodes, blcodes)
  17820. // deflate_state *s;
  17821. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  17822. {
  17823. var rank; /* index in bl_order */
  17824. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  17825. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  17826. // "too many codes");
  17827. //Tracev((stderr, "\nbl counts: "));
  17828. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  17829. send_bits(s, dcodes-1, 5);
  17830. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  17831. for (rank = 0; rank < blcodes; rank++) {
  17832. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  17833. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  17834. }
  17835. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  17836. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  17837. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  17838. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  17839. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  17840. }
  17841. /* ===========================================================================
  17842. * Check if the data type is TEXT or BINARY, using the following algorithm:
  17843. * - TEXT if the two conditions below are satisfied:
  17844. * a) There are no non-portable control characters belonging to the
  17845. * "black list" (0..6, 14..25, 28..31).
  17846. * b) There is at least one printable character belonging to the
  17847. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  17848. * - BINARY otherwise.
  17849. * - The following partially-portable control characters form a
  17850. * "gray list" that is ignored in this detection algorithm:
  17851. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  17852. * IN assertion: the fields Freq of dyn_ltree are set.
  17853. */
  17854. function detect_data_type(s) {
  17855. /* black_mask is the bit mask of black-listed bytes
  17856. * set bits 0..6, 14..25, and 28..31
  17857. * 0xf3ffc07f = binary 11110011111111111100000001111111
  17858. */
  17859. var black_mask = 0xf3ffc07f;
  17860. var n;
  17861. /* Check for non-textual ("black-listed") bytes. */
  17862. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  17863. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  17864. return Z_BINARY;
  17865. }
  17866. }
  17867. /* Check for textual ("white-listed") bytes. */
  17868. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  17869. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  17870. return Z_TEXT;
  17871. }
  17872. for (n = 32; n < LITERALS; n++) {
  17873. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  17874. return Z_TEXT;
  17875. }
  17876. }
  17877. /* There are no "black-listed" or "white-listed" bytes:
  17878. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  17879. */
  17880. return Z_BINARY;
  17881. }
  17882. var static_init_done = false;
  17883. /* ===========================================================================
  17884. * Initialize the tree data structures for a new zlib stream.
  17885. */
  17886. function _tr_init(s)
  17887. {
  17888. if (!static_init_done) {
  17889. tr_static_init();
  17890. static_init_done = true;
  17891. }
  17892. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  17893. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  17894. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  17895. s.bi_buf = 0;
  17896. s.bi_valid = 0;
  17897. /* Initialize the first block of the first file: */
  17898. init_block(s);
  17899. }
  17900. /* ===========================================================================
  17901. * Send a stored block
  17902. */
  17903. function _tr_stored_block(s, buf, stored_len, last)
  17904. //DeflateState *s;
  17905. //charf *buf; /* input block */
  17906. //ulg stored_len; /* length of input block */
  17907. //int last; /* one if this is the last block for a file */
  17908. {
  17909. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  17910. copy_block(s, buf, stored_len, true); /* with header */
  17911. }
  17912. /* ===========================================================================
  17913. * Send one empty static block to give enough lookahead for inflate.
  17914. * This takes 10 bits, of which 7 may remain in the bit buffer.
  17915. */
  17916. function _tr_align(s) {
  17917. send_bits(s, STATIC_TREES<<1, 3);
  17918. send_code(s, END_BLOCK, static_ltree);
  17919. bi_flush(s);
  17920. }
  17921. /* ===========================================================================
  17922. * Determine the best encoding for the current block: dynamic trees, static
  17923. * trees or store, and output the encoded block to the zip file.
  17924. */
  17925. function _tr_flush_block(s, buf, stored_len, last)
  17926. //DeflateState *s;
  17927. //charf *buf; /* input block, or NULL if too old */
  17928. //ulg stored_len; /* length of input block */
  17929. //int last; /* one if this is the last block for a file */
  17930. {
  17931. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  17932. var max_blindex = 0; /* index of last bit length code of non zero freq */
  17933. /* Build the Huffman trees unless a stored block is forced */
  17934. if (s.level > 0) {
  17935. /* Check if the file is binary or text */
  17936. if (s.strm.data_type === Z_UNKNOWN) {
  17937. s.strm.data_type = detect_data_type(s);
  17938. }
  17939. /* Construct the literal and distance trees */
  17940. build_tree(s, s.l_desc);
  17941. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  17942. // s->static_len));
  17943. build_tree(s, s.d_desc);
  17944. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  17945. // s->static_len));
  17946. /* At this point, opt_len and static_len are the total bit lengths of
  17947. * the compressed block data, excluding the tree representations.
  17948. */
  17949. /* Build the bit length tree for the above two trees, and get the index
  17950. * in bl_order of the last bit length code to send.
  17951. */
  17952. max_blindex = build_bl_tree(s);
  17953. /* Determine the best encoding. Compute the block lengths in bytes. */
  17954. opt_lenb = (s.opt_len+3+7) >>> 3;
  17955. static_lenb = (s.static_len+3+7) >>> 3;
  17956. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  17957. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  17958. // s->last_lit));
  17959. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  17960. } else {
  17961. // Assert(buf != (char*)0, "lost buf");
  17962. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  17963. }
  17964. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  17965. /* 4: two words for the lengths */
  17966. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  17967. * Otherwise we can't have processed more than WSIZE input bytes since
  17968. * the last block flush, because compression would have been
  17969. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  17970. * transform a block into a stored block.
  17971. */
  17972. _tr_stored_block(s, buf, stored_len, last);
  17973. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  17974. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  17975. compress_block(s, static_ltree, static_dtree);
  17976. } else {
  17977. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  17978. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  17979. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  17980. }
  17981. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  17982. /* The above check is made mod 2^32, for files larger than 512 MB
  17983. * and uLong implemented on 32 bits.
  17984. */
  17985. init_block(s);
  17986. if (last) {
  17987. bi_windup(s);
  17988. }
  17989. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  17990. // s->compressed_len-7*last));
  17991. }
  17992. /* ===========================================================================
  17993. * Save the match info and tally the frequency counts. Return true if
  17994. * the current block must be flushed.
  17995. */
  17996. function _tr_tally(s, dist, lc)
  17997. // deflate_state *s;
  17998. // unsigned dist; /* distance of matched string */
  17999. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18000. {
  18001. //var out_length, in_length, dcode;
  18002. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18003. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18004. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18005. s.last_lit++;
  18006. if (dist === 0) {
  18007. /* lc is the unmatched char */
  18008. s.dyn_ltree[lc*2]/*.Freq*/++;
  18009. } else {
  18010. s.matches++;
  18011. /* Here, lc is the match length - MIN_MATCH */
  18012. dist--; /* dist = match distance - 1 */
  18013. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18014. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18015. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18016. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  18017. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18018. }
  18019. // (!) This block is disabled in zlib defailts,
  18020. // don't enable it for binary compatibility
  18021. //#ifdef TRUNCATE_BLOCK
  18022. // /* Try to guess if it is profitable to stop the current block here */
  18023. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18024. // /* Compute an upper bound for the compressed length */
  18025. // out_length = s.last_lit*8;
  18026. // in_length = s.strstart - s.block_start;
  18027. //
  18028. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18029. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18030. // }
  18031. // out_length >>>= 3;
  18032. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18033. // // s->last_lit, in_length, out_length,
  18034. // // 100L - out_length*100L/in_length));
  18035. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18036. // return true;
  18037. // }
  18038. // }
  18039. //#endif
  18040. return (s.last_lit === s.lit_bufsize-1);
  18041. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18042. * on 16 bit machines and because stored blocks are restricted to
  18043. * 64K-1 bytes.
  18044. */
  18045. }
  18046. exports._tr_init = _tr_init;
  18047. exports._tr_stored_block = _tr_stored_block;
  18048. exports._tr_flush_block = _tr_flush_block;
  18049. exports._tr_tally = _tr_tally;
  18050. exports._tr_align = _tr_align;
  18051. },{"../utils/common":49}],61:[function(require,module,exports){
  18052. 'use strict';
  18053. function ZStream() {
  18054. /* next input byte */
  18055. this.input = null; // JS specific, because we have no pointers
  18056. this.next_in = 0;
  18057. /* number of bytes available at input */
  18058. this.avail_in = 0;
  18059. /* total number of input bytes read so far */
  18060. this.total_in = 0;
  18061. /* next output byte should be put there */
  18062. this.output = null; // JS specific, because we have no pointers
  18063. this.next_out = 0;
  18064. /* remaining free space at output */
  18065. this.avail_out = 0;
  18066. /* total number of bytes output so far */
  18067. this.total_out = 0;
  18068. /* last error message, NULL if no error */
  18069. this.msg = ''/*Z_NULL*/;
  18070. /* not visible by applications */
  18071. this.state = null;
  18072. /* best guess about the data type: binary or text */
  18073. this.data_type = 2/*Z_UNKNOWN*/;
  18074. /* adler32 value of the uncompressed data */
  18075. this.adler = 0;
  18076. }
  18077. module.exports = ZStream;
  18078. },{}],62:[function(require,module,exports){
  18079. /* Copyright @ 2015 Atlassian Pty Ltd
  18080. *
  18081. * Licensed under the Apache License, Version 2.0 (the "License");
  18082. * you may not use this file except in compliance with the License.
  18083. * You may obtain a copy of the License at
  18084. *
  18085. * http://www.apache.org/licenses/LICENSE-2.0
  18086. *
  18087. * Unless required by applicable law or agreed to in writing, software
  18088. * distributed under the License is distributed on an "AS IS" BASIS,
  18089. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18090. * See the License for the specific language governing permissions and
  18091. * limitations under the License.
  18092. */
  18093. module.exports = function arrayEquals(array) {
  18094. // if the other array is a falsy value, return
  18095. if (!array)
  18096. return false;
  18097. // compare lengths - can save a lot of time
  18098. if (this.length != array.length)
  18099. return false;
  18100. for (var i = 0, l = this.length; i < l; i++) {
  18101. // Check if we have nested arrays
  18102. if (this[i] instanceof Array && array[i] instanceof Array) {
  18103. // recurse into the nested arrays
  18104. if (!arrayEquals.apply(this[i], [array[i]]))
  18105. return false;
  18106. } else if (this[i] != array[i]) {
  18107. // Warning - two different object instances will never be equal:
  18108. // {x:20} != {x:20}
  18109. return false;
  18110. }
  18111. }
  18112. return true;
  18113. };
  18114. },{}],63:[function(require,module,exports){
  18115. /* Copyright @ 2015 Atlassian Pty Ltd
  18116. *
  18117. * Licensed under the Apache License, Version 2.0 (the "License");
  18118. * you may not use this file except in compliance with the License.
  18119. * You may obtain a copy of the License at
  18120. *
  18121. * http://www.apache.org/licenses/LICENSE-2.0
  18122. *
  18123. * Unless required by applicable law or agreed to in writing, software
  18124. * distributed under the License is distributed on an "AS IS" BASIS,
  18125. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18126. * See the License for the specific language governing permissions and
  18127. * limitations under the License.
  18128. */
  18129. exports.Interop = require('./interop');
  18130. },{"./interop":64}],64:[function(require,module,exports){
  18131. /* Copyright @ 2015 Atlassian Pty Ltd
  18132. *
  18133. * Licensed under the Apache License, Version 2.0 (the "License");
  18134. * you may not use this file except in compliance with the License.
  18135. * You may obtain a copy of the License at
  18136. *
  18137. * http://www.apache.org/licenses/LICENSE-2.0
  18138. *
  18139. * Unless required by applicable law or agreed to in writing, software
  18140. * distributed under the License is distributed on an "AS IS" BASIS,
  18141. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18142. * See the License for the specific language governing permissions and
  18143. * limitations under the License.
  18144. */
  18145. /* global RTCSessionDescription */
  18146. /* jshint -W097 */
  18147. "use strict";
  18148. var transform = require('./transform');
  18149. var arrayEquals = require('./array-equals');
  18150. function Interop() {
  18151. /**
  18152. * This map holds the most recent Unified Plan offer/answer SDP that was
  18153. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  18154. * the SDP string as values.
  18155. *
  18156. * @type {{}}
  18157. */
  18158. this.cache = {};
  18159. }
  18160. module.exports = Interop;
  18161. /**
  18162. * Returns the index of the first m-line with the given media type and with a
  18163. * direction which allows sending, in the last Unified Plan description with
  18164. * type "answer" converted to Plan B. Returns {null} if there is no saved
  18165. * answer, or if none of its m-lines with the given type allow sending.
  18166. * @param type the media type ("audio" or "video").
  18167. * @returns {*}
  18168. */
  18169. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  18170. if (!this.cache.answer) {
  18171. return null;
  18172. }
  18173. var session = transform.parse(this.cache.answer);
  18174. if (session && session.media && Array.isArray(session.media)){
  18175. for (var i = 0; i < session.media.length; i++) {
  18176. if (session.media[i].type == type &&
  18177. (!session.media[i].direction /* default to sendrecv */ ||
  18178. session.media[i].direction === 'sendrecv' ||
  18179. session.media[i].direction === 'sendonly')){
  18180. return i;
  18181. }
  18182. }
  18183. }
  18184. return null;
  18185. };
  18186. /**
  18187. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  18188. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  18189. * application.
  18190. *
  18191. * @param desc
  18192. * @returns {*}
  18193. */
  18194. Interop.prototype.toPlanB = function(desc) {
  18195. var self = this;
  18196. //#region Preliminary input validation.
  18197. if (typeof desc !== 'object' || desc === null ||
  18198. typeof desc.sdp !== 'string') {
  18199. console.warn('An empty description was passed as an argument.');
  18200. return desc;
  18201. }
  18202. // Objectify the SDP for easier manipulation.
  18203. var session = transform.parse(desc.sdp);
  18204. // If the SDP contains no media, there's nothing to transform.
  18205. if (typeof session.media === 'undefined' ||
  18206. !Array.isArray(session.media) || session.media.length === 0) {
  18207. console.warn('The description has no media.');
  18208. return desc;
  18209. }
  18210. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  18211. // SDP has a video, an audio and a data "channel" at most.
  18212. if (session.media.length <= 3 && session.media.every(function(m) {
  18213. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18214. })) {
  18215. console.warn('This description does not look like Unified Plan.');
  18216. return desc;
  18217. }
  18218. //#endregion
  18219. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  18220. var sdp = desc.sdp;
  18221. var rewrite = false;
  18222. for (var i = 0; i < session.media.length; i++) {
  18223. var uLine = session.media[i];
  18224. uLine.rtp.forEach(function(rtp) {
  18225. if (rtp.codec === 'NULL')
  18226. {
  18227. rewrite = true;
  18228. var offer = transform.parse(self.cache['offer']);
  18229. rtp.codec = offer.media[i].rtp[0].codec;
  18230. }
  18231. });
  18232. };
  18233. if (rewrite) {
  18234. sdp = transform.write(session);
  18235. }
  18236. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  18237. // -> Unified Plan transformation.
  18238. this.cache[desc.type] = sdp;
  18239. //#region Convert from Unified Plan to Plan B.
  18240. // We rebuild the session.media array.
  18241. var media = session.media;
  18242. session.media = [];
  18243. // Associative array that maps channel types to channel objects for fast
  18244. // access to channel objects by their type, e.g. type2bl['audio']->channel
  18245. // obj.
  18246. var type2bl = {};
  18247. // Used to build the group:BUNDLE value after the channels construction
  18248. // loop.
  18249. var types = [];
  18250. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  18251. media.forEach(function(uLine) {
  18252. // rtcp-mux is required in the Plan B SDP.
  18253. if ((typeof uLine.rtcpMux !== 'string' ||
  18254. uLine.rtcpMux !== 'rtcp-mux') &&
  18255. uLine.direction !== 'inactive') {
  18256. throw new Error('Cannot convert to Plan B because m-lines ' +
  18257. 'without the rtcp-mux attribute were found.');
  18258. }
  18259. if (uLine.type === 'application') {
  18260. session.media.push(uLine);
  18261. types.push(uLine.mid);
  18262. return;
  18263. }
  18264. // If we don't have a channel for this uLine.type, then use this
  18265. // uLine as the channel basis.
  18266. if (typeof type2bl[uLine.type] === 'undefined') {
  18267. type2bl[uLine.type] = uLine;
  18268. }
  18269. // Add sources to the channel and handle a=msid.
  18270. if (typeof uLine.sources === 'object') {
  18271. Object.keys(uLine.sources).forEach(function(ssrc) {
  18272. if (typeof type2bl[uLine.type].sources !== 'object')
  18273. type2bl[uLine.type].sources = {};
  18274. // Assign the sources to the channel.
  18275. type2bl[uLine.type].sources[ssrc] =
  18276. uLine.sources[ssrc];
  18277. if (typeof uLine.msid !== 'undefined') {
  18278. // In Plan B the msid is an SSRC attribute. Also, we don't
  18279. // care about the obsolete label and mslabel attributes.
  18280. //
  18281. // Note that it is not guaranteed that the uLine will
  18282. // have an msid. recvonly channels in particular don't have
  18283. // one.
  18284. type2bl[uLine.type].sources[ssrc].msid =
  18285. uLine.msid;
  18286. }
  18287. // NOTE ssrcs in ssrc groups will share msids, as
  18288. // draft-uberti-rtcweb-plan-00 mandates.
  18289. });
  18290. }
  18291. // Add ssrc groups to the channel.
  18292. if (typeof uLine.ssrcGroups !== 'undefined' &&
  18293. Array.isArray(uLine.ssrcGroups)) {
  18294. // Create the ssrcGroups array, if it's not defined.
  18295. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  18296. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  18297. type2bl[uLine.type].ssrcGroups = [];
  18298. }
  18299. type2bl[uLine.type].ssrcGroups =
  18300. type2bl[uLine.type].ssrcGroups.concat(
  18301. uLine.ssrcGroups);
  18302. }
  18303. if (type2bl[uLine.type] === uLine) {
  18304. // Copy ICE related stuff from the principal media line.
  18305. uLine.candidates = media[0].candidates;
  18306. uLine.iceUfrag = media[0].iceUfrag;
  18307. uLine.icePwd = media[0].icePwd;
  18308. uLine.fingerprint = media[0].fingerprint;
  18309. // Plan B mids are in ['audio', 'video', 'data']
  18310. uLine.mid = uLine.type;
  18311. // Plan B doesn't support/need the bundle-only attribute.
  18312. delete uLine.bundleOnly;
  18313. // In Plan B the msid is an SSRC attribute.
  18314. delete uLine.msid;
  18315. // Used to build the group:BUNDLE value after this loop.
  18316. types.push(uLine.type);
  18317. // Add the channel to the new media array.
  18318. session.media.push(uLine);
  18319. }
  18320. });
  18321. // We regenerate the BUNDLE group with the new mids.
  18322. session.groups.some(function(group) {
  18323. if (group.type === 'BUNDLE') {
  18324. group.mids = types.join(' ');
  18325. return true;
  18326. }
  18327. });
  18328. // msid semantic
  18329. session.msidSemantic = {
  18330. semantic: 'WMS',
  18331. token: '*'
  18332. };
  18333. var resStr = transform.write(session);
  18334. return new RTCSessionDescription({
  18335. type: desc.type,
  18336. sdp: resStr
  18337. });
  18338. //#endregion
  18339. };
  18340. /**
  18341. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  18342. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  18343. * to FF.
  18344. *
  18345. * @param desc
  18346. * @returns {*}
  18347. */
  18348. Interop.prototype.toUnifiedPlan = function(desc) {
  18349. var self = this;
  18350. //#region Preliminary input validation.
  18351. if (typeof desc !== 'object' || desc === null ||
  18352. typeof desc.sdp !== 'string') {
  18353. console.warn('An empty description was passed as an argument.');
  18354. return desc;
  18355. }
  18356. var session = transform.parse(desc.sdp);
  18357. // If the SDP contains no media, there's nothing to transform.
  18358. if (typeof session.media === 'undefined' ||
  18359. !Array.isArray(session.media) || session.media.length === 0) {
  18360. console.warn('The description has no media.');
  18361. return desc;
  18362. }
  18363. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  18364. // a video, an audio and a data "channel" at most.
  18365. if (session.media.length > 3 || !session.media.every(function(m) {
  18366. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  18367. })) {
  18368. console.warn('This description does not look like Plan B.');
  18369. return desc;
  18370. }
  18371. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  18372. var mids = [];
  18373. session.media.forEach(function(m) {
  18374. mids.push(m.mid);
  18375. });
  18376. var hasBundle = false;
  18377. if (typeof session.groups !== 'undefined' &&
  18378. Array.isArray(session.groups)) {
  18379. hasBundle = session.groups.every(function(g) {
  18380. return g.type !== 'BUNDLE' ||
  18381. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  18382. });
  18383. }
  18384. if (!hasBundle) {
  18385. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  18386. " are not bundled were found.");
  18387. }
  18388. //#endregion
  18389. //#region Convert from Plan B to Unified Plan.
  18390. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  18391. // rebuild an equivalent Unified Plan offer/answer.
  18392. //
  18393. // For example, if this is a local answer (in Unified Plan style) that we
  18394. // convert to Plan B prior to handing it over to the application (the
  18395. // PeerConnection wrapper called us, for instance, after a successful
  18396. // createAnswer), we want to remember the m-line at which we've seen the
  18397. // (local) SSRC. That's because when the application wants to do call the
  18398. // SLD method, forcing us to do the inverse transformation (from Plan B to
  18399. // Unified Plan), we need to know to which m-line to assign the (local)
  18400. // SSRC. We also need to know all the other m-lines that the original
  18401. // answer had and include them in the transformed answer as well.
  18402. //
  18403. // Another example is if this is a remote offer that we convert to Plan B
  18404. // prior to giving it to the application, we want to remember the mid at
  18405. // which we've seen the (remote) SSRC.
  18406. //
  18407. // In the iteration that follows, we use the cached Unified Plan (if it
  18408. // exists) to assign mids to ssrcs.
  18409. var cached;
  18410. if (typeof this.cache[desc.type] !== 'undefined') {
  18411. cached = transform.parse(this.cache[desc.type]);
  18412. }
  18413. var recvonlySsrcs = {
  18414. audio: {},
  18415. video: {}
  18416. };
  18417. // A helper map that sends mids to m-line objects. We use it later to
  18418. // rebuild the Unified Plan style session.media array.
  18419. var mid2ul = {};
  18420. session.media.forEach(function(bLine) {
  18421. if ((typeof bLine.rtcpMux !== 'string' ||
  18422. bLine.rtcpMux !== 'rtcp-mux') &&
  18423. bLine.direction !== 'inactive') {
  18424. throw new Error("Cannot convert to Unified Plan because m-lines " +
  18425. "without the rtcp-mux attribute were found.");
  18426. }
  18427. if (bLine.type === 'application') {
  18428. mid2ul[bLine.mid] = bLine;
  18429. return;
  18430. }
  18431. // With rtcp-mux and bundle all the channels should have the same ICE
  18432. // stuff.
  18433. var sources = bLine.sources;
  18434. var ssrcGroups = bLine.ssrcGroups;
  18435. var candidates = bLine.candidates;
  18436. var iceUfrag = bLine.iceUfrag;
  18437. var icePwd = bLine.icePwd;
  18438. var fingerprint = bLine.fingerprint;
  18439. var port = bLine.port;
  18440. // We'll use the "bLine" object as a prototype for each new "mLine"
  18441. // that we create, but first we need to clean it up a bit.
  18442. delete bLine.sources;
  18443. delete bLine.ssrcGroups;
  18444. delete bLine.candidates;
  18445. delete bLine.iceUfrag;
  18446. delete bLine.icePwd;
  18447. delete bLine.fingerprint;
  18448. delete bLine.port;
  18449. delete bLine.mid;
  18450. // inverted ssrc group map
  18451. var ssrc2group = {};
  18452. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  18453. ssrcGroups.forEach(function (ssrcGroup) {
  18454. // TODO(gp) find out how to receive simulcast with FF. For the
  18455. // time being, hide it.
  18456. if (ssrcGroup.semantics === 'SIM') {
  18457. return;
  18458. }
  18459. // XXX This might brake if an SSRC is in more than one group
  18460. // for some reason.
  18461. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18462. Array.isArray(ssrcGroup.ssrcs)) {
  18463. ssrcGroup.ssrcs.forEach(function (ssrc) {
  18464. if (typeof ssrc2group[ssrc] === 'undefined') {
  18465. ssrc2group[ssrc] = [];
  18466. }
  18467. ssrc2group[ssrc].push(ssrcGroup);
  18468. });
  18469. }
  18470. });
  18471. }
  18472. // ssrc to m-line index.
  18473. var ssrc2ml = {};
  18474. if (typeof sources === 'object') {
  18475. // Explode the Plan B channel sources with one m-line per source.
  18476. Object.keys(sources).forEach(function(ssrc) {
  18477. // The (unified) m-line for this SSRC. We either create it from
  18478. // scratch or, if it's a grouped SSRC, we re-use a related
  18479. // mline. In other words, if the source is grouped with another
  18480. // source, put the two together in the same m-line.
  18481. var uLine;
  18482. // We assume here that we are the answerer in the O/A, so any
  18483. // offers which we translate come from the remote side, while
  18484. // answers are local. So the check below is to make that we
  18485. // handle receive-only SSRCs in a special way only if they come
  18486. // from the remote side.
  18487. if (desc.type==='offer') {
  18488. // We want to detect SSRCs which are used by a remote peer
  18489. // in an m-line with direction=recvonly (i.e. they are
  18490. // being used for RTCP only).
  18491. // This information would have gotten lost if the remote
  18492. // peer used Unified Plan and their local description was
  18493. // translated to Plan B. So we use the lack of an MSID
  18494. // attribute to deduce a "receive only" SSRC.
  18495. if (!sources[ssrc].msid) {
  18496. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  18497. // Receive-only SSRCs must not create new m-lines. We
  18498. // will assign them to an existing m-line later.
  18499. return;
  18500. }
  18501. }
  18502. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  18503. Array.isArray(ssrc2group[ssrc])) {
  18504. ssrc2group[ssrc].some(function (ssrcGroup) {
  18505. // ssrcGroup.ssrcs *is* an Array, no need to check
  18506. // again here.
  18507. return ssrcGroup.ssrcs.some(function (related) {
  18508. if (typeof ssrc2ml[related] === 'object') {
  18509. uLine = ssrc2ml[related];
  18510. return true;
  18511. }
  18512. });
  18513. });
  18514. }
  18515. if (typeof uLine === 'object') {
  18516. // the m-line already exists. Just add the source.
  18517. uLine.sources[ssrc] = sources[ssrc];
  18518. delete sources[ssrc].msid;
  18519. } else {
  18520. // Use the "bLine" as a prototype for the "uLine".
  18521. uLine = Object.create(bLine);
  18522. ssrc2ml[ssrc] = uLine;
  18523. if (typeof sources[ssrc].msid !== 'undefined') {
  18524. // Assign the msid of the source to the m-line. Note
  18525. // that it is not guaranteed that the source will have
  18526. // msid. In particular "recvonly" sources don't have an
  18527. // msid. Note that "recvonly" is a term only defined
  18528. // for m-lines.
  18529. uLine.msid = sources[ssrc].msid;
  18530. uLine.direction = 'sendrecv';
  18531. delete sources[ssrc].msid;
  18532. }
  18533. // We assign one SSRC per media line.
  18534. uLine.sources = {};
  18535. uLine.sources[ssrc] = sources[ssrc];
  18536. uLine.ssrcGroups = ssrc2group[ssrc];
  18537. // Use the cached Unified Plan SDP (if it exists) to assign
  18538. // SSRCs to mids.
  18539. if (typeof cached !== 'undefined' &&
  18540. typeof cached.media !== 'undefined' &&
  18541. Array.isArray(cached.media)) {
  18542. cached.media.forEach(function (m) {
  18543. if (typeof m.sources === 'object') {
  18544. Object.keys(m.sources).forEach(function (s) {
  18545. if (s === ssrc) {
  18546. uLine.mid = m.mid;
  18547. }
  18548. });
  18549. }
  18550. });
  18551. }
  18552. if (typeof uLine.mid === 'undefined') {
  18553. // If this is an SSRC that we see for the first time
  18554. // assign it a new mid. This is typically the case when
  18555. // this method is called to transform a remote
  18556. // description for the first time or when there is a
  18557. // new SSRC in the remote description because a new
  18558. // peer has joined the conference. Local SSRCs should
  18559. // have already been added to the map in the toPlanB
  18560. // method.
  18561. //
  18562. // Because FF generates answers in Unified Plan style,
  18563. // we MUST already have a cached answer with all the
  18564. // local SSRCs mapped to some m-line/mid.
  18565. if (desc.type === 'answer') {
  18566. throw new Error("An unmapped SSRC was found.");
  18567. }
  18568. uLine.mid = [bLine.type, '-', ssrc].join('');
  18569. }
  18570. // Include the candidates in the 1st media line.
  18571. uLine.candidates = candidates;
  18572. uLine.iceUfrag = iceUfrag;
  18573. uLine.icePwd = icePwd;
  18574. uLine.fingerprint = fingerprint;
  18575. uLine.port = port;
  18576. mid2ul[uLine.mid] = uLine;
  18577. }
  18578. });
  18579. }
  18580. });
  18581. // Rebuild the media array in the right order and add the missing mLines
  18582. // (missing from the Plan B SDP).
  18583. session.media = [];
  18584. mids = []; // reuse
  18585. if (desc.type === 'answer') {
  18586. // The media lines in the answer must match the media lines in the
  18587. // offer. The order is important too. Here we assume that Firefox is
  18588. // the answerer, so we merely have to use the reconstructed (unified)
  18589. // answer to update the cached (unified) answer accordingly.
  18590. //
  18591. // In the general case, one would have to use the cached (unified)
  18592. // offer to find the m-lines that are missing from the reconstructed
  18593. // answer, potentially grabbing them from the cached (unified) answer.
  18594. // One has to be careful with this approach because inactive m-lines do
  18595. // not always have an mid, making it tricky (impossible?) to find where
  18596. // exactly and which m-lines are missing from the reconstructed answer.
  18597. for (var i = 0; i < cached.media.length; i++) {
  18598. var uLine = cached.media[i];
  18599. if (typeof mid2ul[uLine.mid] === 'undefined') {
  18600. // The mid isn't in the reconstructed (unified) answer.
  18601. // This is either a (unified) m-line containing a remote
  18602. // track only, or a (unified) m-line containing a remote
  18603. // track and a local track that has been removed.
  18604. // In either case, it MUST exist in the cached
  18605. // (unified) answer.
  18606. //
  18607. // In case this is a removed local track, clean-up
  18608. // the (unified) m-line and make sure it's 'recvonly' or
  18609. // 'inactive'.
  18610. delete uLine.msid;
  18611. delete uLine.sources;
  18612. delete uLine.ssrcGroups;
  18613. if (!uLine.direction
  18614. || uLine.direction === 'sendrecv')
  18615. uLine.direction = 'recvonly';
  18616. else if (uLine.direction === 'sendonly')
  18617. uLine.direction = 'inactive';
  18618. } else {
  18619. // This is an (unified) m-line/channel that contains a local
  18620. // track (sendrecv or sendonly channel) or it's a unified
  18621. // recvonly m-line/channel. In either case, since we're
  18622. // going from PlanB -> Unified Plan this m-line MUST
  18623. // exist in the cached answer.
  18624. }
  18625. session.media.push(uLine);
  18626. if (typeof uLine.mid === 'string') {
  18627. // inactive lines don't/may not have an mid.
  18628. mids.push(uLine.mid);
  18629. }
  18630. }
  18631. } else {
  18632. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  18633. // under any circumstances. If we are no longer interested in sending a
  18634. // track, we just remove the msid and ssrc attributes and set it to
  18635. // either a=recvonly (as the reofferer, we must use recvonly if the
  18636. // other side was previously sending on the m-section, but we can also
  18637. // leave the possibility open if it wasn't previously in use), or
  18638. // a=inactive.
  18639. if (typeof cached !== 'undefined' &&
  18640. typeof cached.media !== 'undefined' &&
  18641. Array.isArray(cached.media)) {
  18642. cached.media.forEach(function(uLine) {
  18643. mids.push(uLine.mid);
  18644. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  18645. session.media.push(mid2ul[uLine.mid]);
  18646. } else {
  18647. delete uLine.msid;
  18648. delete uLine.sources;
  18649. delete uLine.ssrcGroups;
  18650. if (!uLine.direction
  18651. || uLine.direction === 'sendrecv')
  18652. uLine.direction = 'recvonly';
  18653. if (!uLine.direction
  18654. || uLine.direction === 'sendonly')
  18655. uLine.direction = 'inactive';
  18656. session.media.push(uLine);
  18657. }
  18658. });
  18659. }
  18660. // Add all the remaining (new) m-lines of the transformed SDP.
  18661. Object.keys(mid2ul).forEach(function(mid) {
  18662. if (mids.indexOf(mid) === -1) {
  18663. mids.push(mid);
  18664. if (mid2ul[mid].direction === 'recvonly') {
  18665. // This is a remote recvonly channel. Add its SSRC to the
  18666. // appropriate sendrecv or sendonly channel.
  18667. // TODO(gp) what if we don't have sendrecv/sendonly
  18668. // channel?
  18669. session.media.some(function (uLine) {
  18670. if ((uLine.direction === 'sendrecv' ||
  18671. uLine.direction === 'sendonly') &&
  18672. uLine.type === mid2ul[mid].type) {
  18673. // mid2ul[mid] shouldn't have any ssrc-groups
  18674. Object.keys(mid2ul[mid].sources).forEach(
  18675. function (ssrc) {
  18676. uLine.sources[ssrc] =
  18677. mid2ul[mid].sources[ssrc];
  18678. });
  18679. return true;
  18680. }
  18681. });
  18682. } else {
  18683. session.media.push(mid2ul[mid]);
  18684. }
  18685. }
  18686. });
  18687. }
  18688. // After we have constructed the Plan Unified m-lines we can figure out
  18689. // where (in which m-line) to place the 'recvonly SSRCs'.
  18690. // Note: we assume here that we are the answerer in the O/A, so any offers
  18691. // which we translate come from the remote side, while answers are local
  18692. // (and so our last local description is cached as an 'answer').
  18693. ["audio", "video"].forEach(function (type) {
  18694. if (!session || !session.media || !Array.isArray(session.media))
  18695. return;
  18696. var idx = null;
  18697. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  18698. idx = self.getFirstSendingIndexFromAnswer(type);
  18699. if (idx === null){
  18700. // If this is the first offer we receive, we don't have a
  18701. // cached answer. Assume that we will be sending media using
  18702. // the first m-line for each media type.
  18703. for (var i = 0; i < session.media.length; i++) {
  18704. if (session.media[i].type === type) {
  18705. idx = i;
  18706. break;
  18707. }
  18708. }
  18709. }
  18710. }
  18711. if (idx && session.media.length > idx) {
  18712. var mLine = session.media[idx];
  18713. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  18714. if (mLine.sources && mLine.sources[ssrc]) {
  18715. console.warn("Replacing an existing SSRC.");
  18716. }
  18717. if (!mLine.sources) {
  18718. mLine.sources = {};
  18719. }
  18720. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  18721. });
  18722. }
  18723. });
  18724. // We regenerate the BUNDLE group (since we regenerated the mids)
  18725. session.groups.some(function(group) {
  18726. if (group.type === 'BUNDLE') {
  18727. group.mids = mids.join(' ');
  18728. return true;
  18729. }
  18730. });
  18731. // msid semantic
  18732. session.msidSemantic = {
  18733. semantic: 'WMS',
  18734. token: '*'
  18735. };
  18736. var resStr = transform.write(session);
  18737. // Cache the transformed SDP (Unified Plan) for later re-use in this
  18738. // function.
  18739. this.cache[desc.type] = resStr;
  18740. return new RTCSessionDescription({
  18741. type: desc.type,
  18742. sdp: resStr
  18743. });
  18744. //#endregion
  18745. };
  18746. },{"./array-equals":62,"./transform":65}],65:[function(require,module,exports){
  18747. /* Copyright @ 2015 Atlassian Pty Ltd
  18748. *
  18749. * Licensed under the Apache License, Version 2.0 (the "License");
  18750. * you may not use this file except in compliance with the License.
  18751. * You may obtain a copy of the License at
  18752. *
  18753. * http://www.apache.org/licenses/LICENSE-2.0
  18754. *
  18755. * Unless required by applicable law or agreed to in writing, software
  18756. * distributed under the License is distributed on an "AS IS" BASIS,
  18757. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18758. * See the License for the specific language governing permissions and
  18759. * limitations under the License.
  18760. */
  18761. var transform = require('sdp-transform');
  18762. exports.write = function(session, opts) {
  18763. if (typeof session !== 'undefined' &&
  18764. typeof session.media !== 'undefined' &&
  18765. Array.isArray(session.media)) {
  18766. session.media.forEach(function (mLine) {
  18767. // expand sources to ssrcs
  18768. if (typeof mLine.sources !== 'undefined' &&
  18769. Object.keys(mLine.sources).length !== 0) {
  18770. mLine.ssrcs = [];
  18771. Object.keys(mLine.sources).forEach(function (ssrc) {
  18772. var source = mLine.sources[ssrc];
  18773. Object.keys(source).forEach(function (attribute) {
  18774. mLine.ssrcs.push({
  18775. id: ssrc,
  18776. attribute: attribute,
  18777. value: source[attribute]
  18778. });
  18779. });
  18780. });
  18781. delete mLine.sources;
  18782. }
  18783. // join ssrcs in ssrc groups
  18784. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18785. Array.isArray(mLine.ssrcGroups)) {
  18786. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  18787. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  18788. Array.isArray(ssrcGroup.ssrcs)) {
  18789. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  18790. }
  18791. });
  18792. }
  18793. });
  18794. }
  18795. // join group mids
  18796. if (typeof session !== 'undefined' &&
  18797. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  18798. session.groups.forEach(function (g) {
  18799. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  18800. g.mids = g.mids.join(' ');
  18801. }
  18802. });
  18803. }
  18804. return transform.write(session, opts);
  18805. };
  18806. exports.parse = function(sdp) {
  18807. var session = transform.parse(sdp);
  18808. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  18809. Array.isArray(session.media)) {
  18810. session.media.forEach(function (mLine) {
  18811. // group sources attributes by ssrc
  18812. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  18813. mLine.sources = {};
  18814. mLine.ssrcs.forEach(function (ssrc) {
  18815. if (!mLine.sources[ssrc.id])
  18816. mLine.sources[ssrc.id] = {};
  18817. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  18818. });
  18819. delete mLine.ssrcs;
  18820. }
  18821. // split ssrcs in ssrc groups
  18822. if (typeof mLine.ssrcGroups !== 'undefined' &&
  18823. Array.isArray(mLine.ssrcGroups)) {
  18824. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  18825. if (typeof ssrcGroup.ssrcs === 'string') {
  18826. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  18827. }
  18828. });
  18829. }
  18830. });
  18831. }
  18832. // split group mids
  18833. if (typeof session !== 'undefined' &&
  18834. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  18835. session.groups.forEach(function (g) {
  18836. if (typeof g.mids === 'string') {
  18837. g.mids = g.mids.split(' ');
  18838. }
  18839. });
  18840. }
  18841. return session;
  18842. };
  18843. },{"sdp-transform":73}],66:[function(require,module,exports){
  18844. /* Copyright @ 2015 Atlassian Pty Ltd
  18845. *
  18846. * Licensed under the Apache License, Version 2.0 (the "License");
  18847. * you may not use this file except in compliance with the License.
  18848. * You may obtain a copy of the License at
  18849. *
  18850. * http://www.apache.org/licenses/LICENSE-2.0
  18851. *
  18852. * Unless required by applicable law or agreed to in writing, software
  18853. * distributed under the License is distributed on an "AS IS" BASIS,
  18854. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18855. * See the License for the specific language governing permissions and
  18856. * limitations under the License.
  18857. */
  18858. var transform = require('sdp-transform');
  18859. var transformUtils = require('./transform-utils');
  18860. var parseSsrcs = transformUtils.parseSsrcs;
  18861. var writeSsrcs = transformUtils.writeSsrcs;
  18862. //region Constants
  18863. var DEFAULT_NUM_OF_LAYERS = 3;
  18864. //endregion
  18865. //region Ctor
  18866. function Simulcast(options) {
  18867. this.options = options ? options : {};
  18868. if (!this.options.numOfLayers) {
  18869. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  18870. }
  18871. this.layers = [];
  18872. }
  18873. //endregion
  18874. //region Stateless private utility functions
  18875. /**
  18876. * Returns a random integer between min (included) and max (excluded)
  18877. * Using Math.round() gives a non-uniform distribution!
  18878. * @returns {number}
  18879. */
  18880. function generateSSRC() {
  18881. var min = 0, max = 0xffffffff;
  18882. return Math.floor(Math.random() * (max - min)) + min;
  18883. };
  18884. function processVideo(session, action) {
  18885. if (session == null || !Array.isArray(session.media)) {
  18886. return;
  18887. }
  18888. session.media.forEach(function (mLine) {
  18889. if (mLine.type === 'video') {
  18890. action(mLine);
  18891. }
  18892. });
  18893. }
  18894. function validateDescription(desc)
  18895. {
  18896. return desc && desc != null
  18897. && desc.type && desc.type != ''
  18898. && desc.sdp && desc.sdp != '';
  18899. }
  18900. function explodeRemoteSimulcast(mLine) {
  18901. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18902. return;
  18903. }
  18904. var sources = parseSsrcs(mLine);
  18905. var order = [];
  18906. // Find the SIM group and explode its sources.
  18907. var j = mLine.ssrcGroups.length;
  18908. while (j--) {
  18909. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  18910. continue;
  18911. }
  18912. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  18913. for (var i = 0; i < simulcastSsrcs.length; i++) {
  18914. var ssrc = simulcastSsrcs[i];
  18915. order.push(ssrc);
  18916. var parts = sources[ssrc].msid.split(' ');
  18917. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  18918. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  18919. // Remove all the groups that this SSRC participates in.
  18920. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18921. if (relatedGroup.semantics === 'SIM') {
  18922. return;
  18923. }
  18924. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18925. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18926. return;
  18927. }
  18928. // Nuke all the related SSRCs.
  18929. relatedSsrcs.forEach(function (relatedSSRC) {
  18930. sources[relatedSSRC].msid = sources[ssrc].msid;
  18931. sources[relatedSSRC].cname = sources[ssrc].cname;
  18932. if (relatedSSRC !== ssrc) {
  18933. order.push(relatedSSRC);
  18934. }
  18935. });
  18936. // Schedule the related group for nuking.
  18937. })
  18938. }
  18939. mLine.ssrcs = writeSsrcs(sources, order);
  18940. mLine.ssrcGroups.splice(j, 1);
  18941. };
  18942. }
  18943. function implodeRemoteSimulcast(mLine) {
  18944. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  18945. console.debug('Halt: There are no SSRC groups in the remote ' +
  18946. 'description.');
  18947. return;
  18948. }
  18949. var sources = parseSsrcs(mLine);
  18950. // Find the SIM group and nuke it.
  18951. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  18952. if (simulcastGroup.semantics !== 'SIM') {
  18953. return;
  18954. }
  18955. console.debug("Imploding SIM group: " + simulcastGroup.ssrcs);
  18956. // Schedule the SIM group for nuking.
  18957. simulcastGroup.nuke = true;
  18958. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  18959. // Nuke all the higher layer SSRCs.
  18960. for (var i = 1; i < simulcastSsrcs.length; i++) {
  18961. var ssrc = simulcastSsrcs[i];
  18962. delete sources[ssrc];
  18963. // Remove all the groups that this SSRC participates in.
  18964. mLine.ssrcGroups.forEach(function (relatedGroup) {
  18965. if (relatedGroup.semantics === 'SIM') {
  18966. return;
  18967. }
  18968. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  18969. if (relatedSsrcs.indexOf(ssrc) === -1) {
  18970. return;
  18971. }
  18972. // Nuke all the related SSRCs.
  18973. relatedSsrcs.forEach(function (relatedSSRC) {
  18974. delete sources[relatedSSRC];
  18975. });
  18976. // Schedule the related group for nuking.
  18977. relatedGroup.nuke = true;
  18978. })
  18979. }
  18980. return;
  18981. });
  18982. mLine.ssrcs = writeSsrcs(sources);
  18983. // Nuke all the scheduled groups.
  18984. var i = mLine.ssrcGroups.length;
  18985. while (i--) {
  18986. if (mLine.ssrcGroups[i].nuke) {
  18987. mLine.ssrcGroups.splice(i, 1);
  18988. }
  18989. }
  18990. }
  18991. function removeGoogConference(mLine) {
  18992. if (!mLine || !Array.isArray(mLine.invalid)) {
  18993. return;
  18994. }
  18995. var i = mLine.invalid.length;
  18996. while (i--) {
  18997. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  18998. mLine.invalid.splice(i, 1);
  18999. }
  19000. }
  19001. }
  19002. function assertGoogConference(mLine) {
  19003. if (!mLine) {
  19004. return;
  19005. }
  19006. if (!Array.isArray(mLine.invalid)) {
  19007. mLine.invalid = [];
  19008. }
  19009. if (!mLine.invalid.some(
  19010. function (i) { return i.value === 'x-google-flag:conference' })) {
  19011. mLine.invalid.push({'value': 'x-google-flag:conference'});
  19012. }
  19013. }
  19014. //endregion
  19015. //region "Private" functions
  19016. /**
  19017. *
  19018. * @param mLine
  19019. * @private
  19020. */
  19021. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  19022. if (!mLine || mLine.type !== 'video') {
  19023. return;
  19024. }
  19025. var sources = parseSsrcs(mLine);
  19026. if (Object.keys(sources).length === 0) {
  19027. // no sources, disable simulcast.
  19028. if (this.layers.length !== 0) {
  19029. this.layers = [];
  19030. }
  19031. return;
  19032. }
  19033. // find the base layer (we'll reuse its msid and cname).
  19034. var baseLayerSSRC = Object.keys(sources)[0];
  19035. var baseLayer = sources[baseLayerSSRC];
  19036. // todo(gp) handle screen sharing.
  19037. // check if base CNAME has changed and reinitialise layers.
  19038. if (this.layers.length > 0
  19039. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  19040. this.layers = [];
  19041. }
  19042. // (re)initialise layers
  19043. if (this.layers.length < 1) {
  19044. // first push the base layer.
  19045. this.layers.push({
  19046. ssrc: baseLayerSSRC,
  19047. msid: baseLayer.msid,
  19048. cname: baseLayer.cname
  19049. });
  19050. var rtx = false; // RFC 4588
  19051. if (Array.isArray(mLine.rtp)) {
  19052. rtx = mLine.rtp.some(
  19053. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  19054. }
  19055. if (rtx) {
  19056. this.layers[0].rtx = generateSSRC();
  19057. }
  19058. // now push additional layers.
  19059. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  19060. var layer = { ssrc: generateSSRC() };
  19061. if (rtx) {
  19062. layer.rtx = generateSSRC();
  19063. }
  19064. this.layers.push(layer);
  19065. }
  19066. }
  19067. };
  19068. /**
  19069. *
  19070. * @param mLine
  19071. * @private
  19072. */
  19073. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  19074. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  19075. var sources = {};
  19076. var msid = this.layers[0].msid;
  19077. var cname = this.layers[0].cname;
  19078. var simulcastSsrcs = [];
  19079. var ssrcGroups = [];
  19080. for (var i = 0; i < this.layers.length; i++) {
  19081. var layer = this.layers[i];
  19082. sources[layer.ssrc] = { msid: msid, cname: cname };
  19083. simulcastSsrcs.push(layer.ssrc);
  19084. if (layer.rtx) {
  19085. sources[layer.rtx] = {
  19086. msid: msid,
  19087. cname: cname
  19088. }
  19089. ssrcGroups.push({
  19090. semantics: 'FID',
  19091. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  19092. });
  19093. }
  19094. }
  19095. ssrcGroups.push({
  19096. semantics: 'SIM',
  19097. ssrcs: simulcastSsrcs.join(' ')
  19098. });
  19099. mLine.ssrcGroups = ssrcGroups;
  19100. mLine.ssrcs = writeSsrcs(sources);
  19101. }
  19102. }
  19103. //endregion
  19104. //region "Public" functions
  19105. Simulcast.prototype.isSupported = function () {
  19106. return window.chrome;
  19107. // TODO this needs improvements. For example I doubt that Chrome in Android
  19108. // has simulcast support. Also, only recent versions of Chromium have native
  19109. // simulcast support.
  19110. }
  19111. /**
  19112. *
  19113. * @param desc
  19114. * @returns {RTCSessionDescription}
  19115. */
  19116. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  19117. if (!validateDescription(desc)) {
  19118. return desc;
  19119. }
  19120. var session = transform.parse(desc.sdp);
  19121. var self = this;
  19122. processVideo(session, function (mLine) {
  19123. // Handle simulcast reception.
  19124. if (self.options.explodeRemoteSimulcast) {
  19125. explodeRemoteSimulcast(mLine);
  19126. } else {
  19127. implodeRemoteSimulcast(mLine);
  19128. }
  19129. // If native simulcast is enabled, we must append the x-goog-conference
  19130. // attribute to the SDP.
  19131. if (self.layers.length < 1) {
  19132. removeGoogConference(mLine);
  19133. } else {
  19134. assertGoogConference(mLine);
  19135. }
  19136. });
  19137. return new RTCSessionDescription({
  19138. type: desc.type,
  19139. sdp: transform.write(session)
  19140. });
  19141. };
  19142. /**
  19143. *
  19144. * @param desc
  19145. * @returns {RTCSessionDescription}
  19146. */
  19147. Simulcast.prototype.mungeLocalDescription = function (desc) {
  19148. if (!validateDescription(desc) || !this.isSupported()) {
  19149. return desc;
  19150. }
  19151. var session = transform.parse(desc.sdp);
  19152. var self = this;
  19153. processVideo(session, function (mLine) {
  19154. // Initialize native simulcast layers, if not already done.
  19155. self._maybeInitializeLayers(mLine);
  19156. // Update the SDP with the simulcast layers.
  19157. self._restoreSimulcastView(mLine);
  19158. });
  19159. return new RTCSessionDescription({
  19160. type: desc.type,
  19161. sdp: transform.write(session)
  19162. });
  19163. };
  19164. //endregion
  19165. module.exports = Simulcast;
  19166. },{"./transform-utils":67,"sdp-transform":69}],67:[function(require,module,exports){
  19167. /* Copyright @ 2015 Atlassian Pty Ltd
  19168. *
  19169. * Licensed under the Apache License, Version 2.0 (the "License");
  19170. * you may not use this file except in compliance with the License.
  19171. * You may obtain a copy of the License at
  19172. *
  19173. * http://www.apache.org/licenses/LICENSE-2.0
  19174. *
  19175. * Unless required by applicable law or agreed to in writing, software
  19176. * distributed under the License is distributed on an "AS IS" BASIS,
  19177. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19178. * See the License for the specific language governing permissions and
  19179. * limitations under the License.
  19180. */
  19181. exports.writeSsrcs = function(sources, order) {
  19182. var ssrcs = [];
  19183. // expand sources to ssrcs
  19184. if (typeof sources !== 'undefined' &&
  19185. Object.keys(sources).length !== 0) {
  19186. if (Array.isArray(order)) {
  19187. for (var i = 0; i < order.length; i++) {
  19188. var ssrc = order[i];
  19189. var source = sources[ssrc];
  19190. Object.keys(source).forEach(function (attribute) {
  19191. ssrcs.push({
  19192. id: ssrc,
  19193. attribute: attribute,
  19194. value: source[attribute]
  19195. });
  19196. });
  19197. }
  19198. } else {
  19199. Object.keys(sources).forEach(function (ssrc) {
  19200. var source = sources[ssrc];
  19201. Object.keys(source).forEach(function (attribute) {
  19202. ssrcs.push({
  19203. id: ssrc,
  19204. attribute: attribute,
  19205. value: source[attribute]
  19206. });
  19207. });
  19208. });
  19209. }
  19210. }
  19211. return ssrcs;
  19212. };
  19213. exports.parseSsrcs = function (mLine) {
  19214. var sources = {};
  19215. // group sources attributes by ssrc.
  19216. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  19217. mLine.ssrcs.forEach(function (ssrc) {
  19218. if (!sources[ssrc.id])
  19219. sources[ssrc.id] = {};
  19220. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  19221. });
  19222. }
  19223. return sources;
  19224. };
  19225. },{}],68:[function(require,module,exports){
  19226. var grammar = module.exports = {
  19227. v: [{
  19228. name: 'version',
  19229. reg: /^(\d*)$/
  19230. }],
  19231. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19232. // NB: sessionId will be a String in most cases because it is huge
  19233. name: 'origin',
  19234. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19235. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19236. format: "%s %s %d %s IP%d %s"
  19237. }],
  19238. // default parsing of these only (though some of these feel outdated)
  19239. s: [{ name: 'name' }],
  19240. i: [{ name: 'description' }],
  19241. u: [{ name: 'uri' }],
  19242. e: [{ name: 'email' }],
  19243. p: [{ name: 'phone' }],
  19244. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19245. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19246. //k: [{}], // outdated thing ignored
  19247. t: [{ //t=0 0
  19248. name: 'timing',
  19249. reg: /^(\d*) (\d*)/,
  19250. names: ['start', 'stop'],
  19251. format: "%d %d"
  19252. }],
  19253. c: [{ //c=IN IP4 10.47.197.26
  19254. name: 'connection',
  19255. reg: /^IN IP(\d) (\S*)/,
  19256. names: ['version', 'ip'],
  19257. format: "IN IP%d %s"
  19258. }],
  19259. b: [{ //b=AS:4000
  19260. push: 'bandwidth',
  19261. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19262. names: ['type', 'limit'],
  19263. format: "%s:%s"
  19264. }],
  19265. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19266. // NB: special - pushes to session
  19267. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19268. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19269. names: ['type', 'port', 'protocol', 'payloads'],
  19270. format: "%s %d %s %s"
  19271. }],
  19272. a: [
  19273. { //a=rtpmap:110 opus/48000/2
  19274. push: 'rtp',
  19275. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19276. names: ['payload', 'codec', 'rate', 'encoding'],
  19277. format: function (o) {
  19278. return (o.encoding) ?
  19279. "rtpmap:%d %s/%s/%s":
  19280. "rtpmap:%d %s/%s";
  19281. }
  19282. },
  19283. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19284. push: 'fmtp',
  19285. reg: /^fmtp:(\d*) (\S*)/,
  19286. names: ['payload', 'config'],
  19287. format: "fmtp:%d %s"
  19288. },
  19289. { //a=control:streamid=0
  19290. name: 'control',
  19291. reg: /^control:(.*)/,
  19292. format: "control:%s"
  19293. },
  19294. { //a=rtcp:65179 IN IP4 193.84.77.194
  19295. name: 'rtcp',
  19296. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19297. names: ['port', 'netType', 'ipVer', 'address'],
  19298. format: function (o) {
  19299. return (o.address != null) ?
  19300. "rtcp:%d %s IP%d %s":
  19301. "rtcp:%d";
  19302. }
  19303. },
  19304. { //a=rtcp-fb:98 trr-int 100
  19305. push: 'rtcpFbTrrInt',
  19306. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19307. names: ['payload', 'value'],
  19308. format: "rtcp-fb:%d trr-int %d"
  19309. },
  19310. { //a=rtcp-fb:98 nack rpsi
  19311. push: 'rtcpFb',
  19312. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19313. names: ['payload', 'type', 'subtype'],
  19314. format: function (o) {
  19315. return (o.subtype != null) ?
  19316. "rtcp-fb:%s %s %s":
  19317. "rtcp-fb:%s %s";
  19318. }
  19319. },
  19320. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19321. //a=extmap:1/recvonly URI-gps-string
  19322. push: 'ext',
  19323. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19324. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19325. format: function (o) {
  19326. return (o.config != null) ?
  19327. "extmap:%s %s %s":
  19328. "extmap:%s %s";
  19329. }
  19330. },
  19331. {
  19332. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19333. push: 'crypto',
  19334. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19335. names: ['id', 'suite', 'config', 'sessionConfig'],
  19336. format: function (o) {
  19337. return (o.sessionConfig != null) ?
  19338. "crypto:%d %s %s %s":
  19339. "crypto:%d %s %s";
  19340. }
  19341. },
  19342. { //a=setup:actpass
  19343. name: 'setup',
  19344. reg: /^setup:(\w*)/,
  19345. format: "setup:%s"
  19346. },
  19347. { //a=mid:1
  19348. name: 'mid',
  19349. reg: /^mid:([^\s]*)/,
  19350. format: "mid:%s"
  19351. },
  19352. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19353. name: 'msid',
  19354. reg: /^msid:(.*)/,
  19355. format: "msid:%s"
  19356. },
  19357. { //a=ptime:20
  19358. name: 'ptime',
  19359. reg: /^ptime:(\d*)/,
  19360. format: "ptime:%d"
  19361. },
  19362. { //a=maxptime:60
  19363. name: 'maxptime',
  19364. reg: /^maxptime:(\d*)/,
  19365. format: "maxptime:%d"
  19366. },
  19367. { //a=sendrecv
  19368. name: 'direction',
  19369. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19370. },
  19371. { //a=ice-lite
  19372. name: 'icelite',
  19373. reg: /^(ice-lite)/
  19374. },
  19375. { //a=ice-ufrag:F7gI
  19376. name: 'iceUfrag',
  19377. reg: /^ice-ufrag:(\S*)/,
  19378. format: "ice-ufrag:%s"
  19379. },
  19380. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19381. name: 'icePwd',
  19382. reg: /^ice-pwd:(\S*)/,
  19383. format: "ice-pwd:%s"
  19384. },
  19385. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19386. name: 'fingerprint',
  19387. reg: /^fingerprint:(\S*) (\S*)/,
  19388. names: ['type', 'hash'],
  19389. format: "fingerprint:%s %s"
  19390. },
  19391. {
  19392. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19393. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19394. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19395. push:'candidates',
  19396. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19397. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19398. format: function (o) {
  19399. var str = "candidate:%s %d %s %d %s %d typ %s";
  19400. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19401. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19402. if (o.generation != null) {
  19403. str += " generation %d";
  19404. }
  19405. return str;
  19406. }
  19407. },
  19408. { //a=end-of-candidates (keep after the candidates line for readability)
  19409. name: 'endOfCandidates',
  19410. reg: /^(end-of-candidates)/
  19411. },
  19412. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19413. name: 'remoteCandidates',
  19414. reg: /^remote-candidates:(.*)/,
  19415. format: "remote-candidates:%s"
  19416. },
  19417. { //a=ice-options:google-ice
  19418. name: 'iceOptions',
  19419. reg: /^ice-options:(\S*)/,
  19420. format: "ice-options:%s"
  19421. },
  19422. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19423. push: "ssrcs",
  19424. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19425. names: ['id', 'attribute', 'value'],
  19426. format: "ssrc:%d %s:%s"
  19427. },
  19428. { //a=ssrc-group:FEC 1 2
  19429. push: "ssrcGroups",
  19430. reg: /^ssrc-group:(\w*) (.*)/,
  19431. names: ['semantics', 'ssrcs'],
  19432. format: "ssrc-group:%s %s"
  19433. },
  19434. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19435. name: "msidSemantic",
  19436. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19437. names: ['semantic', 'token'],
  19438. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19439. },
  19440. { //a=group:BUNDLE audio video
  19441. push: 'groups',
  19442. reg: /^group:(\w*) (.*)/,
  19443. names: ['type', 'mids'],
  19444. format: "group:%s %s"
  19445. },
  19446. { //a=rtcp-mux
  19447. name: 'rtcpMux',
  19448. reg: /^(rtcp-mux)/
  19449. },
  19450. { //a=rtcp-rsize
  19451. name: 'rtcpRsize',
  19452. reg: /^(rtcp-rsize)/
  19453. },
  19454. { // any a= that we don't understand is kepts verbatim on media.invalid
  19455. push: 'invalid',
  19456. names: ["value"]
  19457. }
  19458. ]
  19459. };
  19460. // set sensible defaults to avoid polluting the grammar with boring details
  19461. Object.keys(grammar).forEach(function (key) {
  19462. var objs = grammar[key];
  19463. objs.forEach(function (obj) {
  19464. if (!obj.reg) {
  19465. obj.reg = /(.*)/;
  19466. }
  19467. if (!obj.format) {
  19468. obj.format = "%s";
  19469. }
  19470. });
  19471. });
  19472. },{}],69:[function(require,module,exports){
  19473. var parser = require('./parser');
  19474. var writer = require('./writer');
  19475. exports.write = writer;
  19476. exports.parse = parser.parse;
  19477. exports.parseFmtpConfig = parser.parseFmtpConfig;
  19478. exports.parsePayloads = parser.parsePayloads;
  19479. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  19480. },{"./parser":70,"./writer":71}],70:[function(require,module,exports){
  19481. var toIntIfInt = function (v) {
  19482. return String(Number(v)) === v ? Number(v) : v;
  19483. };
  19484. var attachProperties = function (match, location, names, rawName) {
  19485. if (rawName && !names) {
  19486. location[rawName] = toIntIfInt(match[1]);
  19487. }
  19488. else {
  19489. for (var i = 0; i < names.length; i += 1) {
  19490. if (match[i+1] != null) {
  19491. location[names[i]] = toIntIfInt(match[i+1]);
  19492. }
  19493. }
  19494. }
  19495. };
  19496. var parseReg = function (obj, location, content) {
  19497. var needsBlank = obj.name && obj.names;
  19498. if (obj.push && !location[obj.push]) {
  19499. location[obj.push] = [];
  19500. }
  19501. else if (needsBlank && !location[obj.name]) {
  19502. location[obj.name] = {};
  19503. }
  19504. var keyLocation = obj.push ?
  19505. {} : // blank object that will be pushed
  19506. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19507. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19508. if (obj.push) {
  19509. location[obj.push].push(keyLocation);
  19510. }
  19511. };
  19512. var grammar = require('./grammar');
  19513. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19514. exports.parse = function (sdp) {
  19515. var session = {}
  19516. , media = []
  19517. , location = session; // points at where properties go under (one of the above)
  19518. // parse lines we understand
  19519. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19520. var type = l[0];
  19521. var content = l.slice(2);
  19522. if (type === 'm') {
  19523. media.push({rtp: [], fmtp: []});
  19524. location = media[media.length-1]; // point at latest media line
  19525. }
  19526. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19527. var obj = grammar[type][j];
  19528. if (obj.reg.test(content)) {
  19529. return parseReg(obj, location, content);
  19530. }
  19531. }
  19532. });
  19533. session.media = media; // link it up
  19534. return session;
  19535. };
  19536. var fmtpReducer = function (acc, expr) {
  19537. var s = expr.split('=');
  19538. if (s.length === 2) {
  19539. acc[s[0]] = toIntIfInt(s[1]);
  19540. }
  19541. return acc;
  19542. };
  19543. exports.parseFmtpConfig = function (str) {
  19544. return str.split(';').reduce(fmtpReducer, {});
  19545. };
  19546. exports.parsePayloads = function (str) {
  19547. return str.split(' ').map(Number);
  19548. };
  19549. exports.parseRemoteCandidates = function (str) {
  19550. var candidates = [];
  19551. var parts = str.split(' ').map(toIntIfInt);
  19552. for (var i = 0; i < parts.length; i += 3) {
  19553. candidates.push({
  19554. component: parts[i],
  19555. ip: parts[i + 1],
  19556. port: parts[i + 2]
  19557. });
  19558. }
  19559. return candidates;
  19560. };
  19561. },{"./grammar":68}],71:[function(require,module,exports){
  19562. var grammar = require('./grammar');
  19563. // customized util.format - discards excess arguments and can void middle ones
  19564. var formatRegExp = /%[sdv%]/g;
  19565. var format = function (formatStr) {
  19566. var i = 1;
  19567. var args = arguments;
  19568. var len = args.length;
  19569. return formatStr.replace(formatRegExp, function (x) {
  19570. if (i >= len) {
  19571. return x; // missing argument
  19572. }
  19573. var arg = args[i];
  19574. i += 1;
  19575. switch (x) {
  19576. case '%%':
  19577. return '%';
  19578. case '%s':
  19579. return String(arg);
  19580. case '%d':
  19581. return Number(arg);
  19582. case '%v':
  19583. return '';
  19584. }
  19585. });
  19586. // NB: we discard excess arguments - they are typically undefined from makeLine
  19587. };
  19588. var makeLine = function (type, obj, location) {
  19589. var str = obj.format instanceof Function ?
  19590. (obj.format(obj.push ? location : location[obj.name])) :
  19591. obj.format;
  19592. var args = [type + '=' + str];
  19593. if (obj.names) {
  19594. for (var i = 0; i < obj.names.length; i += 1) {
  19595. var n = obj.names[i];
  19596. if (obj.name) {
  19597. args.push(location[obj.name][n]);
  19598. }
  19599. else { // for mLine and push attributes
  19600. args.push(location[obj.names[i]]);
  19601. }
  19602. }
  19603. }
  19604. else {
  19605. args.push(location[obj.name]);
  19606. }
  19607. return format.apply(null, args);
  19608. };
  19609. // RFC specified order
  19610. // TODO: extend this with all the rest
  19611. var defaultOuterOrder = [
  19612. 'v', 'o', 's', 'i',
  19613. 'u', 'e', 'p', 'c',
  19614. 'b', 't', 'r', 'z', 'a'
  19615. ];
  19616. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  19617. module.exports = function (session, opts) {
  19618. opts = opts || {};
  19619. // ensure certain properties exist
  19620. if (session.version == null) {
  19621. session.version = 0; // "v=0" must be there (only defined version atm)
  19622. }
  19623. if (session.name == null) {
  19624. session.name = " "; // "s= " must be there if no meaningful name set
  19625. }
  19626. session.media.forEach(function (mLine) {
  19627. if (mLine.payloads == null) {
  19628. mLine.payloads = "";
  19629. }
  19630. });
  19631. var outerOrder = opts.outerOrder || defaultOuterOrder;
  19632. var innerOrder = opts.innerOrder || defaultInnerOrder;
  19633. var sdp = [];
  19634. // loop through outerOrder for matching properties on session
  19635. outerOrder.forEach(function (type) {
  19636. grammar[type].forEach(function (obj) {
  19637. if (obj.name in session && session[obj.name] != null) {
  19638. sdp.push(makeLine(type, obj, session));
  19639. }
  19640. else if (obj.push in session && session[obj.push] != null) {
  19641. session[obj.push].forEach(function (el) {
  19642. sdp.push(makeLine(type, obj, el));
  19643. });
  19644. }
  19645. });
  19646. });
  19647. // then for each media line, follow the innerOrder
  19648. session.media.forEach(function (mLine) {
  19649. sdp.push(makeLine('m', grammar.m[0], mLine));
  19650. innerOrder.forEach(function (type) {
  19651. grammar[type].forEach(function (obj) {
  19652. if (obj.name in mLine && mLine[obj.name] != null) {
  19653. sdp.push(makeLine(type, obj, mLine));
  19654. }
  19655. else if (obj.push in mLine && mLine[obj.push] != null) {
  19656. mLine[obj.push].forEach(function (el) {
  19657. sdp.push(makeLine(type, obj, el));
  19658. });
  19659. }
  19660. });
  19661. });
  19662. });
  19663. return sdp.join('\r\n') + '\r\n';
  19664. };
  19665. },{"./grammar":68}],72:[function(require,module,exports){
  19666. var grammar = module.exports = {
  19667. v: [{
  19668. name: 'version',
  19669. reg: /^(\d*)$/
  19670. }],
  19671. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  19672. // NB: sessionId will be a String in most cases because it is huge
  19673. name: 'origin',
  19674. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  19675. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  19676. format: "%s %s %d %s IP%d %s"
  19677. }],
  19678. // default parsing of these only (though some of these feel outdated)
  19679. s: [{ name: 'name' }],
  19680. i: [{ name: 'description' }],
  19681. u: [{ name: 'uri' }],
  19682. e: [{ name: 'email' }],
  19683. p: [{ name: 'phone' }],
  19684. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  19685. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  19686. //k: [{}], // outdated thing ignored
  19687. t: [{ //t=0 0
  19688. name: 'timing',
  19689. reg: /^(\d*) (\d*)/,
  19690. names: ['start', 'stop'],
  19691. format: "%d %d"
  19692. }],
  19693. c: [{ //c=IN IP4 10.47.197.26
  19694. name: 'connection',
  19695. reg: /^IN IP(\d) (\S*)/,
  19696. names: ['version', 'ip'],
  19697. format: "IN IP%d %s"
  19698. }],
  19699. b: [{ //b=AS:4000
  19700. push: 'bandwidth',
  19701. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  19702. names: ['type', 'limit'],
  19703. format: "%s:%s"
  19704. }],
  19705. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  19706. // NB: special - pushes to session
  19707. // TODO: rtp/fmtp should be filtered by the payloads found here?
  19708. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  19709. names: ['type', 'port', 'protocol', 'payloads'],
  19710. format: "%s %d %s %s"
  19711. }],
  19712. a: [
  19713. { //a=rtpmap:110 opus/48000/2
  19714. push: 'rtp',
  19715. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  19716. names: ['payload', 'codec', 'rate', 'encoding'],
  19717. format: function (o) {
  19718. return (o.encoding) ?
  19719. "rtpmap:%d %s/%s/%s":
  19720. "rtpmap:%d %s/%s";
  19721. }
  19722. },
  19723. {
  19724. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  19725. //a=fmtp:111 minptime=10; useinbandfec=1
  19726. push: 'fmtp',
  19727. reg: /^fmtp:(\d*) ([\S| ]*)/,
  19728. names: ['payload', 'config'],
  19729. format: "fmtp:%d %s"
  19730. },
  19731. { //a=control:streamid=0
  19732. name: 'control',
  19733. reg: /^control:(.*)/,
  19734. format: "control:%s"
  19735. },
  19736. { //a=rtcp:65179 IN IP4 193.84.77.194
  19737. name: 'rtcp',
  19738. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  19739. names: ['port', 'netType', 'ipVer', 'address'],
  19740. format: function (o) {
  19741. return (o.address != null) ?
  19742. "rtcp:%d %s IP%d %s":
  19743. "rtcp:%d";
  19744. }
  19745. },
  19746. { //a=rtcp-fb:98 trr-int 100
  19747. push: 'rtcpFbTrrInt',
  19748. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  19749. names: ['payload', 'value'],
  19750. format: "rtcp-fb:%d trr-int %d"
  19751. },
  19752. { //a=rtcp-fb:98 nack rpsi
  19753. push: 'rtcpFb',
  19754. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  19755. names: ['payload', 'type', 'subtype'],
  19756. format: function (o) {
  19757. return (o.subtype != null) ?
  19758. "rtcp-fb:%s %s %s":
  19759. "rtcp-fb:%s %s";
  19760. }
  19761. },
  19762. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  19763. //a=extmap:1/recvonly URI-gps-string
  19764. push: 'ext',
  19765. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  19766. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  19767. format: function (o) {
  19768. return (o.config != null) ?
  19769. "extmap:%s %s %s":
  19770. "extmap:%s %s";
  19771. }
  19772. },
  19773. {
  19774. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  19775. push: 'crypto',
  19776. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  19777. names: ['id', 'suite', 'config', 'sessionConfig'],
  19778. format: function (o) {
  19779. return (o.sessionConfig != null) ?
  19780. "crypto:%d %s %s %s":
  19781. "crypto:%d %s %s";
  19782. }
  19783. },
  19784. { //a=setup:actpass
  19785. name: 'setup',
  19786. reg: /^setup:(\w*)/,
  19787. format: "setup:%s"
  19788. },
  19789. { //a=mid:1
  19790. name: 'mid',
  19791. reg: /^mid:([^\s]*)/,
  19792. format: "mid:%s"
  19793. },
  19794. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  19795. name: 'msid',
  19796. reg: /^msid:(.*)/,
  19797. format: "msid:%s"
  19798. },
  19799. { //a=ptime:20
  19800. name: 'ptime',
  19801. reg: /^ptime:(\d*)/,
  19802. format: "ptime:%d"
  19803. },
  19804. { //a=maxptime:60
  19805. name: 'maxptime',
  19806. reg: /^maxptime:(\d*)/,
  19807. format: "maxptime:%d"
  19808. },
  19809. { //a=sendrecv
  19810. name: 'direction',
  19811. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  19812. },
  19813. { //a=ice-lite
  19814. name: 'icelite',
  19815. reg: /^(ice-lite)/
  19816. },
  19817. { //a=ice-ufrag:F7gI
  19818. name: 'iceUfrag',
  19819. reg: /^ice-ufrag:(\S*)/,
  19820. format: "ice-ufrag:%s"
  19821. },
  19822. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  19823. name: 'icePwd',
  19824. reg: /^ice-pwd:(\S*)/,
  19825. format: "ice-pwd:%s"
  19826. },
  19827. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  19828. name: 'fingerprint',
  19829. reg: /^fingerprint:(\S*) (\S*)/,
  19830. names: ['type', 'hash'],
  19831. format: "fingerprint:%s %s"
  19832. },
  19833. {
  19834. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  19835. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  19836. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  19837. push:'candidates',
  19838. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  19839. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  19840. format: function (o) {
  19841. var str = "candidate:%s %d %s %d %s %d typ %s";
  19842. // NB: candidate has two optional chunks, so %void middle one if it's missing
  19843. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  19844. if (o.generation != null) {
  19845. str += " generation %d";
  19846. }
  19847. return str;
  19848. }
  19849. },
  19850. { //a=end-of-candidates (keep after the candidates line for readability)
  19851. name: 'endOfCandidates',
  19852. reg: /^(end-of-candidates)/
  19853. },
  19854. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  19855. name: 'remoteCandidates',
  19856. reg: /^remote-candidates:(.*)/,
  19857. format: "remote-candidates:%s"
  19858. },
  19859. { //a=ice-options:google-ice
  19860. name: 'iceOptions',
  19861. reg: /^ice-options:(\S*)/,
  19862. format: "ice-options:%s"
  19863. },
  19864. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  19865. push: "ssrcs",
  19866. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  19867. names: ['id', 'attribute', 'value'],
  19868. format: "ssrc:%d %s:%s"
  19869. },
  19870. { //a=ssrc-group:FEC 1 2
  19871. push: "ssrcGroups",
  19872. reg: /^ssrc-group:(\w*) (.*)/,
  19873. names: ['semantics', 'ssrcs'],
  19874. format: "ssrc-group:%s %s"
  19875. },
  19876. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  19877. name: "msidSemantic",
  19878. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  19879. names: ['semantic', 'token'],
  19880. format: "msid-semantic: %s %s" // space after ":" is not accidental
  19881. },
  19882. { //a=group:BUNDLE audio video
  19883. push: 'groups',
  19884. reg: /^group:(\w*) (.*)/,
  19885. names: ['type', 'mids'],
  19886. format: "group:%s %s"
  19887. },
  19888. { //a=rtcp-mux
  19889. name: 'rtcpMux',
  19890. reg: /^(rtcp-mux)/
  19891. },
  19892. { //a=rtcp-rsize
  19893. name: 'rtcpRsize',
  19894. reg: /^(rtcp-rsize)/
  19895. },
  19896. { // any a= that we don't understand is kepts verbatim on media.invalid
  19897. push: 'invalid',
  19898. names: ["value"]
  19899. }
  19900. ]
  19901. };
  19902. // set sensible defaults to avoid polluting the grammar with boring details
  19903. Object.keys(grammar).forEach(function (key) {
  19904. var objs = grammar[key];
  19905. objs.forEach(function (obj) {
  19906. if (!obj.reg) {
  19907. obj.reg = /(.*)/;
  19908. }
  19909. if (!obj.format) {
  19910. obj.format = "%s";
  19911. }
  19912. });
  19913. });
  19914. },{}],73:[function(require,module,exports){
  19915. arguments[4][69][0].apply(exports,arguments)
  19916. },{"./parser":74,"./writer":75,"dup":69}],74:[function(require,module,exports){
  19917. var toIntIfInt = function (v) {
  19918. return String(Number(v)) === v ? Number(v) : v;
  19919. };
  19920. var attachProperties = function (match, location, names, rawName) {
  19921. if (rawName && !names) {
  19922. location[rawName] = toIntIfInt(match[1]);
  19923. }
  19924. else {
  19925. for (var i = 0; i < names.length; i += 1) {
  19926. if (match[i+1] != null) {
  19927. location[names[i]] = toIntIfInt(match[i+1]);
  19928. }
  19929. }
  19930. }
  19931. };
  19932. var parseReg = function (obj, location, content) {
  19933. var needsBlank = obj.name && obj.names;
  19934. if (obj.push && !location[obj.push]) {
  19935. location[obj.push] = [];
  19936. }
  19937. else if (needsBlank && !location[obj.name]) {
  19938. location[obj.name] = {};
  19939. }
  19940. var keyLocation = obj.push ?
  19941. {} : // blank object that will be pushed
  19942. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  19943. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  19944. if (obj.push) {
  19945. location[obj.push].push(keyLocation);
  19946. }
  19947. };
  19948. var grammar = require('./grammar');
  19949. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  19950. exports.parse = function (sdp) {
  19951. var session = {}
  19952. , media = []
  19953. , location = session; // points at where properties go under (one of the above)
  19954. // parse lines we understand
  19955. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  19956. var type = l[0];
  19957. var content = l.slice(2);
  19958. if (type === 'm') {
  19959. media.push({rtp: [], fmtp: []});
  19960. location = media[media.length-1]; // point at latest media line
  19961. }
  19962. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  19963. var obj = grammar[type][j];
  19964. if (obj.reg.test(content)) {
  19965. return parseReg(obj, location, content);
  19966. }
  19967. }
  19968. });
  19969. session.media = media; // link it up
  19970. return session;
  19971. };
  19972. var fmtpReducer = function (acc, expr) {
  19973. var s = expr.split('=');
  19974. if (s.length === 2) {
  19975. acc[s[0]] = toIntIfInt(s[1]);
  19976. }
  19977. return acc;
  19978. };
  19979. exports.parseFmtpConfig = function (str) {
  19980. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  19981. };
  19982. exports.parsePayloads = function (str) {
  19983. return str.split(' ').map(Number);
  19984. };
  19985. exports.parseRemoteCandidates = function (str) {
  19986. var candidates = [];
  19987. var parts = str.split(' ').map(toIntIfInt);
  19988. for (var i = 0; i < parts.length; i += 3) {
  19989. candidates.push({
  19990. component: parts[i],
  19991. ip: parts[i + 1],
  19992. port: parts[i + 2]
  19993. });
  19994. }
  19995. return candidates;
  19996. };
  19997. },{"./grammar":72}],75:[function(require,module,exports){
  19998. arguments[4][71][0].apply(exports,arguments)
  19999. },{"./grammar":72,"dup":71}],76:[function(require,module,exports){
  20000. var MediaStreamType = {
  20001. VIDEO_TYPE: "Video",
  20002. AUDIO_TYPE: "Audio"
  20003. };
  20004. module.exports = MediaStreamType;
  20005. },{}],77:[function(require,module,exports){
  20006. var RTCEvents = {
  20007. RTC_READY: "rtc.ready",
  20008. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  20009. LASTN_CHANGED: "rtc.lastn_changed",
  20010. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  20011. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  20012. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  20013. };
  20014. module.exports = RTCEvents;
  20015. },{}],78:[function(require,module,exports){
  20016. var Resolutions = {
  20017. "1080": {
  20018. width: 1920,
  20019. height: 1080,
  20020. order: 7
  20021. },
  20022. "fullhd": {
  20023. width: 1920,
  20024. height: 1080,
  20025. order: 7
  20026. },
  20027. "720": {
  20028. width: 1280,
  20029. height: 720,
  20030. order: 6
  20031. },
  20032. "hd": {
  20033. width: 1280,
  20034. height: 720,
  20035. order: 6
  20036. },
  20037. "960": {
  20038. width: 960,
  20039. height: 720,
  20040. order: 5
  20041. },
  20042. "640": {
  20043. width: 640,
  20044. height: 480,
  20045. order: 4
  20046. },
  20047. "vga": {
  20048. width: 640,
  20049. height: 480,
  20050. order: 4
  20051. },
  20052. "360": {
  20053. width: 640,
  20054. height: 360,
  20055. order: 3
  20056. },
  20057. "320": {
  20058. width: 320,
  20059. height: 240,
  20060. order: 2
  20061. },
  20062. "180": {
  20063. width: 320,
  20064. height: 180,
  20065. order: 1
  20066. }
  20067. };
  20068. module.exports = Resolutions;
  20069. },{}],79:[function(require,module,exports){
  20070. var StreamEventTypes = {
  20071. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  20072. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  20073. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  20074. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  20075. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  20076. TRACK_MUTE_CHANGED: "rtc.track_mute_changed"
  20077. };
  20078. module.exports = StreamEventTypes;
  20079. },{}],80:[function(require,module,exports){
  20080. var AuthenticationEvents = {
  20081. /**
  20082. * Event callback arguments:
  20083. * function(authenticationEnabled, userIdentity)
  20084. * authenticationEnabled - indicates whether authentication has been enabled
  20085. * in this session
  20086. * userIdentity - if user has been logged in then it contains user name. If
  20087. * contains 'null' or 'undefined' then user is not logged in.
  20088. */
  20089. IDENTITY_UPDATED: "authentication.identity_updated"
  20090. };
  20091. module.exports = AuthenticationEvents;
  20092. },{}],81:[function(require,module,exports){
  20093. var DesktopSharingEventTypes = {
  20094. INIT: "ds.init",
  20095. SWITCHING_DONE: "ds.switching_done",
  20096. NEW_STREAM_CREATED: "ds.new_stream_created"
  20097. };
  20098. module.exports = DesktopSharingEventTypes;
  20099. },{}],82:[function(require,module,exports){
  20100. module.exports = {
  20101. /**
  20102. * An event carrying connection statistics.
  20103. */
  20104. CONNECTION_STATS: "statistics.connectionstats",
  20105. /**
  20106. * FIXME: needs documentation.
  20107. */
  20108. AUDIO_LEVEL: "statistics.audioLevel",
  20109. /**
  20110. * FIXME: needs documentation.
  20111. */
  20112. STOP: "statistics.stop"
  20113. };
  20114. },{}],83:[function(require,module,exports){
  20115. var Constants = {
  20116. LOCAL_JID: 'local'
  20117. };
  20118. module.exports = Constants;
  20119. },{}],84:[function(require,module,exports){
  20120. var XMPPEvents = {
  20121. // Designates an event indicating that the connection to the XMPP server
  20122. // failed.
  20123. CONNECTION_FAILED: "xmpp.connection.failed",
  20124. // Designates an event indicating that the media (ICE) connection was
  20125. // interrupted. This should go to the RTC module.
  20126. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  20127. // Designates an event indicating that the media (ICE) connection was
  20128. // restored. This should go to the RTC module.
  20129. CONNECTION_RESTORED: "xmpp.connection.restored",
  20130. // Designates an event indicating that an offer (e.g. Jingle
  20131. // session-initiate) was received.
  20132. CALL_INCOMING: "xmpp.callincoming.jingle",
  20133. // Designates an event indicating that we were kicked from the XMPP MUC.
  20134. KICKED: "xmpp.kicked",
  20135. // Designates an event indicating that the userID for a specific JID has
  20136. // changed.
  20137. // Note: currently this event fires every time we receive presence from
  20138. // someone (regardless of whether or not the "userID" changed).
  20139. USER_ID_CHANGED: "xmpp.user_id_changed",
  20140. // Designates an event indicating that we have joined the XMPP MUC.
  20141. MUC_JOINED: "xmpp.muc_joined",
  20142. // Designates an event indicating that a participant joined the XMPP MUC.
  20143. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  20144. // Designates an event indicating that a participant left the XMPP MUC.
  20145. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  20146. // Designates an event indicating that the MUC role of a participant has
  20147. // changed.
  20148. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  20149. // Designates an event indicating that the XMPP MUC was destroyed.
  20150. MUC_DESTROYED: "xmpp.muc_destroyed",
  20151. // Designates an event indicating that the display name of a participant
  20152. // has changed.
  20153. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  20154. // Designates an event indicating that we received statistics from a
  20155. // participant in the MUC.
  20156. REMOTE_STATS: "xmpp.remote_stats",
  20157. // Designates an event indicating that our role in the XMPP MUC has changed.
  20158. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  20159. // Designates an event indicating that the subject of the XMPP MUC has
  20160. // changed.
  20161. SUBJECT_CHANGED: "xmpp.subject_changed",
  20162. // Designates an event indicating that an XMPP message in the MUC was
  20163. // received.
  20164. MESSAGE_RECEIVED: "xmpp.message_received",
  20165. // Designates an event indicating that we sent an XMPP message to the MUC.
  20166. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  20167. // Designates an event indicating that the video type (e.g. 'camera' or
  20168. // 'screen') for a participant has changed.
  20169. // Note: currently this event fires every time we receive presence from
  20170. // someone (regardless of whether or not the "video type" changed).
  20171. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  20172. // Designates an event indicating that a participant in the XMPP MUC has
  20173. // advertised that they have audio muted (or unmuted).
  20174. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  20175. // Designates an event indicating that a participant in the XMPP MUC has
  20176. // advertised that they have video muted (or unmuted).
  20177. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  20178. // Designates an event indicating that the focus has asked us to mute our
  20179. // audio.
  20180. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  20181. // Designates an event indicating that a moderator in the room changed the
  20182. // "start muted" settings for the conference.
  20183. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  20184. // Designates an event indicating that we should join the conference with
  20185. // audio and/or video muted.
  20186. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  20187. // Designates an event indicating that a remote participant's available
  20188. // devices (whether he supports a audio and/or video) changed.
  20189. // Note: currently this event fires every time we receive presence from
  20190. // someone (regardless of whether or not the devices changed).
  20191. DEVICE_AVAILABLE: "xmpp.device_available",
  20192. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  20193. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  20194. PASSWORD_REQUIRED: "xmpp.password_required",
  20195. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  20196. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  20197. ETHERPAD: "xmpp.etherpad",
  20198. BRIDGE_DOWN: "xmpp.bridge_down",
  20199. PRESENCE_STATUS: "xmpp.presence_status",
  20200. RESERVATION_ERROR: "xmpp.room_reservation_error",
  20201. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  20202. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  20203. // TODO: only used in a hack, should probably be removed.
  20204. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  20205. // TODO: only used in a hack, should probably be removed.
  20206. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  20207. // TODO: only used in a hack, should probably be removed.
  20208. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  20209. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  20210. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  20211. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  20212. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  20213. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  20214. // xmpp is connected and obtained user media
  20215. READY_TO_JOIN: 'xmpp.ready_to_join',
  20216. FOCUS_LEFT: "xmpp.focus_left",
  20217. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  20218. };
  20219. module.exports = XMPPEvents;
  20220. },{}]},{},[7])(7)
  20221. });