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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JitsiMeetJS=e()}}(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. var RTC = require("./modules/RTC/RTC");
  3. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  4. var StreamEventTypes = require("./service/RTC/StreamEventTypes");
  5. var RTCEvents = require("./service/RTC/RTCEvents");
  6. var EventEmitter = require("events");
  7. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  8. var JitsiParticipant = require("./JitsiParticipant");
  9. /**
  10. * Creates a JitsiConference object with the given name and properties.
  11. * Note: this constructor is not a part of the public API (objects should be
  12. * created using JitsiConnection.createConference).
  13. * @param options.config properties / settings related to the conference that will be created.
  14. * @param options.name the name of the conference
  15. * @param options.connection the JitsiConnection object for this JitsiConference.
  16. * @constructor
  17. */
  18. function JitsiConference(options) {
  19. this.options = options;
  20. this.connection = this.options.connection;
  21. this.xmpp = this.connection.xmpp;
  22. this.eventEmitter = new EventEmitter();
  23. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  24. this.rtc = new RTC(this.room, options);
  25. setupListeners(this);
  26. this.participants = {};
  27. }
  28. /**
  29. * Joins the conference.
  30. * @param password {string} the password
  31. */
  32. JitsiConference.prototype.join = function (password) {
  33. this.room.join(password);
  34. }
  35. /**
  36. * Leaves the conference.
  37. */
  38. JitsiConference.prototype.leave = function () {
  39. this.xmpp.leaveRoom(room.roomjid);
  40. this.room = null;
  41. }
  42. /**
  43. * Creates the media tracks and returns them trough the callback.
  44. * @param options Object with properties / settings specifying the tracks which should be created.
  45. * should be created or some additional configurations about resolution for example.
  46. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  47. * or a JitsiConferenceError if rejected.
  48. */
  49. JitsiConference.prototype.createLocalTracks = function (options) {
  50. return this.rtc.obtainAudioAndVideoPermissions(options || {});
  51. }
  52. /**
  53. * Returns the local tracks.
  54. */
  55. JitsiConference.prototype.getLocalTracks = function () {
  56. return this.rtc.localStreams;
  57. };
  58. /**
  59. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  60. * in JitsiConferenceEvents.
  61. * @param eventId the event ID.
  62. * @param handler handler for the event.
  63. *
  64. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  65. */
  66. JitsiConference.prototype.on = function (eventId, handler) {
  67. this.eventEmitter.on(eventId, handler);
  68. }
  69. /**
  70. * Removes event listener
  71. * @param eventId the event ID.
  72. * @param [handler] optional, the specific handler to unbind
  73. *
  74. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  75. */
  76. JitsiConference.prototype.off = function (eventId, handler) {
  77. this.eventEmitter.removeListener(eventId, listener);
  78. }
  79. // Common aliases for event emitter
  80. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  81. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  82. /**
  83. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  84. * @param command {String} the name of the command
  85. * @param handler {Function} handler for the command
  86. */
  87. JitsiConference.prototype.addCommandListener = function (command, handler) {
  88. this.room.addPresenceListener(command, handler);
  89. }
  90. /**
  91. * Removes command listener
  92. * @param command {String} the name of the command
  93. */
  94. JitsiConference.prototype.removeCommandListener = function (command) {
  95. this.room.removePresenceListener(command);
  96. }
  97. /**
  98. * Sends text message to the other participants in the conference
  99. * @param message the text message.
  100. */
  101. JitsiConference.prototype.sendTextMessage = function (message) {
  102. this.room.sendMessage(message);
  103. }
  104. /**
  105. * Send presence command.
  106. * @param name the name of the command.
  107. * @param values Object with keys and values that will be send.
  108. **/
  109. JitsiConference.prototype.sendCommand = function (name, values) {
  110. this.room.addToPresence(name, values);
  111. this.room.sendPresence();
  112. }
  113. /**
  114. * Send presence command one time.
  115. * @param name the name of the command.
  116. * @param values Object with keys and values that will be send.
  117. **/
  118. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  119. this.sendCommand(name, values);
  120. this.removeCommand(name);
  121. }
  122. /**
  123. * Send presence command.
  124. * @param name the name of the command.
  125. * @param values Object with keys and values that will be send.
  126. * @param persistent if false the command will be sent only one time
  127. **/
  128. JitsiConference.prototype.removeCommand = function (name) {
  129. this.room.removeFromPresence(name);
  130. }
  131. /**
  132. * Sets the display name for this conference.
  133. * @param name the display name to set
  134. */
  135. JitsiConference.prototype.setDisplayName = function(name) {
  136. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  137. }
  138. /**
  139. * Elects the participant with the given id to be the selected participant or the speaker.
  140. * @param id the identifier of the participant
  141. */
  142. JitsiConference.prototype.selectParticipant = function(participantId) {
  143. this.rtc.selectedEndpoint(participantId);
  144. }
  145. /**
  146. *
  147. * @param id the identifier of the participant
  148. */
  149. JitsiConference.prototype.pinParticipant = function(participantId) {
  150. this.rtc.pinEndpoint(participantId);
  151. }
  152. /**
  153. * Returns the list of participants for this conference.
  154. * @return Object a list of participant identifiers containing all conference participants.
  155. */
  156. JitsiConference.prototype.getParticipants = function() {
  157. return this.participants;
  158. }
  159. /**
  160. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  161. * null if there isn't one).
  162. * @param id the id of the participant.
  163. */
  164. JitsiConference.prototype.getParticipantById = function(id) {
  165. return this.participants[id];
  166. }
  167. JitsiConference.prototype.onMemberJoined = function (jid, email, nick) {
  168. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, Strophe.getResourceFromJid(jid));
  169. // this.participants[jid] = new JitsiParticipant();
  170. }
  171. /**
  172. * Setups the listeners needed for the conference.
  173. * @param conference the conference
  174. */
  175. function setupListeners(conference) {
  176. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING,
  177. conference.rtc.onIncommingCall.bind(conference.rtc));
  178. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  179. conference.rtc.createRemoteStream.bind(conference.rtc));
  180. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, function (stream) {
  181. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, stream);
  182. });
  183. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, function (stream) {
  184. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  185. });
  186. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, function (stream) {
  187. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  188. })
  189. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  190. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  191. });
  192. // FIXME
  193. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  194. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  195. // });
  196. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  197. conference.eventEmitter.emit(JitsiConferenceEvents.ACTIVE_SPEAKER_CHANGED, id);
  198. });
  199. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  200. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  201. });
  202. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  203. function (lastNEndpoints, endpointsEnteringLastN) {
  204. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  205. lastNEndpoints, endpointsEnteringLastN);
  206. });
  207. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  208. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT,function (jid) {
  209. conference.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, Strophe.getResourceFromJid(jid));
  210. });
  211. }
  212. module.exports = JitsiConference;
  213. },{"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./modules/RTC/RTC":13,"./service/RTC/RTCEvents":71,"./service/RTC/StreamEventTypes":73,"./service/xmpp/XMPPEvents":76,"events":77}],2:[function(require,module,exports){
  214. /**
  215. * Enumeration with the errors for the conference.
  216. * @type {{string: string}}
  217. */
  218. var JitsiConferenceErrors = {
  219. /**
  220. * Indicates that a password is required in order to join the conference.
  221. */
  222. PASSWORD_REQUIRED: "conference.passwordRequired",
  223. /**
  224. * Indicates that a connection error occurred when trying to join a conference.
  225. */
  226. CONNECTION_ERROR: "conference.connectionError",
  227. /**
  228. * Indicates that there is no available videobridge.
  229. */
  230. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  231. /**
  232. * Many more errors TBD here.
  233. */
  234. };
  235. module.exports = JitsiConferenceErrors;
  236. },{}],3:[function(require,module,exports){
  237. /**
  238. * Enumeration with the events for the conference.
  239. * @type {{string: string}}
  240. */
  241. var JitsiConferenceEvents = {
  242. /**
  243. * A new media track was added to the conference.
  244. */
  245. TRACK_ADDED: "conference.trackAdded",
  246. /**
  247. * The media track was removed to the conference.
  248. */
  249. TRACK_REMOVED: "conference.trackRemoved",
  250. /**
  251. * The active speaker was changed.
  252. */
  253. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  254. /**
  255. * A new user joinned the conference.
  256. */
  257. USER_JOINED: "conference.userJoined",
  258. /**
  259. * A user has left the conference.
  260. */
  261. USER_LEFT: "conference.userLeft",
  262. /**
  263. * New text message was received.
  264. */
  265. MESSAGE_RECEIVED: "conference.messageReceived",
  266. /**
  267. * A user has changed it display name
  268. */
  269. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  270. /**
  271. * A participant avatar has changed.
  272. */
  273. AVATAR_CHANGED: "conference.avatarChanged",
  274. /**
  275. * New connection statistics are received.
  276. */
  277. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  278. /**
  279. * The Last N set is changed.
  280. */
  281. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  282. /**
  283. * You are included / excluded in somebody's last N set
  284. */
  285. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  286. /**
  287. * A media track was muted.
  288. */
  289. TRACK_MUTED: "conference.trackMuted",
  290. /**
  291. * A media track was unmuted.
  292. */
  293. TRACK_UNMUTED: "conference.trackUnmuted",
  294. /**
  295. * Audio levels of a media track was changed.
  296. */
  297. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  298. /**
  299. * Indicates that the connection to the conference has been interrupted for some reason.
  300. */
  301. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  302. /**
  303. * Indicates that the connection to the conference has been restored.
  304. */
  305. CONNECTION_RESTORED: "conference.connecionRestored",
  306. /**
  307. * Indicates that conference has been joined.
  308. */
  309. CONFERENCE_JOINED: "conference.joined",
  310. /**
  311. * Indicates that conference has been left.
  312. */
  313. CONFERENCE_LEFT: "conference.left"
  314. };
  315. module.exports = JitsiConferenceEvents;
  316. },{}],4:[function(require,module,exports){
  317. var JitsiConference = require("./JitsiConference");
  318. var XMPP = require("./modules/xmpp/xmpp");
  319. /**
  320. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  321. * JitsiConference interface.
  322. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  323. * @param token secret generated by the provider of Jitsi Meet video conferencing services.
  324. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  325. * @param options Object with properties / settings related to connection with the server.
  326. * @constructor
  327. */
  328. function JitsiConnection(appID, token, options) {
  329. this.appID = appID;
  330. this.token = token;
  331. this.options = options;
  332. this.xmpp = new XMPP(options);
  333. this.conferences = {};
  334. }
  335. /**
  336. * Connect the client with the server.
  337. * @param options {object} connecting options (for example authentications parameters).
  338. */
  339. JitsiConnection.prototype.connect = function (options) {
  340. if(!options)
  341. options = {};
  342. this.xmpp.connect(options.id, options.password);
  343. }
  344. /**
  345. * Disconnect the client from the server.
  346. */
  347. JitsiConnection.prototype.disconnect = function () {
  348. this.xmpp.disconnect();
  349. }
  350. /**
  351. * This method allows renewal of the tokens if they are expiring.
  352. * @param token the new token.
  353. */
  354. JitsiConnection.prototype.setToken = function (token) {
  355. this.token = token;
  356. }
  357. /**
  358. * Creates and joins new conference.
  359. * @param name the name of the conference; if null - a generated name will be provided from the api
  360. * @param options Object with properties / settings related to the conference that will be created.
  361. * @returns {JitsiConference} returns the new conference object.
  362. */
  363. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  364. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  365. return this.conferences[name];
  366. }
  367. /**
  368. * Subscribes the passed listener to the event.
  369. * @param event {JitsiConnectionEvents} the connection event.
  370. * @param listener {Function} the function that will receive the event
  371. */
  372. JitsiConnection.prototype.addEventListener = function (event, listener) {
  373. this.xmpp.addListener(event, listener);
  374. }
  375. /**
  376. * Unsubscribes the passed handler.
  377. * @param event {JitsiConnectionEvents} the connection event.
  378. * @param listener {Function} the function that will receive the event
  379. */
  380. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  381. this.xmpp.removeListener(event, listener);
  382. }
  383. module.exports = JitsiConnection;
  384. },{"./JitsiConference":1,"./modules/xmpp/xmpp":33}],5:[function(require,module,exports){
  385. /**
  386. * Enumeration with the errors for the connection.
  387. * @type {{string: string}}
  388. */
  389. var JitsiConnectionErrors = {
  390. /**
  391. * Indicates that a password is required in order to join the conference.
  392. */
  393. PASSWORD_REQUIRED: "connection.passwordRequired",
  394. /**
  395. * Indicates that a connection error occurred when trying to join a conference.
  396. */
  397. CONNECTION_ERROR: "connection.connectionError",
  398. /**
  399. * Not specified errors.
  400. */
  401. OTHER_ERROR: "connection.otherError"
  402. };
  403. module.exports = JitsiConnectionErrors;
  404. },{}],6:[function(require,module,exports){
  405. /**
  406. * Enumeration with the events for the connection.
  407. * @type {{string: string}}
  408. */
  409. var JitsiConnnectionEvents = {
  410. /**
  411. * Indicates that the connection has been failed for some reason.
  412. */
  413. CONNECTION_FAILED: "connection.connecionFailed",
  414. /**
  415. * Indicates that the connection has been established.
  416. */
  417. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  418. /**
  419. * Indicates that the connection has been disconnected.
  420. */
  421. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  422. /**
  423. * Indicates that the perfomed action cannot be executed because the
  424. * connection is not in the correct state(connected, disconnected, etc.)
  425. */
  426. WRONG_STATE: "connection.wrongState"
  427. };
  428. module.exports = JitsiConnnectionEvents;
  429. },{}],7:[function(require,module,exports){
  430. var JitsiConnection = require("./JitsiConnection");
  431. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  432. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  433. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  434. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  435. /**
  436. * Namespace for the interface of Jitsi Meet Library.
  437. */
  438. var LibJitsiMeet = {
  439. JitsiConnection: JitsiConnection,
  440. events: {
  441. conference: JitsiConferenceEvents,
  442. connection: JitsiConnectionEvents
  443. },
  444. errors: {
  445. conference: JitsiConferenceErrors,
  446. connection: JitsiConnectionErrors
  447. },
  448. init: function (options) {
  449. require("./modules/RTC/RTC").init(options || {});
  450. }
  451. }
  452. //Setups the promise object.
  453. window.Promise = window.Promise || require("es6-promise").polyfill();
  454. module.exports = LibJitsiMeet;
  455. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./modules/RTC/RTC":13,"es6-promise":35}],8:[function(require,module,exports){
  456. /**
  457. * Represents a participant in (a member of) a conference.
  458. */
  459. function JitsiParticipant(id, conference, displayName){
  460. this._id = id;
  461. this._conference = conference;
  462. this._displayName = displayName;
  463. }
  464. /**
  465. * @returns {JitsiConference} The conference that this participant belongs to.
  466. */
  467. JitsiParticipant.prototype.getConference = function() {
  468. return this._conference;
  469. }
  470. /**
  471. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  472. */
  473. JitsiParticipant.prototype.getTracks = function() {
  474. }
  475. /**
  476. * @returns {String} The ID (i.e. JID) of this participant.
  477. */
  478. JitsiParticipant.prototype.getId = function() {
  479. return this._id;
  480. }
  481. /**
  482. * @returns {String} The human-readable display name of this participant.
  483. */
  484. JitsiParticipant.prototype.getDisplayName = function() {
  485. return this._displayName;
  486. }
  487. /**
  488. * @returns {Boolean} Whether this participant is a moderator or not.
  489. */
  490. JitsiParticipant.prototype.isModerator = function() {
  491. }
  492. // Gets a link to an etherpad instance advertised by the participant?
  493. //JitsiParticipant.prototype.getEtherpad = function() {
  494. //
  495. //}
  496. /*
  497. * @returns {Boolean} Whether this participant has muted their audio.
  498. */
  499. JitsiParticipant.prototype.isAudioMuted = function() {
  500. }
  501. /*
  502. * @returns {Boolean} Whether this participant has muted their video.
  503. */
  504. JitsiParticipant.prototype.isVideoMuted = function() {
  505. }
  506. /*
  507. * @returns {???} The latest statistics reported by this participant (i.e. info used to populate the GSM bars)
  508. * TODO: do we expose this or handle it internally?
  509. */
  510. JitsiParticipant.prototype.getLatestStats = function() {
  511. }
  512. /**
  513. * @returns {String} The role of this participant.
  514. */
  515. JitsiParticipant.prototype.getRole = function() {
  516. }
  517. /*
  518. * @returns {Boolean} Whether this participant is the conference focus (i.e. jicofo).
  519. */
  520. JitsiParticipant.prototype.isFocus = function() {
  521. }
  522. /*
  523. * @returns {Boolean} Whether this participant is a conference recorder (i.e. jirecon).
  524. */
  525. JitsiParticipant.prototype.isRecorder = function() {
  526. }
  527. /*
  528. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  529. */
  530. JitsiParticipant.prototype.isSipGateway = function() {
  531. }
  532. /**
  533. * @returns {String} The ID for this participant's avatar.
  534. */
  535. JitsiParticipant.prototype.getAvatarId = function() {
  536. }
  537. /**
  538. * @returns {Boolean} Whether this participant is currently sharing their screen.
  539. */
  540. JitsiParticipant.prototype.isScreenSharing = function() {
  541. }
  542. /**
  543. * @returns {String} The user agent of this participant (i.e. browser userAgent string).
  544. */
  545. JitsiParticipant.prototype.getUserAgent = function() {
  546. }
  547. /**
  548. * Kicks the participant from the conference (requires certain privileges).
  549. */
  550. JitsiParticipant.prototype.kick = function() {
  551. }
  552. /**
  553. * Asks this participant to mute themselves.
  554. */
  555. JitsiParticipant.prototype.askToMute = function() {
  556. }
  557. module.exports = JitsiParticipant();
  558. },{}],9:[function(require,module,exports){
  559. /* global config, APP, Strophe */
  560. // cache datachannels to avoid garbage collection
  561. // https://code.google.com/p/chromium/issues/detail?id=405545
  562. var RTCEvents = require("../../service/RTC/RTCEvents");
  563. /**
  564. * Binds "ondatachannel" event listener to given PeerConnection instance.
  565. * @param peerConnection WebRTC peer connection instance.
  566. */
  567. function DataChannels(peerConnection, emitter) {
  568. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  569. this.eventEmitter = emitter;
  570. this._dataChannels = [];
  571. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  572. // Although it's not a requirement to open separate channels from both bridge
  573. // and peer as single channel can be used for sending and receiving data.
  574. // So either channel opened by the bridge or the one opened here is enough
  575. // for communication with the bridge.
  576. /*var dataChannelOptions =
  577. {
  578. reliable: true
  579. };
  580. var dataChannel
  581. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  582. // Can be used only when is in open state
  583. dataChannel.onopen = function ()
  584. {
  585. dataChannel.send("My channel !!!");
  586. };
  587. dataChannel.onmessage = function (event)
  588. {
  589. var msgData = event.data;
  590. console.info("Got My Data Channel Message:", msgData, dataChannel);
  591. };*/
  592. };
  593. /**
  594. * Callback triggered by PeerConnection when new data channel is opened
  595. * on the bridge.
  596. * @param event the event info object.
  597. */
  598. DataChannels.prototype.onDataChannel = function (event) {
  599. var dataChannel = event.channel;
  600. var self = this;
  601. dataChannel.onopen = function () {
  602. console.info("Data channel opened by the Videobridge!", dataChannel);
  603. // Code sample for sending string and/or binary data
  604. // Sends String message to the bridge
  605. //dataChannel.send("Hello bridge!");
  606. // Sends 12 bytes binary message to the bridge
  607. //dataChannel.send(new ArrayBuffer(12));
  608. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  609. };
  610. dataChannel.onerror = function (error) {
  611. console.error("Data Channel Error:", error, dataChannel);
  612. };
  613. dataChannel.onmessage = function (event) {
  614. var data = event.data;
  615. // JSON
  616. var obj;
  617. try {
  618. obj = JSON.parse(data);
  619. }
  620. catch (e) {
  621. console.error(
  622. "Failed to parse data channel message as JSON: ",
  623. data,
  624. dataChannel);
  625. }
  626. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  627. var colibriClass = obj.colibriClass;
  628. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  629. // Endpoint ID from the Videobridge.
  630. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  631. console.info(
  632. "Data channel new dominant speaker event: ",
  633. dominantSpeakerEndpoint);
  634. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  635. }
  636. else if ("InLastNChangeEvent" === colibriClass) {
  637. var oldValue = obj.oldValue;
  638. var newValue = obj.newValue;
  639. // Make sure that oldValue and newValue are of type boolean.
  640. var type;
  641. if ((type = typeof oldValue) !== 'boolean') {
  642. if (type === 'string') {
  643. oldValue = (oldValue == "true");
  644. } else {
  645. oldValue = new Boolean(oldValue).valueOf();
  646. }
  647. }
  648. if ((type = typeof newValue) !== 'boolean') {
  649. if (type === 'string') {
  650. newValue = (newValue == "true");
  651. } else {
  652. newValue = new Boolean(newValue).valueOf();
  653. }
  654. }
  655. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  656. }
  657. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  658. // The new/latest list of last-n endpoint IDs.
  659. var lastNEndpoints = obj.lastNEndpoints;
  660. // The list of endpoint IDs which are entering the list of
  661. // last-n at this time i.e. were not in the old list of last-n
  662. // endpoint IDs.
  663. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  664. console.log(
  665. "Data channel new last-n event: ",
  666. lastNEndpoints, endpointsEnteringLastN, obj);
  667. this.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  668. lastNEndpoints, endpointsEnteringLastN, obj);
  669. }
  670. else {
  671. console.debug("Data channel JSON-formatted message: ", obj);
  672. }
  673. }
  674. };
  675. dataChannel.onclose = function () {
  676. console.info("The Data Channel closed", dataChannel);
  677. var idx = self._dataChannels.indexOf(dataChannel);
  678. if (idx > -1)
  679. self._dataChannels = self._dataChannels.splice(idx, 1);
  680. };
  681. this._dataChannels.push(dataChannel);
  682. };
  683. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  684. console.log('selected endpoint changed: ', userResource);
  685. if (this._dataChannels && this._dataChannels.length != 0) {
  686. this._dataChannels.some(function (dataChannel) {
  687. if (dataChannel.readyState == 'open') {
  688. console.log('sending selected endpoint changed ' +
  689. 'notification to the bridge: ', userResource);
  690. dataChannel.send(JSON.stringify({
  691. 'colibriClass': 'SelectedEndpointChangedEvent',
  692. 'selectedEndpoint':
  693. (!userResource || userResource === null)?
  694. null : userResource
  695. }));
  696. return true;
  697. }
  698. });
  699. }
  700. }
  701. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  702. console.log('pinned endpoint changed: ', userResource);
  703. if (this._dataChannels && this._dataChannels.length != 0) {
  704. this._dataChannels.some(function (dataChannel) {
  705. if (dataChannel.readyState == 'open') {
  706. dataChannel.send(JSON.stringify({
  707. 'colibriClass': 'PinnedEndpointChangedEvent',
  708. 'pinnedEndpoint':
  709. (!userResource || userResource == null)?
  710. null : userResource
  711. }));
  712. return true;
  713. }
  714. });
  715. }
  716. }
  717. module.exports = DataChannels;
  718. },{"../../service/RTC/RTCEvents":71}],10:[function(require,module,exports){
  719. var JitsiTrack = require("./JitsiTrack");
  720. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  721. var RTCEvents = require("../../service/RTC/RTCEvents");
  722. /**
  723. * Represents a single media track (either audio or video).
  724. * @constructor
  725. */
  726. function JitsiLocalTrack(RTC, stream, eventEmitter, videoType, isGUMStream)
  727. {
  728. JitsiTrack.call(this, RTC, stream);
  729. this.eventEmitter = eventEmitter;
  730. this.videoType = videoType;
  731. this.isGUMStream = true;
  732. if(isGUMStream === false)
  733. this.isGUMStream = isGUMStream;
  734. this.stream.onended = function () {
  735. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  736. }.bind(this);
  737. }
  738. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  739. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  740. /**
  741. * Mutes / unmutes the track.
  742. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  743. */
  744. JitsiLocalTrack.prototype._setMute = function (mute) {
  745. var isAudio = this.type === JitsiTrack.AUDIO;
  746. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  747. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  748. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  749. // FIXME FF does not support 'removeStream' method used to mute
  750. RTCBrowserType.isFirefox()) {
  751. var tracks = this._getTracks();
  752. for (var idx = 0; idx < tracks.length; idx++) {
  753. tracks[idx].enabled = !mute;
  754. }
  755. if(isAudio)
  756. this.rtc.room.setAudioMute(mute);
  757. else
  758. this.rtc.room.setVideoMute(mute);
  759. this.eventEmitter.emit(eventType, mute);
  760. } else {
  761. if (mute) {
  762. this.rtc.room.removeStream(this.stream);
  763. this.stream.stop();
  764. if(isAudio)
  765. this.rtc.room.setAudioMute(mute);
  766. else
  767. this.rtc.room.setVideoMute(mute);
  768. this.eventEmitter.emit(eventType, true);
  769. } else {
  770. var self = this;
  771. this.rtc.obtainAudioAndVideoPermissions(
  772. {devices: (this.isAudioStream() ? ["audio"] : ["video"])})
  773. .then(function (stream) {
  774. if (isAudio) {
  775. self.rtc.changeLocalAudio(stream,
  776. function () {
  777. this.rtc.room.setAudioMute(mute);
  778. self.eventEmitter.emit(eventType, false);
  779. });
  780. } else {
  781. self.rtc.changeLocalVideo(stream, false,
  782. function () {
  783. this.rtc.room.setVideoMute(mute);
  784. self.eventEmitter.emit(eventType, false);
  785. });
  786. }
  787. });
  788. }
  789. }
  790. }
  791. /**
  792. * Stops sending the media track. And removes it from the HTML.
  793. * NOTE: Works for local tracks only.
  794. */
  795. JitsiLocalTrack.prototype.stop = function () {
  796. this.rtc.room.removeStream(this.stream);
  797. this.stream.stop();
  798. this.detach();
  799. }
  800. /**
  801. * Starts sending the track.
  802. * NOTE: Works for local tracks only.
  803. */
  804. JitsiLocalTrack.prototype.start = function() {
  805. this.rtc.room.addStream(this.stream, function () {});
  806. }
  807. module.exports = JitsiLocalTrack;
  808. },{"../../service/RTC/RTCEvents":71,"../../service/RTC/StreamEventTypes":73,"./JitsiTrack":12}],11:[function(require,module,exports){
  809. var JitsiTrack = require("./JitsiTrack");
  810. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  811. /**
  812. * Represents a single media track (either audio or video).
  813. * @constructor
  814. */
  815. function JitsiRemoteTrack(RTC, data, sid, ssrc, browser, eventEmitter) {
  816. JitsiTrack.call(this, RTC, data.stream);
  817. this.rtc = RTC;
  818. this.sid = sid;
  819. this.stream = data.stream;
  820. this.peerjid = data.peerjid;
  821. this.videoType = data.videoType;
  822. this.ssrc = ssrc;
  823. this.muted = false;
  824. this.eventEmitter = eventEmitter;
  825. var self = this;
  826. if(this.stream)
  827. this.stream.onended = function () {
  828. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_ENDED, self);
  829. }
  830. }
  831. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  832. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  833. JitsiRemoteTrack.prototype._setMute = function (value) {
  834. this.stream.muted = value;
  835. this.muted = value;
  836. };
  837. /**
  838. * @returns {JitsiParticipant} to which this track belongs, or null if it is a local track.
  839. */
  840. JitsiRemoteTrack.prototype.getParitcipantId = function() {
  841. return Strophe.getResourceFromJid(this.peerjid);
  842. };
  843. delete JitsiRemoteTrack.prototype.stop;
  844. delete JitsiRemoteTrack.prototype.start;
  845. module.exports = JitsiRemoteTrack;
  846. },{"../../service/RTC/StreamEventTypes":73,"./JitsiTrack":12}],12:[function(require,module,exports){
  847. var RTC = require("./RTCUtils");
  848. var RTCBrowserType = require("./RTCBrowserType");
  849. /**
  850. * This implements 'onended' callback normally fired by WebRTC after the stream
  851. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  852. * @param stream original WebRTC stream object to which 'onended' handling
  853. * will be added.
  854. */
  855. function implementOnEndedHandling(stream) {
  856. var originalStop = stream.stop;
  857. stream.stop = function () {
  858. originalStop.apply(stream);
  859. if (!stream.ended) {
  860. stream.ended = true;
  861. stream.onended();
  862. }
  863. };
  864. }
  865. /**
  866. * Represents a single media track (either audio or video).
  867. * @constructor
  868. */
  869. function JitsiTrack(RTC, stream)
  870. {
  871. this.rtc = RTC;
  872. this.stream = stream;
  873. this.type = (this.stream.getVideoTracks().length > 0)?
  874. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  875. if(this.type == "audio") {
  876. this._getTracks = function () {
  877. return this.stream.getAudioTracks();
  878. }.bind(this);
  879. } else {
  880. this._getTracks = function () {
  881. return this.stream.getVideoTracks();
  882. }.bind(this);
  883. }
  884. if (RTCBrowserType.isFirefox() && this.stream) {
  885. implementOnEndedHandling(this.stream);
  886. }
  887. }
  888. /**
  889. * JitsiTrack video type.
  890. * @type {string}
  891. */
  892. JitsiTrack.VIDEO = "video";
  893. /**
  894. * JitsiTrack audio type.
  895. * @type {string}
  896. */
  897. JitsiTrack.AUDIO = "audio";
  898. /**
  899. * Returns the type (audio or video) of this track.
  900. */
  901. JitsiTrack.prototype.getType = function() {
  902. return this.type;
  903. };
  904. /**
  905. * Returns the RTCMediaStream from the browser (?).
  906. */
  907. JitsiTrack.prototype.getOriginalStream = function() {
  908. return this.stream;
  909. }
  910. /**
  911. * Mutes the track.
  912. */
  913. JitsiTrack.prototype.mute = function () {
  914. this._setMute(true);
  915. }
  916. /**
  917. * Unmutes the stream.
  918. */
  919. JitsiTrack.prototype.unmute = function () {
  920. this._setMute(false);
  921. }
  922. /**
  923. * Attaches the MediaStream of this track to an HTML container (?).
  924. * @param container the HTML container
  925. */
  926. JitsiTrack.prototype.attach = function (container) {
  927. RTC.attachMediaStream(container, this.stream);
  928. }
  929. /**
  930. * Removes the track from the passed HTML container.
  931. * @param container the HTML container
  932. */
  933. JitsiTrack.prototype.detach = function (container) {
  934. $(container).find(">video").remove();
  935. }
  936. /**
  937. * Stops sending the media track. And removes it from the HTML.
  938. * NOTE: Works for local tracks only.
  939. */
  940. JitsiTrack.prototype.stop = function () {
  941. this.detach();
  942. }
  943. /**
  944. * Starts sending the track.
  945. * NOTE: Works for local tracks only.
  946. */
  947. JitsiTrack.prototype.start = function() {
  948. }
  949. /**
  950. * Returns true if this is a video track and the source of the video is a
  951. * screen capture as opposed to a camera.
  952. */
  953. JitsiTrack.prototype.isScreenSharing = function(){
  954. }
  955. /**
  956. * Returns id of the track.
  957. * @returns {string} id of the track or null if this is fake track.
  958. */
  959. JitsiTrack.prototype.getId = function () {
  960. var tracks = this.stream.getTracks();
  961. if(!tracks || tracks.length === 0)
  962. return null;
  963. return tracks[0].id;
  964. };
  965. module.exports = JitsiTrack;
  966. },{"./RTCBrowserType":14,"./RTCUtils":15}],13:[function(require,module,exports){
  967. /* global APP */
  968. var EventEmitter = require("events");
  969. var RTCBrowserType = require("./RTCBrowserType");
  970. var RTCUtils = require("./RTCUtils.js");
  971. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  972. var DataChannels = require("./DataChannels");
  973. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  974. var DesktopSharingEventTypes
  975. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  976. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  977. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  978. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  979. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  980. var desktopsharing = require("../desktopsharing/desktopsharing");
  981. function getMediaStreamUsage()
  982. {
  983. var result = {
  984. audio: true,
  985. video: true
  986. };
  987. /** There are some issues with the desktop sharing
  988. * when this property is enabled.
  989. * WARNING: We must change the implementation to start video/audio if we
  990. * receive from the focus that the peer is not muted.
  991. var isSecureConnection = window.location.protocol == "https:";
  992. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  993. {
  994. result = {
  995. audio: false,
  996. video: false
  997. };
  998. }
  999. **/
  1000. return result;
  1001. }
  1002. var rtcReady = false;
  1003. function RTC(room, options) {
  1004. this.devices = {
  1005. audio: true,
  1006. video: true
  1007. };
  1008. this.room = room;
  1009. this.localStreams = [];
  1010. this.remoteStreams = {};
  1011. this.localAudio = null;
  1012. this.localVideo = null;
  1013. this.eventEmitter = new EventEmitter();
  1014. var self = this;
  1015. this.options = options || {};
  1016. desktopsharing.addListener(
  1017. function (stream, isUsingScreenStream, callback) {
  1018. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1019. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1020. }
  1021. RTC.prototype.obtainAudioAndVideoPermissions = function (options) {
  1022. return RTCUtils.obtainAudioAndVideoPermissions(this,
  1023. options.devices, getMediaStreamUsage(), options.resolution);
  1024. }
  1025. RTC.prototype.onIncommingCall = function(event) {
  1026. if(this.options.config.openSctp)
  1027. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  1028. this.room.addLocalStreams(this.localStreams);
  1029. }
  1030. RTC.prototype.selectedEndpoint = function (id) {
  1031. if(this.dataChannels)
  1032. this.dataChannels.handleSelectedEndpointEvent(id);
  1033. }
  1034. RTC.prototype.pinEndpoint = function (id) {
  1035. if(this.dataChannels)
  1036. this.dataChannels.handlePinnedEndpointEvent(id);
  1037. }
  1038. RTC.prototype.addStreamListener = function (listener, eventType) {
  1039. this.eventEmitter.on(eventType, listener);
  1040. };
  1041. RTC.prototype.addListener = function (type, listener) {
  1042. this.eventEmitter.on(type, listener);
  1043. };
  1044. RTC.prototype.removeListener = function (listener, eventType) {
  1045. this.eventEmitter.removeListener(eventType, listener);
  1046. };
  1047. RTC.prototype.removeStreamListener = function (listener, eventType) {
  1048. if(!(eventType instanceof StreamEventTypes))
  1049. throw "Illegal argument";
  1050. this.eventEmitter.removeListener(eventType, listener);
  1051. };
  1052. RTC.addRTCReadyListener = function (listener) {
  1053. RTCUtils.eventEmitter.on(RTCEvents.RTC_READY, listener);
  1054. }
  1055. RTC.removeRTCReadyListener = function (listener) {
  1056. RTCUtils.eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1057. }
  1058. RTC.isRTCReady = function () {
  1059. return rtcReady;
  1060. }
  1061. RTC.init = function (options) {
  1062. // In case of IE we continue from 'onReady' callback
  1063. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1064. // once it is initialized.
  1065. var onReady = function () {
  1066. rtcReady = true;
  1067. RTCUtils.eventEmitter.emit(RTCEvents.RTC_READY, true);
  1068. };
  1069. RTCUtils.init(onReady, options || {});
  1070. // Call onReady() if Temasys plugin is not used
  1071. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1072. onReady();
  1073. }
  1074. }
  1075. RTC.prototype.createLocalStreams = function (streams, change) {
  1076. for (var i = 0; i < streams.length; i++) {
  1077. var localStream = new JitsiLocalTrack(this, streams[i].stream,
  1078. this.eventEmitter, streams[i].videoType,
  1079. streams[i].isGUMStream);
  1080. this.localStreams.push(localStream);
  1081. if (streams[i].isMuted === true)
  1082. localStream.setMute(true);
  1083. if (streams[i].type == "audio") {
  1084. this.localAudio = localStream;
  1085. } else {
  1086. this.localVideo = localStream;
  1087. }
  1088. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1089. if (change)
  1090. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  1091. this.eventEmitter.emit(eventType, localStream, streams[i].isMuted);
  1092. }
  1093. return this.localStreams;
  1094. };
  1095. RTC.prototype.removeLocalStream = function (stream) {
  1096. for(var i = 0; i < this.localStreams.length; i++) {
  1097. if(this.localStreams[i].getOriginalStream() === stream) {
  1098. delete this.localStreams[i];
  1099. return;
  1100. }
  1101. }
  1102. };
  1103. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  1104. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  1105. RTCBrowserType.getBrowserType(), this.eventEmitter);
  1106. if(!data.peerjid)
  1107. return;
  1108. var jid = data.peerjid;
  1109. if(!this.remoteStreams[jid]) {
  1110. this.remoteStreams[jid] = {};
  1111. }
  1112. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1113. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1114. return remoteStream;
  1115. };
  1116. RTC.getPCConstraints = function () {
  1117. return RTCUtils.pc_constraints;
  1118. };
  1119. RTC.prototype.getUserMediaWithConstraints = function(um, success_callback,
  1120. failure_callback, resolution,
  1121. bandwidth, fps, desktopStream)
  1122. {
  1123. return RTCUtils.getUserMediaWithConstraints(this, um, success_callback,
  1124. failure_callback, resolution, bandwidth, fps, desktopStream);
  1125. };
  1126. RTC.attachMediaStream = function (elSelector, stream) {
  1127. RTCUtils.attachMediaStream(elSelector, stream);
  1128. };
  1129. RTC.getStreamID = function (stream) {
  1130. return RTCUtils.getStreamID(stream);
  1131. };
  1132. RTC.getVideoSrc = function (element) {
  1133. return RTCUtils.getVideoSrc(element);
  1134. };
  1135. RTC.setVideoSrc = function (element, src) {
  1136. RTCUtils.setVideoSrc(element, src);
  1137. };
  1138. RTC.prototype.getVideoElementName = function () {
  1139. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1140. };
  1141. RTC.prototype.dispose = function() {
  1142. };
  1143. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  1144. var stream;
  1145. if(this.remoteStreams[jid] &&
  1146. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1147. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1148. }
  1149. if(!stream)
  1150. return true;
  1151. if (value != stream.muted) {
  1152. stream.setMute(value);
  1153. return true;
  1154. }
  1155. return false;
  1156. };
  1157. RTC.prototype.switchVideoStreams = function (new_stream) {
  1158. this.localVideo.stream = new_stream;
  1159. this.localStreams = [];
  1160. //in firefox we have only one stream object
  1161. if (this.localAudio.getOriginalStream() != new_stream)
  1162. this.localStreams.push(this.localAudio);
  1163. this.localStreams.push(this.localVideo);
  1164. };
  1165. RTC.prototype.changeLocalVideo = function (stream, isUsingScreenStream, callback) {
  1166. var oldStream = this.localVideo.getOriginalStream();
  1167. var type = (isUsingScreenStream ? "screen" : "camera");
  1168. var localCallback = callback;
  1169. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1170. localCallback = function() {
  1171. this.room.setVideoMute(false, function(mute) {
  1172. this.eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1173. }.bind(this));
  1174. callback();
  1175. };
  1176. }
  1177. // FIXME: Workaround for FF/IE/Safari
  1178. if (stream && stream.videoStream) {
  1179. stream = stream.videoStream;
  1180. }
  1181. var videoStream = RTCUtils.createStream(stream, true);
  1182. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1183. // Stop the stream to trigger onended event for old stream
  1184. oldStream.stop();
  1185. this.switchVideoStreams(videoStream, oldStream);
  1186. this.room.switchStreams(videoStream, oldStream,localCallback);
  1187. };
  1188. RTC.prototype.changeLocalAudio = function (stream, callback) {
  1189. var oldStream = this.localAudio.getOriginalStream();
  1190. var newStream = RTCUtils.createStream(stream);
  1191. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1192. // Stop the stream to trigger onended event for old stream
  1193. oldStream.stop();
  1194. this.room.switchStreams(newStream, oldStream, callback, true);
  1195. };
  1196. RTC.prototype.isVideoMuted = function (jid) {
  1197. if (jid === APP.xmpp.myJid()) {
  1198. var localVideo = APP.RTC.localVideo;
  1199. return (!localVideo || localVideo.isMuted());
  1200. } else {
  1201. if (!this.remoteStreams[jid] ||
  1202. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1203. return null;
  1204. }
  1205. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1206. }
  1207. };
  1208. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1209. if (!this.localVideo)
  1210. return;
  1211. if (mute == this.localVideo.isMuted())
  1212. {
  1213. APP.xmpp.sendVideoInfoPresence(mute);
  1214. if (callback)
  1215. callback(mute);
  1216. }
  1217. else
  1218. {
  1219. this.localVideo.setMute(mute);
  1220. this.room.setVideoMute(
  1221. mute,
  1222. callback,
  1223. options);
  1224. }
  1225. };
  1226. RTC.prototype.setDeviceAvailability = function (devices) {
  1227. if(!devices)
  1228. return;
  1229. if(devices.audio === true || devices.audio === false)
  1230. this.devices.audio = devices.audio;
  1231. if(devices.video === true || devices.video === false)
  1232. this.devices.video = devices.video;
  1233. this.eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1234. };
  1235. module.exports = RTC;
  1236. },{"../../service/RTC/MediaStreamTypes":70,"../../service/RTC/RTCEvents.js":71,"../../service/RTC/StreamEventTypes.js":73,"../../service/desktopsharing/DesktopSharingEventTypes":75,"../../service/xmpp/XMPPEvents":76,"../desktopsharing/desktopsharing":17,"./DataChannels":9,"./JitsiLocalTrack.js":10,"./JitsiRemoteTrack.js":11,"./RTCBrowserType":14,"./RTCUtils.js":15,"events":77}],14:[function(require,module,exports){
  1237. var currentBrowser;
  1238. var browserVersion;
  1239. var RTCBrowserType = {
  1240. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1241. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1242. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1243. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1244. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1245. getBrowserType: function () {
  1246. return currentBrowser;
  1247. },
  1248. isChrome: function () {
  1249. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1250. },
  1251. isOpera: function () {
  1252. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1253. },
  1254. isFirefox: function () {
  1255. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1256. },
  1257. isIExplorer: function () {
  1258. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1259. },
  1260. isSafari: function () {
  1261. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1262. },
  1263. isTemasysPluginUsed: function () {
  1264. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1265. },
  1266. getFirefoxVersion: function () {
  1267. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1268. },
  1269. getChromeVersion: function () {
  1270. return RTCBrowserType.isChrome() ? browserVersion : null;
  1271. },
  1272. usesPlanB: function() {
  1273. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1274. RTCBrowserType.isTemasysPluginUsed();
  1275. },
  1276. usesUnifiedPlan: function() {
  1277. return RTCBrowserType.isFirefox();
  1278. }
  1279. // Add version getters for other browsers when needed
  1280. };
  1281. // detectOpera() must be called before detectChrome() !!!
  1282. // otherwise Opera wil be detected as Chrome
  1283. function detectChrome() {
  1284. if (navigator.webkitGetUserMedia) {
  1285. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1286. var userAgent = navigator.userAgent.toLowerCase();
  1287. // We can assume that user agent is chrome, because it's
  1288. // enforced when 'ext' streaming method is set
  1289. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1290. console.log("This appears to be Chrome, ver: " + ver);
  1291. return ver;
  1292. }
  1293. return null;
  1294. }
  1295. function detectOpera() {
  1296. var userAgent = navigator.userAgent;
  1297. if (userAgent.match(/Opera|OPR/)) {
  1298. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1299. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1300. console.info("This appears to be Opera, ver: " + version);
  1301. return version;
  1302. }
  1303. return null;
  1304. }
  1305. function detectFirefox() {
  1306. if (navigator.mozGetUserMedia) {
  1307. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1308. var version = parseInt(
  1309. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1310. console.log('This appears to be Firefox, ver: ' + version);
  1311. return version;
  1312. }
  1313. return null;
  1314. }
  1315. function detectSafari() {
  1316. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1317. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1318. console.info("This appears to be Safari");
  1319. // FIXME detect Safari version when needed
  1320. return 1;
  1321. }
  1322. return null;
  1323. }
  1324. function detectIE() {
  1325. var version;
  1326. var ua = window.navigator.userAgent;
  1327. var msie = ua.indexOf('MSIE ');
  1328. if (msie > 0) {
  1329. // IE 10 or older => return version number
  1330. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1331. }
  1332. var trident = ua.indexOf('Trident/');
  1333. if (!version && trident > 0) {
  1334. // IE 11 => return version number
  1335. var rv = ua.indexOf('rv:');
  1336. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1337. }
  1338. var edge = ua.indexOf('Edge/');
  1339. if (!version && edge > 0) {
  1340. // IE 12 => return version number
  1341. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1342. }
  1343. if (version) {
  1344. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1345. console.info("This appears to be IExplorer, ver: " + version);
  1346. }
  1347. return version;
  1348. }
  1349. function detectBrowser() {
  1350. var version;
  1351. var detectors = [
  1352. detectOpera,
  1353. detectChrome,
  1354. detectFirefox,
  1355. detectIE,
  1356. detectSafari
  1357. ];
  1358. // Try all browser detectors
  1359. for (var i = 0; i < detectors.length; i++) {
  1360. version = detectors[i]();
  1361. if (version)
  1362. return version;
  1363. }
  1364. console.error("Failed to detect browser type");
  1365. return undefined;
  1366. }
  1367. browserVersion = detectBrowser();
  1368. module.exports = RTCBrowserType;
  1369. },{}],15:[function(require,module,exports){
  1370. /* global config, require, attachMediaStream, getUserMedia */
  1371. var RTCBrowserType = require("./RTCBrowserType");
  1372. var Resolutions = require("../../service/RTC/Resolutions");
  1373. var AdapterJS = require("./adapter.screenshare");
  1374. var SDPUtil = require("../xmpp/SDPUtil");
  1375. var EventEmitter = require("events");
  1376. function DummyMediaStream(id) {
  1377. this.id = id;
  1378. this.label = id;
  1379. this.stop = function() { };
  1380. this.getAudioTracks = function() { return []; };
  1381. this.getVideoTracks = function() { return []; };
  1382. }
  1383. function getPreviousResolution(resolution) {
  1384. if(!Resolutions[resolution])
  1385. return null;
  1386. var order = Resolutions[resolution].order;
  1387. var res = null;
  1388. var resName = null;
  1389. for(var i in Resolutions) {
  1390. var tmp = Resolutions[i];
  1391. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1392. resName = i;
  1393. res = tmp;
  1394. }
  1395. }
  1396. return resName;
  1397. }
  1398. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1399. if (Resolutions[resolution]) {
  1400. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1401. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1402. }
  1403. else if (isAndroid) {
  1404. // FIXME can't remember if the purpose of this was to always request
  1405. // low resolution on Android ? if yes it should be moved up front
  1406. constraints.video.mandatory.minWidth = 320;
  1407. constraints.video.mandatory.minHeight = 240;
  1408. constraints.video.mandatory.maxFrameRate = 15;
  1409. }
  1410. if (constraints.video.mandatory.minWidth)
  1411. constraints.video.mandatory.maxWidth =
  1412. constraints.video.mandatory.minWidth;
  1413. if (constraints.video.mandatory.minHeight)
  1414. constraints.video.mandatory.maxHeight =
  1415. constraints.video.mandatory.minHeight;
  1416. }
  1417. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1418. {
  1419. var constraints = {audio: false, video: false};
  1420. if (um.indexOf('video') >= 0) {
  1421. // same behaviour as true
  1422. constraints.video = { mandatory: {}, optional: [] };
  1423. constraints.video.optional.push({ googLeakyBucket: true });
  1424. setResolutionConstraints(constraints, resolution, isAndroid);
  1425. }
  1426. if (um.indexOf('audio') >= 0) {
  1427. if (!RTCBrowserType.isFirefox()) {
  1428. // same behaviour as true
  1429. constraints.audio = { mandatory: {}, optional: []};
  1430. // if it is good enough for hangouts...
  1431. constraints.audio.optional.push(
  1432. {googEchoCancellation: true},
  1433. {googAutoGainControl: true},
  1434. {googNoiseSupression: true},
  1435. {googHighpassFilter: true},
  1436. {googNoisesuppression2: true},
  1437. {googEchoCancellation2: true},
  1438. {googAutoGainControl2: true}
  1439. );
  1440. } else {
  1441. constraints.audio = true;
  1442. }
  1443. }
  1444. if (um.indexOf('screen') >= 0) {
  1445. if (RTCBrowserType.isChrome()) {
  1446. constraints.video = {
  1447. mandatory: {
  1448. chromeMediaSource: "screen",
  1449. googLeakyBucket: true,
  1450. maxWidth: window.screen.width,
  1451. maxHeight: window.screen.height,
  1452. maxFrameRate: 3
  1453. },
  1454. optional: []
  1455. };
  1456. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1457. constraints.video = {
  1458. optional: [
  1459. {
  1460. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1461. }
  1462. ]
  1463. };
  1464. } else {
  1465. console.error(
  1466. "'screen' WebRTC media source is supported only in Chrome" +
  1467. " and with Temasys plugin");
  1468. }
  1469. }
  1470. if (um.indexOf('desktop') >= 0) {
  1471. constraints.video = {
  1472. mandatory: {
  1473. chromeMediaSource: "desktop",
  1474. chromeMediaSourceId: desktopStream,
  1475. googLeakyBucket: true,
  1476. maxWidth: window.screen.width,
  1477. maxHeight: window.screen.height,
  1478. maxFrameRate: 3
  1479. },
  1480. optional: []
  1481. };
  1482. }
  1483. if (bandwidth) {
  1484. if (!constraints.video) {
  1485. //same behaviour as true
  1486. constraints.video = {mandatory: {}, optional: []};
  1487. }
  1488. constraints.video.optional.push({bandwidth: bandwidth});
  1489. }
  1490. if (fps) {
  1491. // for some cameras it might be necessary to request 30fps
  1492. // so they choose 30fps mjpg over 10fps yuy2
  1493. if (!constraints.video) {
  1494. // same behaviour as true;
  1495. constraints.video = {mandatory: {}, optional: []};
  1496. }
  1497. constraints.video.mandatory.minFrameRate = fps;
  1498. }
  1499. return constraints;
  1500. }
  1501. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1502. var RTCUtils = {
  1503. eventEmitter: new EventEmitter(),
  1504. init: function (onTemasysPluginReady, options) {
  1505. var self = this;
  1506. if (RTCBrowserType.isFirefox()) {
  1507. var FFversion = RTCBrowserType.getFirefoxVersion();
  1508. if (FFversion >= 40) {
  1509. this.peerconnection = mozRTCPeerConnection;
  1510. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1511. this.pc_constraints = {};
  1512. this.attachMediaStream = function (element, stream) {
  1513. // srcObject is being standardized and FF will eventually
  1514. // support that unprefixed. FF also supports the
  1515. // "element.src = URL.createObjectURL(...)" combo, but that
  1516. // will be deprecated in favour of srcObject.
  1517. //
  1518. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1519. // https://github.com/webrtc/samples/issues/302
  1520. if (!element[0])
  1521. return;
  1522. element[0].mozSrcObject = stream;
  1523. element[0].play();
  1524. };
  1525. this.getStreamID = function (stream) {
  1526. var id = stream.id;
  1527. if (!id) {
  1528. var tracks = stream.getVideoTracks();
  1529. if (!tracks || tracks.length === 0) {
  1530. tracks = stream.getAudioTracks();
  1531. }
  1532. id = tracks[0].id;
  1533. }
  1534. return SDPUtil.filter_special_chars(id);
  1535. };
  1536. this.getVideoSrc = function (element) {
  1537. if (!element)
  1538. return null;
  1539. return element.mozSrcObject;
  1540. };
  1541. this.setVideoSrc = function (element, src) {
  1542. if (element)
  1543. element.mozSrcObject = src;
  1544. };
  1545. RTCSessionDescription = mozRTCSessionDescription;
  1546. RTCIceCandidate = mozRTCIceCandidate;
  1547. } else {
  1548. console.error(
  1549. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1550. window.location.href = 'unsupported_browser.html';
  1551. return;
  1552. }
  1553. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1554. this.peerconnection = webkitRTCPeerConnection;
  1555. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1556. this.attachMediaStream = function (element, stream) {
  1557. element.attr('src', webkitURL.createObjectURL(stream));
  1558. };
  1559. this.getStreamID = function (stream) {
  1560. // streams from FF endpoints have the characters '{' and '}'
  1561. // that make jQuery choke.
  1562. return SDPUtil.filter_special_chars(stream.id);
  1563. };
  1564. this.getVideoSrc = function (element) {
  1565. if (!element)
  1566. return null;
  1567. return element.getAttribute("src");
  1568. };
  1569. this.setVideoSrc = function (element, src) {
  1570. if (element)
  1571. element.setAttribute("src", src);
  1572. };
  1573. // DTLS should now be enabled by default but..
  1574. this.pc_constraints = {'optional': [
  1575. {'DtlsSrtpKeyAgreement': 'true'}
  1576. ]};
  1577. if (options.useIPv6) {
  1578. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1579. this.pc_constraints.optional.push({googIPv6: true});
  1580. }
  1581. if (navigator.userAgent.indexOf('Android') != -1) {
  1582. this.pc_constraints = {}; // disable DTLS on Android
  1583. }
  1584. if (!webkitMediaStream.prototype.getVideoTracks) {
  1585. webkitMediaStream.prototype.getVideoTracks = function () {
  1586. return this.videoTracks;
  1587. };
  1588. }
  1589. if (!webkitMediaStream.prototype.getAudioTracks) {
  1590. webkitMediaStream.prototype.getAudioTracks = function () {
  1591. return this.audioTracks;
  1592. };
  1593. }
  1594. }
  1595. // Detect IE/Safari
  1596. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1597. //AdapterJS.WebRTCPlugin.setLogLevel(
  1598. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1599. AdapterJS.webRTCReady(function (isPlugin) {
  1600. self.peerconnection = RTCPeerConnection;
  1601. self.getUserMedia = getUserMedia;
  1602. self.attachMediaStream = function (elSel, stream) {
  1603. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1604. return;
  1605. }
  1606. attachMediaStream(elSel[0], stream);
  1607. };
  1608. self.getStreamID = function (stream) {
  1609. var id = SDPUtil.filter_special_chars(stream.label);
  1610. return id;
  1611. };
  1612. self.getVideoSrc = function (element) {
  1613. if (!element) {
  1614. console.warn("Attempt to get video SRC of null element");
  1615. return null;
  1616. }
  1617. var children = element.children;
  1618. for (var i = 0; i !== children.length; ++i) {
  1619. if (children[i].name === 'streamId') {
  1620. return children[i].value;
  1621. }
  1622. }
  1623. //console.info(element.id + " SRC: " + src);
  1624. return null;
  1625. };
  1626. self.setVideoSrc = function (element, src) {
  1627. //console.info("Set video src: ", element, src);
  1628. if (!src) {
  1629. console.warn("Not attaching video stream, 'src' is null");
  1630. return;
  1631. }
  1632. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1633. var stream = AdapterJS.WebRTCPlugin.plugin
  1634. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1635. attachMediaStream(element, stream);
  1636. };
  1637. onTemasysPluginReady(isPlugin);
  1638. });
  1639. } else {
  1640. try {
  1641. console.log('Browser does not appear to be WebRTC-capable');
  1642. } catch (e) {
  1643. }
  1644. window.location.href = 'unsupported_browser.html';
  1645. }
  1646. },
  1647. getUserMediaWithConstraints: function (RTC, um, success_callback, failure_callback, resolution, bandwidth, fps, desktopStream) {
  1648. // Check if we are running on Android device
  1649. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1650. var constraints = getConstraints(
  1651. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1652. console.info("Get media constraints", constraints);
  1653. var self = this;
  1654. try {
  1655. this.getUserMedia(constraints,
  1656. function (stream) {
  1657. console.log('onUserMediaSuccess');
  1658. self.setAvailableDevices(RTC, um, true);
  1659. success_callback(stream);
  1660. },
  1661. function (error) {
  1662. self.setAvailableDevices(RTC, um, false);
  1663. console.warn('Failed to get access to local media. Error ',
  1664. error, constraints);
  1665. if (failure_callback) {
  1666. failure_callback(error, resolution);
  1667. }
  1668. });
  1669. } catch (e) {
  1670. console.error('GUM failed: ', e);
  1671. if (failure_callback) {
  1672. failure_callback(e);
  1673. }
  1674. }
  1675. },
  1676. setAvailableDevices: function (RTC, um, available) {
  1677. var devices = {};
  1678. if (um.indexOf("video") != -1) {
  1679. devices.video = available;
  1680. }
  1681. if (um.indexOf("audio") != -1) {
  1682. devices.audio = available;
  1683. }
  1684. RTC.setDeviceAvailability(devices);
  1685. },
  1686. /**
  1687. * We ask for audio and video combined stream in order to get permissions and
  1688. * not to ask twice.
  1689. */
  1690. obtainAudioAndVideoPermissions: function (RTC, devices, usageOptions, resolution) {
  1691. var self = this;
  1692. // Get AV
  1693. return new Promise(function (resolve, reject) {
  1694. var successCallback = function (stream) {
  1695. resolve(self.successCallback(RTC , stream, usageOptions));
  1696. };
  1697. if (!devices)
  1698. devices = ['audio', 'video'];
  1699. var newDevices = [];
  1700. if (usageOptions)
  1701. for (var i = 0; i < devices.length; i++) {
  1702. var device = devices[i];
  1703. if (usageOptions[device] === true)
  1704. newDevices.push(device);
  1705. }
  1706. else
  1707. newDevices = devices;
  1708. if (newDevices.length === 0) {
  1709. successCallback();
  1710. return;
  1711. }
  1712. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1713. // With FF/IE we can't split the stream into audio and video because FF
  1714. // doesn't support media stream constructors. So, we need to get the
  1715. // audio stream separately from the video stream using two distinct GUM
  1716. // calls. Not very user friendly :-( but we don't have many other
  1717. // options neither.
  1718. //
  1719. // Note that we pack those 2 streams in a single object and pass it to
  1720. // the successCallback method.
  1721. var obtainVideo = function (audioStream) {
  1722. self.getUserMediaWithConstraints(
  1723. RTC,
  1724. ['video'],
  1725. function (videoStream) {
  1726. return successCallback({
  1727. audioStream: audioStream,
  1728. videoStream: videoStream
  1729. });
  1730. },
  1731. function (error, resolution) {
  1732. console.error(
  1733. 'failed to obtain video stream - stop', error);
  1734. self.errorCallback(error, resolve, RTC, resolution);
  1735. },
  1736. config.resolution || '360');
  1737. };
  1738. var obtainAudio = function () {
  1739. self.getUserMediaWithConstraints(
  1740. RTC,
  1741. ['audio'],
  1742. function (audioStream) {
  1743. if (newDevices.indexOf('video') !== -1)
  1744. obtainVideo(audioStream);
  1745. },
  1746. function (error) {
  1747. console.error(
  1748. 'failed to obtain audio stream - stop', error);
  1749. self.errorCallback(error, resolve, RTC);
  1750. }
  1751. );
  1752. };
  1753. if (newDevices.indexOf('audio') !== -1) {
  1754. obtainAudio();
  1755. } else {
  1756. obtainVideo(null);
  1757. }
  1758. } else {
  1759. this.getUserMediaWithConstraints(
  1760. RTC,
  1761. newDevices,
  1762. function (stream) {
  1763. successCallback(stream);
  1764. },
  1765. function (error, resolution) {
  1766. self.errorCallback(error, resolve, RTC, resolution);
  1767. },
  1768. resolution || '360');
  1769. }
  1770. }.bind(this));
  1771. },
  1772. successCallback: function (RTC, stream, usageOptions) {
  1773. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1774. // it's an object with two properties: audioStream, videoStream.
  1775. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1776. console.log('got', stream, stream.getAudioTracks().length,
  1777. stream.getVideoTracks().length);
  1778. return this.handleLocalStream(RTC, stream, usageOptions);
  1779. },
  1780. errorCallback: function (error, resolve, RTC, currentResolution) {
  1781. var self = this;
  1782. console.error('failed to obtain audio/video stream - trying audio only', error);
  1783. var resolution = getPreviousResolution(currentResolution);
  1784. if (typeof error == "object" && error.constraintName && error.name
  1785. && (error.name == "ConstraintNotSatisfiedError" ||
  1786. error.name == "OverconstrainedError") &&
  1787. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1788. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1789. && resolution != null) {
  1790. self.getUserMediaWithConstraints(RTC, ['audio', 'video'],
  1791. function (stream) {
  1792. resolve(self.successCallback(RTC, stream));
  1793. }, function (error, resolution) {
  1794. return self.errorCallback(error, resolve, RTC, resolution);
  1795. }, resolution);
  1796. }
  1797. else {
  1798. self.getUserMediaWithConstraints(
  1799. RTC,
  1800. ['audio'],
  1801. function (stream) {
  1802. resolve(self.successCallback(RTC, stream));
  1803. },
  1804. function (error) {
  1805. console.error('failed to obtain audio/video stream - stop',
  1806. error);
  1807. resolve(self.successCallback(RTC, null));
  1808. }
  1809. );
  1810. }
  1811. },
  1812. handleLocalStream: function (service, stream, usageOptions) {
  1813. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1814. // an object with two properties: audioStream, videoStream.
  1815. if (window.webkitMediaStream) {
  1816. audioStream = new webkitMediaStream();
  1817. videoStream = new webkitMediaStream();
  1818. if (stream) {
  1819. var audioTracks = stream.getAudioTracks();
  1820. for (var i = 0; i < audioTracks.length; i++) {
  1821. audioStream.addTrack(audioTracks[i]);
  1822. }
  1823. var videoTracks = stream.getVideoTracks();
  1824. for (i = 0; i < videoTracks.length; i++) {
  1825. videoStream.addTrack(videoTracks[i]);
  1826. }
  1827. }
  1828. }
  1829. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  1830. if (stream && stream.audioStream)
  1831. audioStream = stream.audioStream;
  1832. else
  1833. audioStream = new DummyMediaStream("dummyAudio");
  1834. if (stream && stream.videoStream)
  1835. videoStream = stream.videoStream;
  1836. else
  1837. videoStream = new DummyMediaStream("dummyVideo");
  1838. }
  1839. var audioMuted = (usageOptions && usageOptions.audio === false),
  1840. videoMuted = (usageOptions && usageOptions.video === false);
  1841. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1842. videoGUM = (!usageOptions || usageOptions.video !== false);
  1843. return service.createLocalStreams(
  1844. [
  1845. {stream: audioStream, type: "audio", isMuted: audioMuted, isGUMStream: audioGUM, videoType: null},
  1846. {stream: videoStream, type: "video", isMuted: videoMuted, isGUMStream: videoGUM, videoType: "camera"}
  1847. ]);
  1848. },
  1849. createStream: function (stream, isVideo) {
  1850. var newStream = null;
  1851. if (window.webkitMediaStream) {
  1852. newStream = new webkitMediaStream();
  1853. if (newStream) {
  1854. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1855. for (var i = 0; i < tracks.length; i++) {
  1856. newStream.addTrack(tracks[i]);
  1857. }
  1858. }
  1859. }
  1860. else {
  1861. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1862. if (stream) {
  1863. newStream = stream;
  1864. } else {
  1865. newStream =
  1866. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1867. }
  1868. }
  1869. return newStream;
  1870. }
  1871. }
  1872. module.exports = RTCUtils;
  1873. },{"../../service/RTC/Resolutions":72,"../xmpp/SDPUtil":25,"./RTCBrowserType":14,"./adapter.screenshare":16,"events":77}],16:[function(require,module,exports){
  1874. /*! adapterjs - custom version from - 2015-08-12 */
  1875. // Adapter's interface.
  1876. var AdapterJS = AdapterJS || {};
  1877. // Browserify compatibility
  1878. if(typeof exports !== 'undefined') {
  1879. module.exports = AdapterJS;
  1880. }
  1881. AdapterJS.options = AdapterJS.options || {};
  1882. // uncomment to get virtual webcams
  1883. // AdapterJS.options.getAllCams = true;
  1884. // uncomment to prevent the install prompt when the plugin in not yet installed
  1885. // AdapterJS.options.hidePluginInstallPrompt = true;
  1886. // AdapterJS version
  1887. AdapterJS.VERSION = '0.11.1';
  1888. // This function will be called when the WebRTC API is ready to be used
  1889. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1890. // the plugin
  1891. // You may Override this function to synchronise the start of your application
  1892. // with the WebRTC API being ready.
  1893. // If you decide not to override use this synchronisation, it may result in
  1894. // an extensive CPU usage on the plugin start (once per tab loaded)
  1895. // Params:
  1896. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1897. //
  1898. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1899. // The WebRTC API is ready.
  1900. // Override me and do whatever you want here
  1901. };
  1902. // Sets a callback function to be called when the WebRTC interface is ready.
  1903. // The first argument is the function to callback.\
  1904. // Throws an error if the first argument is not a function
  1905. AdapterJS.webRTCReady = function (callback) {
  1906. if (typeof callback !== 'function') {
  1907. throw new Error('Callback provided is not a function');
  1908. }
  1909. if (true === AdapterJS.onwebrtcreadyDone) {
  1910. // All WebRTC interfaces are ready, just call the callback
  1911. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1912. } else {
  1913. // will be triggered automatically when your browser/plugin is ready.
  1914. AdapterJS.onwebrtcready = callback;
  1915. }
  1916. };
  1917. // Plugin namespace
  1918. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1919. // The object to store plugin information
  1920. AdapterJS.WebRTCPlugin.pluginInfo = {
  1921. prefix : 'Tem',
  1922. plugName : 'TemWebRTCPlugin',
  1923. pluginId : 'plugin0',
  1924. type : 'application/x-temwebrtcplugin',
  1925. onload : '__TemWebRTCReady0',
  1926. portalLink : 'http://skylink.io/plugin/',
  1927. downloadLink : null, //set below
  1928. companyName: 'Temasys'
  1929. };
  1930. if(!!navigator.platform.match(/^Mac/i)) {
  1931. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1932. }
  1933. else if(!!navigator.platform.match(/^Win/i)) {
  1934. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1935. }
  1936. // Unique identifier of each opened page
  1937. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1938. // Use this whenever you want to call the plugin.
  1939. AdapterJS.WebRTCPlugin.plugin = null;
  1940. // Set log level for the plugin once it is ready.
  1941. // The different values are
  1942. // This is an asynchronous function that will run when the plugin is ready
  1943. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1944. // Defines webrtc's JS interface according to the plugin's implementation.
  1945. // Define plugin Browsers as WebRTC Interface.
  1946. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1947. // This function detects whether or not a plugin is installed.
  1948. // Checks if Not IE (firefox, for example), else if it's IE,
  1949. // we're running IE and do something. If not it is not supported.
  1950. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1951. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1952. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1953. // Inject the HTML DOM object element into the page.
  1954. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1955. // States of readiness that the plugin goes through when
  1956. // being injected and stated
  1957. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1958. NONE : 0, // no plugin use
  1959. INITIALIZING : 1, // Detected need for plugin
  1960. INJECTING : 2, // Injecting plugin
  1961. INJECTED: 3, // Plugin element injected but not usable yet
  1962. READY: 4 // Plugin ready to be used
  1963. };
  1964. // Current state of the plugin. You cannot use the plugin before this is
  1965. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1966. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1967. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1968. // Used to make sure AdapterJS.onwebrtcready is only called once
  1969. AdapterJS.onwebrtcreadyDone = false;
  1970. // Log levels for the plugin.
  1971. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1972. /*
  1973. Log outputs are prefixed in some cases.
  1974. INFO: Information reported by the plugin.
  1975. ERROR: Errors originating from within the plugin.
  1976. WEBRTC: Error originating from within the libWebRTC library
  1977. */
  1978. // From the least verbose to the most verbose
  1979. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1980. NONE : 'NONE',
  1981. ERROR : 'ERROR',
  1982. WARNING : 'WARNING',
  1983. INFO: 'INFO',
  1984. VERBOSE: 'VERBOSE',
  1985. SENSITIVE: 'SENSITIVE'
  1986. };
  1987. // Does a waiting check before proceeding to load the plugin.
  1988. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1989. // This methid will use an interval to wait for the plugin to be ready.
  1990. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1991. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1992. // This function will be called when plugin is ready. It sends necessary
  1993. // details to the plugin.
  1994. // The function will wait for the document to be ready and the set the
  1995. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1996. // indicating that it can start being requested.
  1997. // This function is not in the IE/Safari condition brackets so that
  1998. // TemPluginLoaded function might be called on Chrome/Firefox.
  1999. // This function is the only private function that is not encapsulated to
  2000. // allow the plugin method to be called.
  2001. __TemWebRTCReady0 = function () {
  2002. if (document.readyState === 'complete') {
  2003. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2004. AdapterJS.maybeThroughWebRTCReady();
  2005. } else {
  2006. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2007. if (document.readyState === 'complete') {
  2008. // TODO: update comments, we wait for the document to be ready
  2009. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2010. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2011. AdapterJS.maybeThroughWebRTCReady();
  2012. }
  2013. }, 100);
  2014. }
  2015. };
  2016. AdapterJS.maybeThroughWebRTCReady = function() {
  2017. if (!AdapterJS.onwebrtcreadyDone) {
  2018. AdapterJS.onwebrtcreadyDone = true;
  2019. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2020. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2021. }
  2022. }
  2023. };
  2024. // Text namespace
  2025. AdapterJS.TEXT = {
  2026. PLUGIN: {
  2027. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2028. 'to work on this browser.',
  2029. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2030. BUTTON: 'Install Now'
  2031. },
  2032. REFRESH: {
  2033. REQUIRE_REFRESH: 'Please refresh page',
  2034. BUTTON: 'Refresh Page'
  2035. }
  2036. };
  2037. // The result of ice connection states.
  2038. // - starting: Ice connection is starting.
  2039. // - checking: Ice connection is checking.
  2040. // - connected Ice connection is connected.
  2041. // - completed Ice connection is connected.
  2042. // - done Ice connection has been completed.
  2043. // - disconnected Ice connection has been disconnected.
  2044. // - failed Ice connection has failed.
  2045. // - closed Ice connection is closed.
  2046. AdapterJS._iceConnectionStates = {
  2047. starting : 'starting',
  2048. checking : 'checking',
  2049. connected : 'connected',
  2050. completed : 'connected',
  2051. done : 'completed',
  2052. disconnected : 'disconnected',
  2053. failed : 'failed',
  2054. closed : 'closed'
  2055. };
  2056. //The IceConnection states that has been fired for each peer.
  2057. AdapterJS._iceConnectionFiredStates = [];
  2058. // Check if WebRTC Interface is defined.
  2059. AdapterJS.isDefined = null;
  2060. // This function helps to retrieve the webrtc detected browser information.
  2061. // This sets:
  2062. // - webrtcDetectedBrowser: The browser agent name.
  2063. // - webrtcDetectedVersion: The browser version.
  2064. // - webrtcDetectedType: The types of webRTC support.
  2065. // - 'moz': Mozilla implementation of webRTC.
  2066. // - 'webkit': WebKit implementation of webRTC.
  2067. // - 'plugin': Using the plugin implementation.
  2068. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2069. var hasMatch, checkMatch = navigator.userAgent.match(
  2070. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2071. if (/trident/i.test(checkMatch[1])) {
  2072. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2073. webrtcDetectedBrowser = 'IE';
  2074. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2075. } else if (checkMatch[1] === 'Chrome') {
  2076. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2077. if (hasMatch !== null) {
  2078. webrtcDetectedBrowser = 'opera';
  2079. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2080. }
  2081. }
  2082. if (navigator.userAgent.indexOf('Safari')) {
  2083. if (typeof InstallTrigger !== 'undefined') {
  2084. webrtcDetectedBrowser = 'firefox';
  2085. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2086. webrtcDetectedBrowser = 'IE';
  2087. } else if (
  2088. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2089. webrtcDetectedBrowser = 'safari';
  2090. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2091. webrtcDetectedBrowser = 'opera';
  2092. } else if (!!window.chrome) {
  2093. webrtcDetectedBrowser = 'chrome';
  2094. }
  2095. }
  2096. if (!webrtcDetectedBrowser) {
  2097. webrtcDetectedVersion = checkMatch[1];
  2098. }
  2099. if (!webrtcDetectedVersion) {
  2100. try {
  2101. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2102. [navigator.appName, navigator.appVersion, '-?'];
  2103. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2104. checkMatch.splice(1, 1, hasMatch[1]);
  2105. }
  2106. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2107. } catch (error) { }
  2108. }
  2109. };
  2110. // To fix configuration as some browsers does not support
  2111. // the 'urls' attribute.
  2112. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2113. if (pcConfig === null) {
  2114. return;
  2115. }
  2116. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2117. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2118. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2119. delete pcConfig.iceServers[i].urls;
  2120. }
  2121. }
  2122. };
  2123. AdapterJS.addEvent = function(elem, evnt, func) {
  2124. if (elem.addEventListener) { // W3C DOM
  2125. elem.addEventListener(evnt, func, false);
  2126. } else if (elem.attachEvent) {// OLD IE DOM
  2127. elem.attachEvent('on'+evnt, func);
  2128. } else { // No much to do
  2129. elem[evnt] = func;
  2130. }
  2131. };
  2132. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2133. // only inject once the page is ready
  2134. if (document.readyState !== 'complete') {
  2135. return;
  2136. }
  2137. var w = window;
  2138. var i = document.createElement('iframe');
  2139. i.style.position = 'fixed';
  2140. i.style.top = '-41px';
  2141. i.style.left = 0;
  2142. i.style.right = 0;
  2143. i.style.width = '100%';
  2144. i.style.height = '40px';
  2145. i.style.backgroundColor = '#ffffe1';
  2146. i.style.border = 'none';
  2147. i.style.borderBottom = '1px solid #888888';
  2148. i.style.zIndex = '9999999';
  2149. if(typeof i.style.webkitTransition === 'string') {
  2150. i.style.webkitTransition = 'all .5s ease-out';
  2151. } else if(typeof i.style.transition === 'string') {
  2152. i.style.transition = 'all .5s ease-out';
  2153. }
  2154. document.body.appendChild(i);
  2155. c = (i.contentWindow) ? i.contentWindow :
  2156. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2157. c.document.open();
  2158. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2159. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2160. 'middle; cursor: default;">' + text + '</span>');
  2161. if(buttonText && buttonLink) {
  2162. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2163. c.document.close();
  2164. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2165. if (!!displayRefreshBar) {
  2166. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2167. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2168. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2169. }
  2170. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2171. e.preventDefault();
  2172. try {
  2173. event.cancelBubble = true;
  2174. } catch(error) { }
  2175. var pluginInstallInterval = setInterval(function(){
  2176. if(! isIE) {
  2177. navigator.plugins.refresh(false);
  2178. }
  2179. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2180. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2181. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2182. function() {
  2183. clearInterval(pluginInstallInterval);
  2184. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  2185. },
  2186. function() { //Does nothing because not used here
  2187. });
  2188. } , 500);
  2189. });
  2190. }else {
  2191. c.document.close();
  2192. }
  2193. AdapterJS.addEvent(c.document, 'click', function() {
  2194. w.document.body.removeChild(i);
  2195. });
  2196. setTimeout(function() {
  2197. if(typeof i.style.webkitTransform === 'string') {
  2198. i.style.webkitTransform = 'translateY(40px)';
  2199. } else if(typeof i.style.transform === 'string') {
  2200. i.style.transform = 'translateY(40px)';
  2201. } else {
  2202. i.style.top = '0px';
  2203. }
  2204. }, 300);
  2205. };
  2206. // -----------------------------------------------------------
  2207. // Detected webrtc implementation. Types are:
  2208. // - 'moz': Mozilla implementation of webRTC.
  2209. // - 'webkit': WebKit implementation of webRTC.
  2210. // - 'plugin': Using the plugin implementation.
  2211. webrtcDetectedType = null;
  2212. // Detected webrtc datachannel support. Types are:
  2213. // - 'SCTP': SCTP datachannel support.
  2214. // - 'RTP': RTP datachannel support.
  2215. webrtcDetectedDCSupport = null;
  2216. // Set the settings for creating DataChannels, MediaStream for
  2217. // Cross-browser compability.
  2218. // - This is only for SCTP based support browsers.
  2219. // the 'urls' attribute.
  2220. checkMediaDataChannelSettings =
  2221. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2222. if (typeof callback !== 'function') {
  2223. return;
  2224. }
  2225. var beOfferer = true;
  2226. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2227. // Nightly version does not require MozDontOfferDataChannel for interop
  2228. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2229. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2230. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2231. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2232. // Resends an updated version of constraints for MozDataChannel to work
  2233. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2234. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2235. try {
  2236. delete constraints.mandatory.MozDontOfferDataChannel;
  2237. } catch (error) {
  2238. console.error('Failed deleting MozDontOfferDataChannel');
  2239. console.error(error);
  2240. }
  2241. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2242. constraints.mandatory.MozDontOfferDataChannel = true;
  2243. }
  2244. if (!isLocalFirefox) {
  2245. // temporary measure to remove Moz* constraints in non Firefox browsers
  2246. for (var prop in constraints.mandatory) {
  2247. if (constraints.mandatory.hasOwnProperty(prop)) {
  2248. if (prop.indexOf('Moz') !== -1) {
  2249. delete constraints.mandatory[prop];
  2250. }
  2251. }
  2252. }
  2253. }
  2254. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2255. // interopability of the media stream
  2256. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2257. beOfferer = false;
  2258. }
  2259. callback(beOfferer, constraints);
  2260. };
  2261. // Handles the differences for all browsers ice connection state output.
  2262. // - Tested outcomes are:
  2263. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2264. // - Chrome (answerer) : 'checking' > 'connected'
  2265. // - Firefox (offerer) : 'checking' > 'connected'
  2266. // - Firefox (answerer): 'checking' > 'connected'
  2267. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2268. if (typeof callback !== 'function') {
  2269. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2270. return;
  2271. }
  2272. peerId = (peerId) ? peerId : 'peer';
  2273. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2274. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2275. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2276. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2277. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2278. }
  2279. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2280. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2281. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2282. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2283. setTimeout(function () {
  2284. AdapterJS._iceConnectionFiredStates[peerId]
  2285. .push(AdapterJS._iceConnectionStates.done);
  2286. callback(AdapterJS._iceConnectionStates.done);
  2287. }, 1000);
  2288. }
  2289. callback(iceConnectionState);
  2290. }
  2291. return;
  2292. };
  2293. // Firefox:
  2294. // - Creates iceServer from the url for Firefox.
  2295. // - Create iceServer with stun url.
  2296. // - Create iceServer with turn url.
  2297. // - Ignore the transport parameter from TURN url for FF version <=27.
  2298. // - Return null for createIceServer if transport=tcp.
  2299. // - FF 27 and above supports transport parameters in TURN url,
  2300. // - So passing in the full url to create iceServer.
  2301. // Chrome:
  2302. // - Creates iceServer from the url for Chrome M33 and earlier.
  2303. // - Create iceServer with stun url.
  2304. // - Chrome M28 & above uses below TURN format.
  2305. // Plugin:
  2306. // - Creates Ice Server for Plugin Browsers
  2307. // - If Stun - Create iceServer with stun url.
  2308. // - Else - Create iceServer with turn url
  2309. // - This is a WebRTC Function
  2310. createIceServer = null;
  2311. // Firefox:
  2312. // - Creates IceServers for Firefox
  2313. // - Use .url for FireFox.
  2314. // - Multiple Urls support
  2315. // Chrome:
  2316. // - Creates iceServers from the urls for Chrome M34 and above.
  2317. // - .urls is supported since Chrome M34.
  2318. // - Multiple Urls support
  2319. // Plugin:
  2320. // - Creates Ice Servers for Plugin Browsers
  2321. // - Multiple Urls support
  2322. // - This is a WebRTC Function
  2323. createIceServers = null;
  2324. //------------------------------------------------------------
  2325. //The RTCPeerConnection object.
  2326. RTCPeerConnection = null;
  2327. // Creates RTCSessionDescription object for Plugin Browsers
  2328. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2329. RTCSessionDescription : null;
  2330. // Creates RTCIceCandidate object for Plugin Browsers
  2331. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2332. RTCIceCandidate : null;
  2333. // Get UserMedia (only difference is the prefix).
  2334. // Code from Adam Barth.
  2335. getUserMedia = null;
  2336. // Attach a media stream to an element.
  2337. attachMediaStream = null;
  2338. // Re-attach a media stream to an element.
  2339. reattachMediaStream = null;
  2340. // Detected browser agent name. Types are:
  2341. // - 'firefox': Firefox browser.
  2342. // - 'chrome': Chrome browser.
  2343. // - 'opera': Opera browser.
  2344. // - 'safari': Safari browser.
  2345. // - 'IE' - Internet Explorer browser.
  2346. webrtcDetectedBrowser = null;
  2347. // Detected browser version.
  2348. webrtcDetectedVersion = null;
  2349. // Check for browser types and react accordingly
  2350. if (navigator.mozGetUserMedia) {
  2351. webrtcDetectedBrowser = 'firefox';
  2352. webrtcDetectedVersion = parseInt(navigator
  2353. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2354. webrtcDetectedType = 'moz';
  2355. webrtcDetectedDCSupport = 'SCTP';
  2356. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2357. AdapterJS.maybeFixConfiguration(pcConfig);
  2358. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2359. };
  2360. // The RTCSessionDescription object.
  2361. RTCSessionDescription = mozRTCSessionDescription;
  2362. window.RTCSessionDescription = RTCSessionDescription;
  2363. // The RTCIceCandidate object.
  2364. RTCIceCandidate = mozRTCIceCandidate;
  2365. window.RTCIceCandidate = RTCIceCandidate;
  2366. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2367. navigator.getUserMedia = window.getUserMedia;
  2368. // Shim for MediaStreamTrack.getSources.
  2369. MediaStreamTrack.getSources = function(successCb) {
  2370. setTimeout(function() {
  2371. var infos = [
  2372. { kind: 'audio', id: 'default', label:'', facing:'' },
  2373. { kind: 'video', id: 'default', label:'', facing:'' }
  2374. ];
  2375. successCb(infos);
  2376. }, 0);
  2377. };
  2378. createIceServer = function (url, username, password) {
  2379. var iceServer = null;
  2380. var url_parts = url.split(':');
  2381. if (url_parts[0].indexOf('stun') === 0) {
  2382. iceServer = { url : url };
  2383. } else if (url_parts[0].indexOf('turn') === 0) {
  2384. if (webrtcDetectedVersion < 27) {
  2385. var turn_url_parts = url.split('?');
  2386. if (turn_url_parts.length === 1 ||
  2387. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2388. iceServer = {
  2389. url : turn_url_parts[0],
  2390. credential : password,
  2391. username : username
  2392. };
  2393. }
  2394. } else {
  2395. iceServer = {
  2396. url : url,
  2397. credential : password,
  2398. username : username
  2399. };
  2400. }
  2401. }
  2402. return iceServer;
  2403. };
  2404. createIceServers = function (urls, username, password) {
  2405. var iceServers = [];
  2406. for (i = 0; i < urls.length; i++) {
  2407. var iceServer = createIceServer(urls[i], username, password);
  2408. if (iceServer !== null) {
  2409. iceServers.push(iceServer);
  2410. }
  2411. }
  2412. return iceServers;
  2413. };
  2414. attachMediaStream = function (element, stream) {
  2415. element.mozSrcObject = stream;
  2416. if (stream !== null)
  2417. element.play();
  2418. return element;
  2419. };
  2420. reattachMediaStream = function (to, from) {
  2421. to.mozSrcObject = from.mozSrcObject;
  2422. to.play();
  2423. return to;
  2424. };
  2425. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2426. if (!callback) {
  2427. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2428. ': 1 argument required, but only 0 present.');
  2429. }
  2430. return callback([]);
  2431. };
  2432. // Fake get{Video,Audio}Tracks
  2433. if (!MediaStream.prototype.getVideoTracks) {
  2434. MediaStream.prototype.getVideoTracks = function () {
  2435. return [];
  2436. };
  2437. }
  2438. if (!MediaStream.prototype.getAudioTracks) {
  2439. MediaStream.prototype.getAudioTracks = function () {
  2440. return [];
  2441. };
  2442. }
  2443. AdapterJS.maybeThroughWebRTCReady();
  2444. } else if (navigator.webkitGetUserMedia) {
  2445. webrtcDetectedBrowser = 'chrome';
  2446. webrtcDetectedType = 'webkit';
  2447. webrtcDetectedVersion = parseInt(navigator
  2448. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2449. // check if browser is opera 20+
  2450. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2451. if (checkIfOpera !== null) {
  2452. webrtcDetectedBrowser = 'opera';
  2453. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2454. }
  2455. // check browser datachannel support
  2456. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2457. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2458. webrtcDetectedDCSupport = 'SCTP';
  2459. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2460. webrtcDetectedVersion > 24) {
  2461. webrtcDetectedDCSupport = 'RTP';
  2462. } else {
  2463. webrtcDetectedDCSupport = '';
  2464. }
  2465. createIceServer = function (url, username, password) {
  2466. var iceServer = null;
  2467. var url_parts = url.split(':');
  2468. if (url_parts[0].indexOf('stun') === 0) {
  2469. iceServer = { 'url' : url };
  2470. } else if (url_parts[0].indexOf('turn') === 0) {
  2471. iceServer = {
  2472. 'url' : url,
  2473. 'credential' : password,
  2474. 'username' : username
  2475. };
  2476. }
  2477. return iceServer;
  2478. };
  2479. createIceServers = function (urls, username, password) {
  2480. var iceServers = [];
  2481. if (webrtcDetectedVersion >= 34) {
  2482. iceServers = {
  2483. 'urls' : urls,
  2484. 'credential' : password,
  2485. 'username' : username
  2486. };
  2487. } else {
  2488. for (i = 0; i < urls.length; i++) {
  2489. var iceServer = createIceServer(urls[i], username, password);
  2490. if (iceServer !== null) {
  2491. iceServers.push(iceServer);
  2492. }
  2493. }
  2494. }
  2495. return iceServers;
  2496. };
  2497. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2498. if (webrtcDetectedVersion < 34) {
  2499. AdapterJS.maybeFixConfiguration(pcConfig);
  2500. }
  2501. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2502. };
  2503. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2504. navigator.getUserMedia = window.getUserMedia;
  2505. attachMediaStream = function (element, stream) {
  2506. if (typeof element.srcObject !== 'undefined') {
  2507. element.srcObject = stream;
  2508. } else if (typeof element.mozSrcObject !== 'undefined') {
  2509. element.mozSrcObject = stream;
  2510. } else if (typeof element.src !== 'undefined') {
  2511. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2512. } else {
  2513. console.log('Error attaching stream to element.');
  2514. }
  2515. return element;
  2516. };
  2517. reattachMediaStream = function (to, from) {
  2518. to.src = from.src;
  2519. return to;
  2520. };
  2521. AdapterJS.maybeThroughWebRTCReady();
  2522. } else { // TRY TO USE PLUGIN
  2523. // IE 9 is not offering an implementation of console.log until you open a console
  2524. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2525. /* jshint -W020 */
  2526. console = {} || console;
  2527. // Implemented based on console specs from MDN
  2528. // You may override these functions
  2529. console.log = function (arg) {};
  2530. console.info = function (arg) {};
  2531. console.error = function (arg) {};
  2532. console.dir = function (arg) {};
  2533. console.exception = function (arg) {};
  2534. console.trace = function (arg) {};
  2535. console.warn = function (arg) {};
  2536. console.count = function (arg) {};
  2537. console.debug = function (arg) {};
  2538. console.count = function (arg) {};
  2539. console.time = function (arg) {};
  2540. console.timeEnd = function (arg) {};
  2541. console.group = function (arg) {};
  2542. console.groupCollapsed = function (arg) {};
  2543. console.groupEnd = function (arg) {};
  2544. /* jshint +W020 */
  2545. }
  2546. webrtcDetectedType = 'plugin';
  2547. webrtcDetectedDCSupport = 'plugin';
  2548. AdapterJS.parseWebrtcDetectedBrowser();
  2549. isIE = webrtcDetectedBrowser === 'IE';
  2550. /* jshint -W035 */
  2551. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2552. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2553. /* empty because it needs to prevent the function from running. */
  2554. }
  2555. };
  2556. /* jshint +W035 */
  2557. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2558. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2559. // Call immediately if possible
  2560. // Once the plugin is set, the code will always take this path
  2561. callback();
  2562. } else {
  2563. // otherwise start a 100ms interval
  2564. var checkPluginReadyState = setInterval(function () {
  2565. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2566. clearInterval(checkPluginReadyState);
  2567. callback();
  2568. }
  2569. }, 100);
  2570. }
  2571. };
  2572. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2573. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2574. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2575. });
  2576. };
  2577. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2578. // only inject once the page is ready
  2579. if (document.readyState !== 'complete') {
  2580. return;
  2581. }
  2582. // Prevent multiple injections
  2583. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2584. return;
  2585. }
  2586. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2587. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2588. var frag = document.createDocumentFragment();
  2589. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2590. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2591. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2592. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2593. '<param name="pluginId" value="' +
  2594. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2595. '<param name="windowless" value="false" /> ' +
  2596. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2597. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2598. '" />' +
  2599. // uncomment to be able to use virtual cams
  2600. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2601. '</object>';
  2602. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2603. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2604. }
  2605. document.body.appendChild(frag);
  2606. // Need to re-fetch the plugin
  2607. AdapterJS.WebRTCPlugin.plugin =
  2608. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2609. } else {
  2610. // Load Plugin
  2611. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2612. AdapterJS.WebRTCPlugin.plugin.id =
  2613. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2614. // IE will only start the plugin if it's ACTUALLY visible
  2615. if (isIE) {
  2616. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2617. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2618. } else { // The size of the plugin on Safari should be 0x0px
  2619. // so that the autorisation prompt is at the top
  2620. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2621. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2622. }
  2623. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2624. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2625. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2626. '<param name="pluginId" value="' +
  2627. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2628. '<param name="windowless" value="false" /> ' +
  2629. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2630. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2631. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2632. }
  2633. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2634. };
  2635. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2636. function (comName, plugName, installedCb, notInstalledCb) {
  2637. if (!isIE) {
  2638. var pluginArray = navigator.plugins;
  2639. for (var i = 0; i < pluginArray.length; i++) {
  2640. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2641. installedCb();
  2642. return;
  2643. }
  2644. }
  2645. notInstalledCb();
  2646. } else {
  2647. try {
  2648. var axo = new ActiveXObject(comName + '.' + plugName);
  2649. } catch (e) {
  2650. notInstalledCb();
  2651. return;
  2652. }
  2653. installedCb();
  2654. }
  2655. };
  2656. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2657. if (AdapterJS.WebRTCPlugin.pluginState ===
  2658. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2659. console.error("WebRTC interface has been defined already");
  2660. return;
  2661. }
  2662. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2663. AdapterJS.isDefined = function (variable) {
  2664. return variable !== null && variable !== undefined;
  2665. };
  2666. createIceServer = function (url, username, password) {
  2667. var iceServer = null;
  2668. var url_parts = url.split(':');
  2669. if (url_parts[0].indexOf('stun') === 0) {
  2670. iceServer = {
  2671. 'url' : url,
  2672. 'hasCredentials' : false
  2673. };
  2674. } else if (url_parts[0].indexOf('turn') === 0) {
  2675. iceServer = {
  2676. 'url' : url,
  2677. 'hasCredentials' : true,
  2678. 'credential' : password,
  2679. 'username' : username
  2680. };
  2681. }
  2682. return iceServer;
  2683. };
  2684. createIceServers = function (urls, username, password) {
  2685. var iceServers = [];
  2686. for (var i = 0; i < urls.length; ++i) {
  2687. iceServers.push(createIceServer(urls[i], username, password));
  2688. }
  2689. return iceServers;
  2690. };
  2691. RTCSessionDescription = function (info) {
  2692. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2693. return AdapterJS.WebRTCPlugin.plugin.
  2694. ConstructSessionDescription(info.type, info.sdp);
  2695. };
  2696. RTCPeerConnection = function (servers, constraints) {
  2697. var iceServers = null;
  2698. if (servers) {
  2699. iceServers = servers.iceServers;
  2700. for (var i = 0; i < iceServers.length; i++) {
  2701. if (iceServers[i].urls && !iceServers[i].url) {
  2702. iceServers[i].url = iceServers[i].urls;
  2703. }
  2704. iceServers[i].hasCredentials = AdapterJS.
  2705. isDefined(iceServers[i].username) &&
  2706. AdapterJS.isDefined(iceServers[i].credential);
  2707. }
  2708. }
  2709. var mandatory = (constraints && constraints.mandatory) ?
  2710. constraints.mandatory : null;
  2711. var optional = (constraints && constraints.optional) ?
  2712. constraints.optional : null;
  2713. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2714. return AdapterJS.WebRTCPlugin.plugin.
  2715. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2716. iceServers, mandatory, optional);
  2717. };
  2718. MediaStreamTrack = {};
  2719. MediaStreamTrack.getSources = function (callback) {
  2720. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2721. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2722. });
  2723. };
  2724. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2725. constraints.audio = constraints.audio || false;
  2726. constraints.video = constraints.video || false;
  2727. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2728. AdapterJS.WebRTCPlugin.plugin.
  2729. getUserMedia(constraints, successCallback, failureCallback);
  2730. });
  2731. };
  2732. window.navigator.getUserMedia = window.getUserMedia;
  2733. attachMediaStream = function (element, stream) {
  2734. if (!element || !element.parentNode) {
  2735. return;
  2736. }
  2737. var streamId
  2738. if (stream === null) {
  2739. streamId = '';
  2740. }
  2741. else {
  2742. stream.enableSoundTracks(true);
  2743. streamId = stream.id;
  2744. }
  2745. if (element.nodeName.toLowerCase() !== 'audio') {
  2746. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2747. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2748. var frag = document.createDocumentFragment();
  2749. var temp = document.createElement('div');
  2750. var classHTML = '';
  2751. if (element.className) {
  2752. classHTML = 'class="' + element.className + '" ';
  2753. } else if (element.attributes && element.attributes['class']) {
  2754. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2755. }
  2756. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2757. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2758. '<param name="pluginId" value="' + elementId + '" /> ' +
  2759. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2760. '<param name="windowless" value="true" /> ' +
  2761. '<param name="streamId" value="' + streamId + '" /> ' +
  2762. '</object>';
  2763. while (temp.firstChild) {
  2764. frag.appendChild(temp.firstChild);
  2765. }
  2766. var height = '';
  2767. var width = '';
  2768. if (element.getBoundingClientRect) {
  2769. var rectObject = element.getBoundingClientRect();
  2770. width = rectObject.width + 'px';
  2771. height = rectObject.height + 'px';
  2772. }
  2773. else if (element.width) {
  2774. width = element.width;
  2775. height = element.height;
  2776. } else {
  2777. // TODO: What scenario could bring us here?
  2778. }
  2779. element.parentNode.insertBefore(frag, element);
  2780. frag = document.getElementById(elementId);
  2781. frag.width = width;
  2782. frag.height = height;
  2783. element.parentNode.removeChild(element);
  2784. } else {
  2785. var children = element.children;
  2786. for (var i = 0; i !== children.length; ++i) {
  2787. if (children[i].name === 'streamId') {
  2788. children[i].value = streamId;
  2789. break;
  2790. }
  2791. }
  2792. element.setStreamId(streamId);
  2793. }
  2794. var newElement = document.getElementById(elementId);
  2795. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2796. if (isIE) { // on IE the event needs to be plugged manually
  2797. newElement.attachEvent('onplaying', newElement.onplaying);
  2798. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2799. newElement._TemOnClick = function (id) {
  2800. var arg = {
  2801. srcElement : document.getElementById(id)
  2802. };
  2803. newElement.onclick(arg);
  2804. };
  2805. }
  2806. return newElement;
  2807. } else {
  2808. return element;
  2809. }
  2810. };
  2811. reattachMediaStream = function (to, from) {
  2812. var stream = null;
  2813. var children = from.children;
  2814. for (var i = 0; i !== children.length; ++i) {
  2815. if (children[i].name === 'streamId') {
  2816. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2817. stream = AdapterJS.WebRTCPlugin.plugin
  2818. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2819. break;
  2820. }
  2821. }
  2822. if (stream !== null) {
  2823. return attachMediaStream(to, stream);
  2824. } else {
  2825. console.log('Could not find the stream associated with this element');
  2826. }
  2827. };
  2828. RTCIceCandidate = function (candidate) {
  2829. if (!candidate.sdpMid) {
  2830. candidate.sdpMid = '';
  2831. }
  2832. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2833. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2834. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2835. );
  2836. };
  2837. // inject plugin
  2838. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2839. AdapterJS.WebRTCPlugin.injectPlugin();
  2840. };
  2841. // This function will be called if the plugin is needed (browser different
  2842. // from Chrome or Firefox), but the plugin is not installed.
  2843. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2844. function() {
  2845. AdapterJS.addEvent(document,
  2846. 'readystatechange',
  2847. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2848. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2849. };
  2850. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2851. if (AdapterJS.options.hidePluginInstallPrompt) {
  2852. return;
  2853. }
  2854. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2855. if(downloadLink) { // if download link
  2856. var popupString;
  2857. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2858. popupString = 'This website requires you to install the ' +
  2859. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2860. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2861. ' WebRTC Plugin</a>' +
  2862. ' to work on this browser.';
  2863. } else { // no portal link, just print a generic explanation
  2864. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2865. }
  2866. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2867. } else { // no download link, just print a generic explanation
  2868. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2869. }
  2870. };
  2871. // Try to detect the plugin and act accordingly
  2872. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2873. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2874. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2875. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2876. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2877. }
  2878. (function () {
  2879. 'use strict';
  2880. var baseGetUserMedia = null;
  2881. AdapterJS.TEXT.EXTENSION = {
  2882. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2883. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2884. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2885. BUTTON_FF: 'Install Now',
  2886. BUTTON_CHROME: 'Go to Chrome Web Store'
  2887. };
  2888. var clone = function(obj) {
  2889. if (null == obj || "object" != typeof obj) return obj;
  2890. var copy = obj.constructor();
  2891. for (var attr in obj) {
  2892. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2893. }
  2894. return copy;
  2895. };
  2896. if (window.navigator.mozGetUserMedia) {
  2897. baseGetUserMedia = window.navigator.getUserMedia;
  2898. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2899. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2900. // intercepting screensharing requests
  2901. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2902. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2903. }
  2904. var updatedConstraints = clone(constraints);
  2905. //constraints.video.mediaSource = constraints.video.mediaSource;
  2906. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2907. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2908. // strange but this works anyway
  2909. var checkIfReady = setInterval(function () {
  2910. if (document.readyState === 'complete') {
  2911. clearInterval(checkIfReady);
  2912. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2913. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2914. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2915. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2916. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2917. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2918. } else {
  2919. failureCb(error);
  2920. }
  2921. });
  2922. }
  2923. }, 1);
  2924. } else { // regular GetUserMediaRequest
  2925. baseGetUserMedia(constraints, successCb, failureCb);
  2926. }
  2927. };
  2928. getUserMedia = navigator.getUserMedia;
  2929. } else if (window.navigator.webkitGetUserMedia) {
  2930. baseGetUserMedia = window.navigator.getUserMedia;
  2931. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2932. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2933. if (window.webrtcDetectedBrowser !== 'chrome') {
  2934. throw new Error('Current browser does not support screensharing');
  2935. }
  2936. // would be fine since no methods
  2937. var updatedConstraints = clone(constraints);
  2938. var chromeCallback = function(error, sourceId) {
  2939. if(!error) {
  2940. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2941. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2942. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2943. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2944. if (sourceId) {
  2945. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2946. }
  2947. delete updatedConstraints.video.mediaSource;
  2948. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2949. } else {
  2950. if (error === 'permission-denied') {
  2951. throw new Error('Permission denied for screen retrieval');
  2952. } else {
  2953. throw new Error('Failed retrieving selected screen');
  2954. }
  2955. }
  2956. };
  2957. var onIFrameCallback = function (event) {
  2958. if (!event.data) {
  2959. return;
  2960. }
  2961. if (event.data.chromeMediaSourceId) {
  2962. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2963. chromeCallback('permission-denied');
  2964. } else {
  2965. chromeCallback(null, event.data.chromeMediaSourceId);
  2966. }
  2967. }
  2968. if (event.data.chromeExtensionStatus) {
  2969. if (event.data.chromeExtensionStatus === 'not-installed') {
  2970. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2971. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2972. event.data.data, true, true);
  2973. } else {
  2974. chromeCallback(event.data.chromeExtensionStatus, null);
  2975. }
  2976. }
  2977. // this event listener is no more needed
  2978. window.removeEventListener('message', onIFrameCallback);
  2979. };
  2980. window.addEventListener('message', onIFrameCallback);
  2981. postFrameMessage({
  2982. captureSourceId: true
  2983. });
  2984. } else {
  2985. baseGetUserMedia(constraints, successCb, failureCb);
  2986. }
  2987. };
  2988. getUserMedia = navigator.getUserMedia;
  2989. } else {
  2990. baseGetUserMedia = window.navigator.getUserMedia;
  2991. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2992. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2993. // would be fine since no methods
  2994. var updatedConstraints = clone(constraints);
  2995. // wait for plugin to be ready
  2996. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2997. // check if screensharing feature is available
  2998. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2999. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3000. // set the constraints
  3001. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  3002. updatedConstraints.video.optional.push({
  3003. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  3004. });
  3005. delete updatedConstraints.video.mediaSource;
  3006. } else {
  3007. throw new Error('Your WebRTC plugin does not support screensharing');
  3008. }
  3009. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  3010. });
  3011. } else {
  3012. baseGetUserMedia(constraints, successCb, failureCb);
  3013. }
  3014. };
  3015. getUserMedia = window.navigator.getUserMedia;
  3016. }
  3017. if (window.webrtcDetectedBrowser === 'chrome') {
  3018. var iframe = document.createElement('iframe');
  3019. iframe.onload = function() {
  3020. iframe.isLoaded = true;
  3021. };
  3022. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  3023. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  3024. iframe.style.display = 'none';
  3025. (document.body || document.documentElement).appendChild(iframe);
  3026. var postFrameMessage = function (object) {
  3027. object = object || {};
  3028. if (!iframe.isLoaded) {
  3029. setTimeout(function () {
  3030. iframe.contentWindow.postMessage(object, '*');
  3031. }, 100);
  3032. return;
  3033. }
  3034. iframe.contentWindow.postMessage(object, '*');
  3035. };
  3036. }
  3037. })();
  3038. },{}],17:[function(require,module,exports){
  3039. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  3040. getUserMediaWithConstraints */
  3041. /**
  3042. * Indicates that desktop stream is currently in use(for toggle purpose).
  3043. * @type {boolean}
  3044. */
  3045. var isUsingScreenStream = false;
  3046. /**
  3047. * Indicates that switch stream operation is in progress and prevent from
  3048. * triggering new events.
  3049. * @type {boolean}
  3050. */
  3051. var switchInProgress = false;
  3052. /**
  3053. * Method used to get screen sharing stream.
  3054. *
  3055. * @type {function (stream_callback, failure_callback}
  3056. */
  3057. var obtainDesktopStream = null;
  3058. /**
  3059. * Indicates whether desktop sharing extension is installed.
  3060. * @type {boolean}
  3061. */
  3062. var extInstalled = false;
  3063. /**
  3064. * Indicates whether update of desktop sharing extension is required.
  3065. * @type {boolean}
  3066. */
  3067. var extUpdateRequired = false;
  3068. var AdapterJS = require("../RTC/adapter.screenshare");
  3069. var EventEmitter = require("events");
  3070. var eventEmitter = new EventEmitter();
  3071. var DesktopSharingEventTypes
  3072. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3073. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3074. var RTCEvents = require("../../service/RTC/RTCEvents");
  3075. /**
  3076. * Method obtains desktop stream from WebRTC 'screen' source.
  3077. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  3078. */
  3079. function obtainWebRTCScreen(streamCallback, failCallback) {
  3080. APP.RTC.getUserMediaWithConstraints(
  3081. ['screen'],
  3082. streamCallback,
  3083. failCallback
  3084. );
  3085. }
  3086. /**
  3087. * Constructs inline install URL for Chrome desktop streaming extension.
  3088. * The 'chromeExtensionId' must be defined in config.js.
  3089. * @returns {string}
  3090. */
  3091. function getWebStoreInstallUrl()
  3092. {
  3093. return "https://chrome.google.com/webstore/detail/" +
  3094. config.chromeExtensionId;
  3095. }
  3096. /**
  3097. * Checks whether extension update is required.
  3098. * @param minVersion minimal required version
  3099. * @param extVersion current extension version
  3100. * @returns {boolean}
  3101. */
  3102. function isUpdateRequired(minVersion, extVersion)
  3103. {
  3104. try
  3105. {
  3106. var s1 = minVersion.split('.');
  3107. var s2 = extVersion.split('.');
  3108. var len = Math.max(s1.length, s2.length);
  3109. for (var i = 0; i < len; i++)
  3110. {
  3111. var n1 = 0,
  3112. n2 = 0;
  3113. if (i < s1.length)
  3114. n1 = parseInt(s1[i]);
  3115. if (i < s2.length)
  3116. n2 = parseInt(s2[i]);
  3117. if (isNaN(n1) || isNaN(n2))
  3118. {
  3119. return true;
  3120. }
  3121. else if (n1 !== n2)
  3122. {
  3123. return n1 > n2;
  3124. }
  3125. }
  3126. // will happen if boths version has identical numbers in
  3127. // their components (even if one of them is longer, has more components)
  3128. return false;
  3129. }
  3130. catch (e)
  3131. {
  3132. console.error("Failed to parse extension version", e);
  3133. APP.UI.messageHandler.showError("dialog.error",
  3134. "dialog.detectext");
  3135. return true;
  3136. }
  3137. }
  3138. function checkChromeExtInstalled(callback) {
  3139. if (!chrome.runtime) {
  3140. // No API, so no extension for sure
  3141. callback(false, false);
  3142. return;
  3143. }
  3144. chrome.runtime.sendMessage(
  3145. config.chromeExtensionId,
  3146. { getVersion: true },
  3147. function (response) {
  3148. if (!response || !response.version) {
  3149. // Communication failure - assume that no endpoint exists
  3150. console.warn(
  3151. "Extension not installed?: ", chrome.runtime.lastError);
  3152. callback(false, false);
  3153. return;
  3154. }
  3155. // Check installed extension version
  3156. var extVersion = response.version;
  3157. console.log('Extension version is: ' + extVersion);
  3158. var updateRequired
  3159. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  3160. callback(!updateRequired, updateRequired);
  3161. }
  3162. );
  3163. }
  3164. function doGetStreamFromExtension(streamCallback, failCallback) {
  3165. // Sends 'getStream' msg to the extension.
  3166. // Extension id must be defined in the config.
  3167. chrome.runtime.sendMessage(
  3168. config.chromeExtensionId,
  3169. { getStream: true, sources: config.desktopSharingSources },
  3170. function (response) {
  3171. if (!response) {
  3172. failCallback(chrome.runtime.lastError);
  3173. return;
  3174. }
  3175. console.log("Response from extension: " + response);
  3176. if (response.streamId) {
  3177. APP.RTC.getUserMediaWithConstraints(
  3178. ['desktop'],
  3179. function (stream) {
  3180. streamCallback(stream);
  3181. },
  3182. failCallback,
  3183. null, null, null,
  3184. response.streamId);
  3185. } else {
  3186. failCallback("Extension failed to get the stream");
  3187. }
  3188. }
  3189. );
  3190. }
  3191. /**
  3192. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  3193. * stream for returned stream token.
  3194. */
  3195. function obtainScreenFromExtension(streamCallback, failCallback) {
  3196. if (extInstalled) {
  3197. doGetStreamFromExtension(streamCallback, failCallback);
  3198. } else {
  3199. if (extUpdateRequired) {
  3200. alert(
  3201. 'Jitsi Desktop Streamer requires update. ' +
  3202. 'Changes will take effect after next Chrome restart.');
  3203. }
  3204. chrome.webstore.install(
  3205. getWebStoreInstallUrl(),
  3206. function (arg) {
  3207. console.log("Extension installed successfully", arg);
  3208. extInstalled = true;
  3209. // We need to give a moment for the endpoint to become available
  3210. window.setTimeout(function () {
  3211. doGetStreamFromExtension(streamCallback, failCallback);
  3212. }, 500);
  3213. },
  3214. function (arg) {
  3215. console.log("Failed to install the extension", arg);
  3216. failCallback(arg);
  3217. APP.UI.messageHandler.showError("dialog.error",
  3218. "dialog.failtoinstall");
  3219. }
  3220. );
  3221. }
  3222. }
  3223. /**
  3224. * Call this method to toggle desktop sharing feature.
  3225. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  3226. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  3227. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  3228. * enabled), pass any other string or nothing in order to disable this
  3229. * feature completely.
  3230. */
  3231. function setDesktopSharing(method) {
  3232. obtainDesktopStream = null;
  3233. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  3234. // care about 'method' parameter
  3235. if (RTCBrowserType.isTemasysPluginUsed()) {
  3236. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3237. console.info("Screensharing not supported by this plugin version");
  3238. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3239. console.info(
  3240. "Screensharing not available with Temasys plugin on this site");
  3241. } else {
  3242. obtainDesktopStream = obtainWebRTCScreen;
  3243. console.info("Using Temasys plugin for desktop sharing");
  3244. }
  3245. } else if (RTCBrowserType.isChrome()) {
  3246. if (method == "ext") {
  3247. if (RTCBrowserType.getChromeVersion() >= 34) {
  3248. obtainDesktopStream = obtainScreenFromExtension;
  3249. console.info("Using Chrome extension for desktop sharing");
  3250. initChromeExtension();
  3251. } else {
  3252. console.info("Chrome extension not supported until ver 34");
  3253. }
  3254. } else if (method == "webrtc") {
  3255. obtainDesktopStream = obtainWebRTCScreen;
  3256. console.info("Using Chrome WebRTC for desktop sharing");
  3257. }
  3258. }
  3259. if (!obtainDesktopStream) {
  3260. console.info("Desktop sharing disabled");
  3261. }
  3262. }
  3263. /**
  3264. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3265. * config.js to support inline installs. Host site must be selected as main
  3266. * website of published extension.
  3267. */
  3268. function initInlineInstalls()
  3269. {
  3270. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  3271. }
  3272. function initChromeExtension() {
  3273. // Initialize Chrome extension inline installs
  3274. initInlineInstalls();
  3275. // Check if extension is installed
  3276. checkChromeExtInstalled(function (installed, updateRequired) {
  3277. extInstalled = installed;
  3278. extUpdateRequired = updateRequired;
  3279. console.info(
  3280. "Chrome extension installed: " + extInstalled +
  3281. " updateRequired: " + extUpdateRequired);
  3282. });
  3283. }
  3284. function getVideoStreamFailed(error) {
  3285. console.error("Failed to obtain the stream to switch to", error);
  3286. switchInProgress = false;
  3287. isUsingScreenStream = false;
  3288. newStreamCreated(null);
  3289. }
  3290. function getDesktopStreamFailed(error) {
  3291. console.error("Failed to obtain the stream to switch to", error);
  3292. switchInProgress = false;
  3293. }
  3294. function streamSwitchDone() {
  3295. switchInProgress = false;
  3296. eventEmitter.emit(
  3297. DesktopSharingEventTypes.SWITCHING_DONE,
  3298. isUsingScreenStream);
  3299. }
  3300. function newStreamCreated(stream)
  3301. {
  3302. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  3303. stream, isUsingScreenStream, streamSwitchDone);
  3304. }
  3305. function onEndedHandler(stream) {
  3306. if (!switchInProgress && isUsingScreenStream) {
  3307. APP.desktopsharing.toggleScreenSharing();
  3308. }
  3309. //FIXME: to be verified
  3310. if (stream.removeEventListener) {
  3311. stream.removeEventListener('ended', onEndedHandler);
  3312. } else {
  3313. stream.detachEvent('ended', onEndedHandler);
  3314. }
  3315. }
  3316. // Called when RTC finishes initialization
  3317. function onWebRtcReady() {
  3318. setDesktopSharing(config.desktopSharing);
  3319. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  3320. }
  3321. module.exports = {
  3322. isUsingScreenStream: function () {
  3323. return isUsingScreenStream;
  3324. },
  3325. /**
  3326. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  3327. * and enabled.
  3328. */
  3329. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  3330. init: function () {
  3331. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  3332. },
  3333. addListener: function (listener, type)
  3334. {
  3335. eventEmitter.on(type, listener);
  3336. },
  3337. removeListener: function (listener, type) {
  3338. eventEmitter.removeListener(type, listener);
  3339. },
  3340. /*
  3341. * Toggles screen sharing.
  3342. */
  3343. toggleScreenSharing: function () {
  3344. if (switchInProgress || !obtainDesktopStream) {
  3345. console.warn("Switch in progress or no method defined");
  3346. return;
  3347. }
  3348. switchInProgress = true;
  3349. if (!isUsingScreenStream)
  3350. {
  3351. // Switch to desktop stream
  3352. obtainDesktopStream(
  3353. function (stream) {
  3354. // We now use screen stream
  3355. isUsingScreenStream = true;
  3356. // Hook 'ended' event to restore camera
  3357. // when screen stream stops
  3358. //FIXME: to be verified
  3359. if (stream.addEventListener) {
  3360. stream.addEventListener('ended', function () {
  3361. onEndedHandler(stream);
  3362. });
  3363. } else {
  3364. stream.attachEvent('ended', function () {
  3365. onEndedHandler(stream);
  3366. });
  3367. }
  3368. newStreamCreated(stream);
  3369. },
  3370. getDesktopStreamFailed);
  3371. } else {
  3372. // Disable screen stream
  3373. APP.RTC.getUserMediaWithConstraints(
  3374. ['video'],
  3375. function (stream) {
  3376. // We are now using camera stream
  3377. isUsingScreenStream = false;
  3378. newStreamCreated(stream);
  3379. },
  3380. getVideoStreamFailed, config.resolution || '360'
  3381. );
  3382. }
  3383. }
  3384. };
  3385. },{"../../service/RTC/RTCEvents":71,"../../service/desktopsharing/DesktopSharingEventTypes":75,"../RTC/RTCBrowserType":14,"../RTC/adapter.screenshare":16,"events":77}],18:[function(require,module,exports){
  3386. function supportsLocalStorage() {
  3387. try {
  3388. return 'localStorage' in window && window.localStorage !== null;
  3389. } catch (e) {
  3390. console.log("localstorage is not supported");
  3391. return false;
  3392. }
  3393. }
  3394. function generateUniqueId() {
  3395. function _p8() {
  3396. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3397. }
  3398. return _p8() + _p8() + _p8() + _p8();
  3399. }
  3400. function Settings(conferenceID) {
  3401. this.email = '';
  3402. this.displayName = '';
  3403. this.userId;
  3404. this.language = null;
  3405. this.confSettings = null;
  3406. this.conferenceID = conferenceID;
  3407. if (supportsLocalStorage()) {
  3408. if(!window.localStorage.getItem(conferenceID))
  3409. this.confSettings = {};
  3410. else
  3411. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3412. if(!this.confSettings.jitsiMeetId) {
  3413. this.confSettings.jitsiMeetId = generateUniqueId();
  3414. console.log("generated id",
  3415. this.confSettings.jitsiMeetId);
  3416. this.save();
  3417. }
  3418. this.userId = this.confSettings.jitsiMeetId || '';
  3419. this.email = this.confSettings.email || '';
  3420. this.displayName = this.confSettings.displayname || '';
  3421. this.language = this.confSettings.language;
  3422. } else {
  3423. console.log("local storage is not supported");
  3424. this.userId = generateUniqueId();
  3425. }
  3426. }
  3427. Settings.prototype.save = function () {
  3428. if(!supportsLocalStorage())
  3429. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3430. }
  3431. Settings.prototype.setDisplayName = function (newDisplayName) {
  3432. this.displayName = newDisplayName;
  3433. if(this.confSettings != null)
  3434. this.confSettings.displayname = displayName;
  3435. this.save();
  3436. return this.displayName;
  3437. },
  3438. Settings.prototype.setEmail = function (newEmail) {
  3439. this.email = newEmail;
  3440. if(this.confSettings != null)
  3441. this.confSettings.email = newEmail;
  3442. this.save();
  3443. return this.email;
  3444. },
  3445. Settings.prototype.getSettings = function () {
  3446. return {
  3447. email: this.email,
  3448. displayName: this.displayName,
  3449. uid: this.userId,
  3450. language: this.language
  3451. };
  3452. },
  3453. Settings.prototype.setLanguage = function (lang) {
  3454. this.language = lang;
  3455. if(this.confSettings != null)
  3456. this.confSettings.language = lang;
  3457. this.save();
  3458. }
  3459. module.exports = Settings;
  3460. },{}],19:[function(require,module,exports){
  3461. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3462. var Moderator = require("./moderator");
  3463. var EventEmitter = require("events");
  3464. var parser = {
  3465. packet2JSON: function (packet, nodes) {
  3466. var self = this;
  3467. $(packet).children().each(function (index) {
  3468. var tagName = $(this).prop("tagName");
  3469. var node = {}
  3470. node["tagName"] = tagName;
  3471. node.attributes = {};
  3472. $($(this)[0].attributes).each(function( index, attr ) {
  3473. node.attributes[ attr.name ] = attr.value;
  3474. } );
  3475. var text = Strophe.getText($(this)[0]);
  3476. if(text)
  3477. node.value = text;
  3478. node.children = [];
  3479. nodes.push(node);
  3480. self.packet2JSON($(this), node.children);
  3481. })
  3482. },
  3483. JSON2packet: function (nodes, packet) {
  3484. for(var i = 0; i < nodes.length; i++)
  3485. {
  3486. var node = nodes[i];
  3487. if(!node || node === null){
  3488. continue;
  3489. }
  3490. packet.c(node.tagName, node.attributes);
  3491. if(node.value)
  3492. packet.t(node.value);
  3493. if(node.children)
  3494. this.JSON2packet(node.children, packet);
  3495. packet.up();
  3496. }
  3497. packet.up();
  3498. }
  3499. };
  3500. function ChatRoom(connection, jid, password, XMPP, options)
  3501. {
  3502. this.eventEmitter = new EventEmitter();
  3503. this.xmpp = XMPP;
  3504. this.connection = connection;
  3505. this.roomjid = Strophe.getBareJidFromJid(jid);
  3506. this.myroomjid = jid;
  3507. this.password = password;
  3508. console.info("Joined MUC as " + this.myroomjid);
  3509. this.members = {};
  3510. this.presMap = {};
  3511. this.presHandlers = {};
  3512. this.joined = false;
  3513. this.role = null;
  3514. this.focusMucJid = null;
  3515. this.bridgeIsDown = false;
  3516. this.options = options || {};
  3517. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  3518. this.initPresenceMap();
  3519. this.session = null;
  3520. var self = this;
  3521. }
  3522. ChatRoom.prototype.initPresenceMap = function () {
  3523. this.presMap['to'] = this.myroomjid;
  3524. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  3525. this.presMap["nodes"] = [];
  3526. this.presMap["nodes"].push( {
  3527. "tagName": "user-agent",
  3528. "value": navigator.userAgent,
  3529. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  3530. });
  3531. };
  3532. ChatRoom.prototype.join = function (password) {
  3533. if(password)
  3534. this.password = password;
  3535. this.moderator.allocateConferenceFocus(function()
  3536. {
  3537. this.sendPresence();
  3538. }.bind(this));
  3539. }
  3540. ChatRoom.prototype.sendPresence = function () {
  3541. if (!this.presMap['to']) {
  3542. // Too early to send presence - not initialized
  3543. return;
  3544. }
  3545. var pres = $pres({to: this.presMap['to'] });
  3546. pres.c('x', {xmlns: this.presMap['xns']});
  3547. if (this.password) {
  3548. pres.c('password').t(this.password).up();
  3549. }
  3550. pres.up();
  3551. // Send XEP-0115 'c' stanza that contains our capabilities info
  3552. if (this.connection.caps) {
  3553. this.connection.caps.node = this.xmpp.options.clientNode;
  3554. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  3555. }
  3556. parser.JSON2packet(this.presMap.nodes, pres);
  3557. this.connection.send(pres);
  3558. };
  3559. ChatRoom.prototype.doLeave = function () {
  3560. console.log("do leave", this.myroomjid);
  3561. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  3562. this.presMap.length = 0;
  3563. this.connection.send(pres);
  3564. };
  3565. ChatRoom.prototype.createNonAnonymousRoom = function () {
  3566. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  3567. var getForm = $iq({type: 'get', to: this.roomjid})
  3568. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  3569. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3570. var self = this;
  3571. this.connection.sendIQ(getForm, function (form) {
  3572. if (!$(form).find(
  3573. '>query>x[xmlns="jabber:x:data"]' +
  3574. '>field[var="muc#roomconfig_whois"]').length) {
  3575. console.error('non-anonymous rooms not supported');
  3576. return;
  3577. }
  3578. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  3579. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3580. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3581. formSubmit.c('field', {'var': 'FORM_TYPE'})
  3582. .c('value')
  3583. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3584. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  3585. .c('value').t('anyone').up().up();
  3586. self.connection.sendIQ(formSubmit);
  3587. }, function (error) {
  3588. console.error("Error getting room configuration form");
  3589. });
  3590. };
  3591. ChatRoom.prototype.onPresence = function (pres) {
  3592. var from = pres.getAttribute('from');
  3593. // Parse roles.
  3594. var member = {};
  3595. member.show = $(pres).find('>show').text();
  3596. member.status = $(pres).find('>status').text();
  3597. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  3598. member.affiliation = tmp.attr('affiliation');
  3599. member.role = tmp.attr('role');
  3600. // Focus recognition
  3601. member.jid = tmp.attr('jid');
  3602. member.isFocus = false;
  3603. if (member.jid
  3604. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  3605. member.isFocus = true;
  3606. }
  3607. $(pres).find(">x").remove();
  3608. var nodes = [];
  3609. parser.packet2JSON(pres, nodes);
  3610. for(var i = 0; i < nodes.length; i++)
  3611. {
  3612. var node = nodes[i];
  3613. switch(node.tagName)
  3614. {
  3615. case "nick":
  3616. member.nick = node.value;
  3617. if(!member.isFocus) {
  3618. var displayName = !this.xmpp.options.displayJids
  3619. ? member.nick : Strophe.getResourceFromJid(from);
  3620. if (displayName && displayName.length > 0) {
  3621. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  3622. }
  3623. console.info("Display name: " + displayName, pres);
  3624. }
  3625. break;
  3626. case "userId":
  3627. member.id = node.value;
  3628. break;
  3629. case "email":
  3630. member.email = node.value;
  3631. break;
  3632. case "bridgeIsDown":
  3633. if(!this.bridgeIsDown) {
  3634. this.bridgeIsDown = true;
  3635. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  3636. }
  3637. break;
  3638. default :
  3639. this.processNode(node, from);
  3640. }
  3641. }
  3642. if (from == this.myroomjid) {
  3643. if (member.affiliation == 'owner')
  3644. if (this.role !== member.role) {
  3645. this.role = member.role;
  3646. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  3647. member, this.isModerator());
  3648. }
  3649. if (!this.joined) {
  3650. this.joined = true;
  3651. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  3652. }
  3653. } else if (this.members[from] === undefined) {
  3654. // new participant
  3655. this.members[from] = member;
  3656. console.log('entered', from, member);
  3657. if (member.isFocus) {
  3658. this.focusMucJid = from;
  3659. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  3660. }
  3661. else {
  3662. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  3663. }
  3664. } else {
  3665. // Presence update for existing participant
  3666. // Watch role change:
  3667. if (this.members[from].role != member.role) {
  3668. this.members[from].role = member.role;
  3669. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  3670. member.role, member.nick);
  3671. }
  3672. }
  3673. if(!member.isFocus)
  3674. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  3675. // Trigger status message update
  3676. if (member.status) {
  3677. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  3678. }
  3679. };
  3680. ChatRoom.prototype.processNode = function (node, from) {
  3681. if(this.presHandlers[node.tagName])
  3682. this.presHandlers[node.tagName](node, from);
  3683. };
  3684. ChatRoom.prototype.sendMessage = function (body, nickname) {
  3685. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3686. msg.c('body', body).up();
  3687. if (nickname) {
  3688. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  3689. }
  3690. this.connection.send(msg);
  3691. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  3692. };
  3693. ChatRoom.prototype.setSubject = function (subject) {
  3694. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3695. msg.c('subject', subject);
  3696. this.connection.send(msg);
  3697. console.log("topic changed to " + subject);
  3698. };
  3699. ChatRoom.prototype.onParticipantLeft = function (jid) {
  3700. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  3701. this.moderator.onMucMemberLeft(jid);
  3702. };
  3703. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  3704. // room destroyed ?
  3705. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3706. '>destroy').length) {
  3707. var reason;
  3708. var reasonSelect = $(pres).find(
  3709. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3710. '>destroy>reason');
  3711. if (reasonSelect.length) {
  3712. reason = reasonSelect.text();
  3713. }
  3714. this.xmpp.disposeConference(false);
  3715. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  3716. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  3717. return true;
  3718. }
  3719. // Status code 110 indicates that this notification is "self-presence".
  3720. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  3721. delete this.members[from];
  3722. this.onParticipantLeft(from);
  3723. }
  3724. // If the status code is 110 this means we're leaving and we would like
  3725. // to remove everyone else from our view, so we trigger the event.
  3726. else if (Object.keys(this.members).length > 1) {
  3727. for (var i in this.members) {
  3728. var member = this.members[i];
  3729. delete this.members[i];
  3730. this.onParticipantLeft(member);
  3731. }
  3732. }
  3733. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  3734. if (this.myroomjid === from) {
  3735. this.xmpp.disposeConference(false);
  3736. this.eventEmitter.emit(XMPPEvents.KICKED);
  3737. }
  3738. }
  3739. };
  3740. ChatRoom.prototype.onMessage = function (msg, from) {
  3741. var nick =
  3742. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  3743. .text() ||
  3744. Strophe.getResourceFromJid(from);
  3745. var txt = $(msg).find('>body').text();
  3746. var type = msg.getAttribute("type");
  3747. if (type == "error") {
  3748. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  3749. $(msg).find('>text').text(), txt);
  3750. return true;
  3751. }
  3752. var subject = $(msg).find('>subject');
  3753. if (subject.length) {
  3754. var subjectText = subject.text();
  3755. if (subjectText || subjectText == "") {
  3756. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  3757. console.log("Subject is changed to " + subjectText);
  3758. }
  3759. }
  3760. // xep-0203 delay
  3761. var stamp = $(msg).find('>delay').attr('stamp');
  3762. if (!stamp) {
  3763. // or xep-0091 delay, UTC timestamp
  3764. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  3765. if (stamp) {
  3766. // the format is CCYYMMDDThh:mm:ss
  3767. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  3768. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  3769. }
  3770. }
  3771. if (txt) {
  3772. console.log('chat', nick, txt);
  3773. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  3774. from, nick, txt, this.myroomjid, stamp);
  3775. }
  3776. }
  3777. ChatRoom.prototype.onPresenceError = function (pres, from) {
  3778. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3779. console.log('on password required', from);
  3780. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  3781. } else if ($(pres).find(
  3782. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3783. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  3784. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  3785. // enter the room by replying with 'not-authorized'. This would
  3786. // result in reconnection from authorized domain.
  3787. // We're either missing Jicofo/Prosody config for anonymous
  3788. // domains or something is wrong.
  3789. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  3790. } else {
  3791. console.warn('onPresError ', pres);
  3792. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3793. }
  3794. } else {
  3795. console.warn('onPresError ', pres);
  3796. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3797. }
  3798. };
  3799. ChatRoom.prototype.kick = function (jid) {
  3800. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  3801. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  3802. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  3803. .c('reason').t('You have been kicked.').up().up().up();
  3804. this.connection.sendIQ(
  3805. kickIQ,
  3806. function (result) {
  3807. console.log('Kick participant with jid: ', jid, result);
  3808. },
  3809. function (error) {
  3810. console.log('Kick participant error: ', error);
  3811. });
  3812. };
  3813. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  3814. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  3815. var ob = this;
  3816. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  3817. function (res) {
  3818. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  3819. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3820. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3821. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3822. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  3823. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  3824. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  3825. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  3826. ob.connection.sendIQ(formsubmit,
  3827. onSuccess,
  3828. onError);
  3829. } else {
  3830. onNotSupported();
  3831. }
  3832. }, onError);
  3833. };
  3834. ChatRoom.prototype.addToPresence = function (key, values) {
  3835. values.tagName = key;
  3836. this.presMap["nodes"].push(values);
  3837. };
  3838. ChatRoom.prototype.removeFromPresence = function (key) {
  3839. for(var i = 0; i < this.presMap.nodes.length; i++)
  3840. {
  3841. if(key === this.presMap.nodes[i].tagName)
  3842. this.presMap.nodes.splice(i, 1);
  3843. }
  3844. };
  3845. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  3846. this.presHandlers[name] = handler;
  3847. }
  3848. ChatRoom.prototype.removePresenceListener = function (name) {
  3849. delete this.presHandlers[name];
  3850. }
  3851. ChatRoom.prototype.isModerator = function (jid) {
  3852. return this.role === 'moderator';
  3853. };
  3854. ChatRoom.prototype.getMemberRole = function (peerJid) {
  3855. if (this.members[peerJid]) {
  3856. return this.members[peerJid].role;
  3857. }
  3858. return null;
  3859. };
  3860. ChatRoom.prototype.setJingleSession = function(session){
  3861. this.session = session;
  3862. this.session.room = this;
  3863. };
  3864. ChatRoom.prototype.removeStream = function (stream) {
  3865. if(!this.session)
  3866. return;
  3867. this.session.peerconnection.removeStream(stream)
  3868. }
  3869. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  3870. if(this.session) {
  3871. // FIXME: will block switchInProgress on true value in case of exception
  3872. this.session.switchStreams(stream, oldStream, callback, isAudio);
  3873. } else {
  3874. // We are done immediately
  3875. console.warn("No conference handler or conference not started yet");
  3876. callback();
  3877. }
  3878. };
  3879. ChatRoom.prototype.addStream = function (stream, callback) {
  3880. if(this.session) {
  3881. // FIXME: will block switchInProgress on true value in case of exception
  3882. this.session.addStream(stream, callback);
  3883. } else {
  3884. // We are done immediately
  3885. console.warn("No conference handler or conference not started yet");
  3886. callback();
  3887. }
  3888. }
  3889. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  3890. var self = this;
  3891. var localCallback = function (mute) {
  3892. self.sendVideoInfoPresence(mute);
  3893. if(callback)
  3894. callback(mute)
  3895. };
  3896. if(this.session)
  3897. {
  3898. this.session.setVideoMute(
  3899. mute, localCallback, options);
  3900. }
  3901. else {
  3902. localCallback(mute);
  3903. }
  3904. };
  3905. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  3906. //This will be for remote streams only
  3907. // if (this.forceMuted && !mute) {
  3908. // console.info("Asking focus for unmute");
  3909. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  3910. // // FIXME: wait for result before resetting muted status
  3911. // this.forceMuted = false;
  3912. // }
  3913. return this.sendAudioInfoPresence(mute, callback);;
  3914. };
  3915. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  3916. this.addToPresence("audiomuted",
  3917. {attributes:
  3918. {"audions": "http://jitsi.org/jitmeet/audio"},
  3919. value: mute.toString()});
  3920. }
  3921. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  3922. this.addAudioInfoToPresence(mute);
  3923. if(this.connection) {
  3924. this.sendPresence();
  3925. }
  3926. if(callback)
  3927. callback();
  3928. };
  3929. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  3930. this.addToPresence("videomuted",
  3931. {attributes:
  3932. {"videons": "http://jitsi.org/jitmeet/video"},
  3933. value: mute.toString()});
  3934. }
  3935. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  3936. this.addVideoInfoToPresence(mute);
  3937. if(!this.connection)
  3938. return;
  3939. this.sendPresence();
  3940. };
  3941. ChatRoom.prototype.addListener = function(type, listener) {
  3942. this.eventEmitter.on(type, listener);
  3943. };
  3944. ChatRoom.prototype.removeListener = function (type, listener) {
  3945. this.eventEmitter.removeListener(type, listener);
  3946. };
  3947. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  3948. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  3949. }
  3950. ChatRoom.prototype.addLocalStreams = function (localStreams) {
  3951. this.session.addLocalStreams(localStreams);
  3952. }
  3953. module.exports = ChatRoom;
  3954. },{"../../service/xmpp/XMPPEvents":76,"./moderator":27,"events":77}],20:[function(require,module,exports){
  3955. /*
  3956. * JingleSession provides an API to manage a single Jingle session. We will
  3957. * have different implementations depending on the underlying interface used
  3958. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  3959. */
  3960. function JingleSession(me, sid, connection, service, eventEmitter) {
  3961. /**
  3962. * Our JID.
  3963. */
  3964. this.me = me;
  3965. /**
  3966. * The Jingle session identifier.
  3967. */
  3968. this.sid = sid;
  3969. /**
  3970. * The XMPP connection.
  3971. */
  3972. this.connection = connection;
  3973. /**
  3974. * The XMPP service.
  3975. */
  3976. this.service = service;
  3977. /**
  3978. * The event emitter.
  3979. */
  3980. this.eventEmitter = eventEmitter;
  3981. /**
  3982. * Whether to use dripping or not. Dripping is sending trickle candidates
  3983. * not one-by-one.
  3984. * Note: currently we do not support 'false'.
  3985. */
  3986. this.usedrip = true;
  3987. /**
  3988. * When dripping is used, stores ICE candidates which are to be sent.
  3989. */
  3990. this.drip_container = [];
  3991. // Media constraints. Is this WebRTC only?
  3992. this.media_constraints = null;
  3993. // ICE servers config (RTCConfiguration?).
  3994. this.ice_config = {};
  3995. // The chat room instance associated with the session.
  3996. this.room = null;
  3997. }
  3998. /**
  3999. * Prepares this object to initiate a session.
  4000. * @param peerjid the JID of the remote peer.
  4001. * @param isInitiator whether we will be the Jingle initiator.
  4002. * @param media_constraints
  4003. * @param ice_config
  4004. */
  4005. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  4006. media_constraints, ice_config) {
  4007. this.media_constraints = media_constraints;
  4008. this.ice_config = ice_config;
  4009. if (this.state !== null) {
  4010. console.error('attempt to initiate on session ' + this.sid +
  4011. 'in state ' + this.state);
  4012. return;
  4013. }
  4014. this.state = 'pending';
  4015. this.initiator = isInitiator ? this.me : peerjid;
  4016. this.responder = !isInitiator ? this.me : peerjid;
  4017. this.peerjid = peerjid;
  4018. this.doInitialize();
  4019. };
  4020. /**
  4021. * Finishes initialization.
  4022. */
  4023. JingleSession.prototype.doInitialize = function() {};
  4024. /**
  4025. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  4026. * Note: currently only used on transport-info
  4027. */
  4028. JingleSession.prototype.addIceCandidates = function(contents) {};
  4029. /**
  4030. * Handles an 'add-source' event.
  4031. *
  4032. * @param contents an array of Jingle 'content' elements.
  4033. */
  4034. JingleSession.prototype.addSources = function(contents) {};
  4035. /**
  4036. * Handles a 'remove-source' event.
  4037. *
  4038. * @param contents an array of Jingle 'content' elements.
  4039. */
  4040. JingleSession.prototype.removeSources = function(contents) {};
  4041. /**
  4042. * Terminates this Jingle session (stops sending media and closes the streams?)
  4043. */
  4044. JingleSession.prototype.terminate = function() {};
  4045. /**
  4046. * Sends a Jingle session-terminate message to the peer and terminates the
  4047. * session.
  4048. * @param reason
  4049. * @param text
  4050. */
  4051. JingleSession.prototype.sendTerminate = function(reason, text) {};
  4052. /**
  4053. * Handles an offer from the remote peer (prepares to accept a session).
  4054. * @param jingle the 'jingle' XML element.
  4055. */
  4056. JingleSession.prototype.setOffer = function(jingle) {};
  4057. /**
  4058. * Handles an answer from the remote peer (prepares to accept a session).
  4059. * @param jingle the 'jingle' XML element.
  4060. */
  4061. JingleSession.prototype.setAnswer = function(jingle) {};
  4062. module.exports = JingleSession;
  4063. },{}],21:[function(require,module,exports){
  4064. /* jshint -W117 */
  4065. var JingleSession = require("./JingleSession");
  4066. var TraceablePeerConnection = require("./TraceablePeerConnection");
  4067. var SDPDiffer = require("./SDPDiffer");
  4068. var SDPUtil = require("./SDPUtil");
  4069. var SDP = require("./SDP");
  4070. var async = require("async");
  4071. var transform = require("sdp-transform");
  4072. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  4073. var RTCBrowserType = require("../RTC/RTCBrowserType");
  4074. var SSRCReplacement = require("./LocalSSRCReplacement");
  4075. var RTC = require("../RTC/RTC");
  4076. // Jingle stuff
  4077. function JingleSessionPC(me, sid, connection, service) {
  4078. JingleSession.call(this, me, sid, connection, service);
  4079. this.initiator = null;
  4080. this.responder = null;
  4081. this.peerjid = null;
  4082. this.state = null;
  4083. this.localSDP = null;
  4084. this.remoteSDP = null;
  4085. this.relayedStreams = [];
  4086. this.usetrickle = true;
  4087. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  4088. this.hadstuncandidate = false;
  4089. this.hadturncandidate = false;
  4090. this.lasticecandidate = false;
  4091. this.statsinterval = null;
  4092. this.reason = null;
  4093. this.addssrc = [];
  4094. this.removessrc = [];
  4095. this.pendingop = null;
  4096. this.switchstreams = false;
  4097. this.wait = true;
  4098. this.localStreamsSSRC = null;
  4099. this.ssrcOwners = {};
  4100. this.ssrcVideoTypes = {};
  4101. /**
  4102. * The indicator which determines whether the (local) video has been muted
  4103. * in response to a user command in contrast to an automatic decision made
  4104. * by the application logic.
  4105. */
  4106. this.videoMuteByUser = false;
  4107. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  4108. // We start with the queue paused. We resume it when the signaling state is
  4109. // stable and the ice connection state is connected.
  4110. this.modifySourcesQueue.pause();
  4111. }
  4112. JingleSessionPC.prototype = JingleSession.prototype;
  4113. JingleSessionPC.prototype.constructor = JingleSessionPC;
  4114. JingleSessionPC.prototype.setOffer = function(offer) {
  4115. this.setRemoteDescription(offer, 'offer');
  4116. };
  4117. JingleSessionPC.prototype.setAnswer = function(answer) {
  4118. this.setRemoteDescription(answer, 'answer');
  4119. };
  4120. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  4121. var signalingState = this.peerconnection.signalingState;
  4122. var iceConnectionState = this.peerconnection.iceConnectionState;
  4123. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  4124. this.modifySourcesQueue.resume();
  4125. } else {
  4126. this.modifySourcesQueue.pause();
  4127. }
  4128. };
  4129. JingleSessionPC.prototype.doInitialize = function () {
  4130. var self = this;
  4131. this.hadstuncandidate = false;
  4132. this.hadturncandidate = false;
  4133. this.lasticecandidate = false;
  4134. this.isreconnect = false;
  4135. this.peerconnection = new TraceablePeerConnection(
  4136. this.connection.jingle.ice_config,
  4137. RTC.getPCConstraints(),
  4138. this);
  4139. this.peerconnection.onicecandidate = function (event) {
  4140. self.sendIceCandidate(event.candidate);
  4141. };
  4142. this.peerconnection.onaddstream = function (event) {
  4143. if (event.stream.id !== 'default') {
  4144. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  4145. self.remoteStreamAdded(event);
  4146. } else {
  4147. // This is a recvonly stream. Clients that implement Unified Plan,
  4148. // such as Firefox use recvonly "streams/channels/tracks" for
  4149. // receiving remote stream/tracks, as opposed to Plan B where there
  4150. // are only 3 channels: audio, video and data.
  4151. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  4152. }
  4153. };
  4154. this.peerconnection.onremovestream = function (event) {
  4155. };
  4156. this.peerconnection.onsignalingstatechange = function (event) {
  4157. if (!(self && self.peerconnection)) return;
  4158. self.updateModifySourcesQueue();
  4159. };
  4160. /**
  4161. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  4162. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  4163. * RTCPeerConnection.iceConnectionState changes.
  4164. *
  4165. * @param event the event containing information about the change
  4166. */
  4167. this.peerconnection.oniceconnectionstatechange = function (event) {
  4168. if (!(self && self.peerconnection)) return;
  4169. self.updateModifySourcesQueue();
  4170. switch (self.peerconnection.iceConnectionState) {
  4171. case 'connected':
  4172. // Informs interested parties that the connection has been restored.
  4173. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  4174. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  4175. self.isreconnect = false;
  4176. break;
  4177. case 'disconnected':
  4178. self.isreconnect = true;
  4179. // Informs interested parties that the connection has been interrupted.
  4180. if (self.peerconnection.signalingState === 'stable')
  4181. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  4182. break;
  4183. case 'failed':
  4184. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4185. break;
  4186. }
  4187. onIceConnectionStateChange(self.sid, self);
  4188. };
  4189. this.peerconnection.onnegotiationneeded = function (event) {
  4190. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  4191. };
  4192. this.relayedStreams.forEach(function(stream) {
  4193. self.peerconnection.addStream(stream);
  4194. });
  4195. };
  4196. JingleSessionPC.prototype.addLocalStreams = function (localStreams) {
  4197. var self = this;
  4198. // add any local and relayed stream
  4199. localStreams.forEach(function(stream) {
  4200. self.peerconnection.addStream(stream.getOriginalStream());
  4201. });
  4202. }
  4203. function onIceConnectionStateChange(sid, session) {
  4204. switch (session.peerconnection.iceConnectionState) {
  4205. case 'checking':
  4206. session.timeChecking = (new Date()).getTime();
  4207. session.firstconnect = true;
  4208. break;
  4209. case 'completed': // on caller side
  4210. case 'connected':
  4211. if (session.firstconnect) {
  4212. session.firstconnect = false;
  4213. var metadata = {};
  4214. metadata.setupTime
  4215. = (new Date()).getTime() - session.timeChecking;
  4216. session.peerconnection.getStats(function (res) {
  4217. if(res && res.result) {
  4218. res.result().forEach(function (report) {
  4219. if (report.type == 'googCandidatePair' &&
  4220. report.stat('googActiveConnection') == 'true') {
  4221. metadata.localCandidateType
  4222. = report.stat('googLocalCandidateType');
  4223. metadata.remoteCandidateType
  4224. = report.stat('googRemoteCandidateType');
  4225. // log pair as well so we can get nice pie
  4226. // charts
  4227. metadata.candidatePair
  4228. = report.stat('googLocalCandidateType') +
  4229. ';' +
  4230. report.stat('googRemoteCandidateType');
  4231. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  4232. {
  4233. metadata.ipv6 = true;
  4234. }
  4235. }
  4236. });
  4237. }
  4238. });
  4239. }
  4240. break;
  4241. }
  4242. }
  4243. JingleSessionPC.prototype.accept = function () {
  4244. this.state = 'active';
  4245. var pranswer = this.peerconnection.localDescription;
  4246. if (!pranswer || pranswer.type != 'pranswer') {
  4247. return;
  4248. }
  4249. console.log('going from pranswer to answer');
  4250. if (this.usetrickle) {
  4251. // remove candidates already sent from session-accept
  4252. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  4253. for (var i = 0; i < lines.length; i++) {
  4254. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  4255. }
  4256. }
  4257. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  4258. // FIXME: change any inactive to sendrecv or whatever they were originally
  4259. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  4260. }
  4261. var prsdp = new SDP(pranswer.sdp);
  4262. var accept = $iq({to: this.peerjid,
  4263. type: 'set'})
  4264. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4265. action: 'session-accept',
  4266. initiator: this.initiator,
  4267. responder: this.responder,
  4268. sid: this.sid });
  4269. // FIXME why do we generate session-accept in 3 different places ?
  4270. prsdp.toJingle(
  4271. accept,
  4272. this.initiator == this.me ? 'initiator' : 'responder',
  4273. this.localStreamsSSRC);
  4274. var sdp = this.peerconnection.localDescription.sdp;
  4275. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  4276. // FIXME: change any inactive to sendrecv or whatever they were originally
  4277. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  4278. }
  4279. var self = this;
  4280. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  4281. function () {
  4282. //console.log('setLocalDescription success');
  4283. self.setLocalDescription();
  4284. SSRCReplacement.processSessionInit(accept);
  4285. self.connection.sendIQ(accept,
  4286. function () {
  4287. var ack = {};
  4288. ack.source = 'answer';
  4289. $(document).trigger('ack.jingle', [self.sid, ack]);
  4290. },
  4291. function (stanza) {
  4292. var error = ($(stanza).find('error').length) ? {
  4293. code: $(stanza).find('error').attr('code'),
  4294. reason: $(stanza).find('error :first')[0].tagName
  4295. }:{};
  4296. error.source = 'answer';
  4297. JingleSessionPC.onJingleError(self.sid, error);
  4298. },
  4299. 10000);
  4300. },
  4301. function (e) {
  4302. console.error('setLocalDescription failed', e);
  4303. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4304. }
  4305. );
  4306. };
  4307. JingleSessionPC.prototype.terminate = function (reason) {
  4308. this.state = 'ended';
  4309. this.reason = reason;
  4310. this.peerconnection.close();
  4311. if (this.statsinterval !== null) {
  4312. window.clearInterval(this.statsinterval);
  4313. this.statsinterval = null;
  4314. }
  4315. };
  4316. JingleSessionPC.prototype.active = function () {
  4317. return this.state == 'active';
  4318. };
  4319. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  4320. var self = this;
  4321. if (candidate && !this.lasticecandidate) {
  4322. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  4323. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  4324. if (!(ice && jcand)) {
  4325. console.error('failed to get ice && jcand');
  4326. return;
  4327. }
  4328. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4329. if (jcand.type === 'srflx') {
  4330. this.hadstuncandidate = true;
  4331. } else if (jcand.type === 'relay') {
  4332. this.hadturncandidate = true;
  4333. }
  4334. if (this.usetrickle) {
  4335. if (this.usedrip) {
  4336. if (this.drip_container.length === 0) {
  4337. // start 20ms callout
  4338. window.setTimeout(function () {
  4339. if (self.drip_container.length === 0) return;
  4340. self.sendIceCandidates(self.drip_container);
  4341. self.drip_container = [];
  4342. }, 20);
  4343. }
  4344. this.drip_container.push(candidate);
  4345. return;
  4346. } else {
  4347. self.sendIceCandidate([candidate]);
  4348. }
  4349. }
  4350. } else {
  4351. //console.log('sendIceCandidate: last candidate.');
  4352. if (!this.usetrickle) {
  4353. //console.log('should send full offer now...');
  4354. //FIXME why do we generate session-accept in 3 different places ?
  4355. var init = $iq({to: this.peerjid,
  4356. type: 'set'})
  4357. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4358. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  4359. initiator: this.initiator,
  4360. sid: this.sid});
  4361. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  4362. var sendJingle = function (ssrc) {
  4363. if(!ssrc)
  4364. ssrc = {};
  4365. self.localSDP.toJingle(
  4366. init,
  4367. self.initiator == self.me ? 'initiator' : 'responder',
  4368. ssrc);
  4369. SSRCReplacement.processSessionInit(init);
  4370. self.connection.sendIQ(init,
  4371. function () {
  4372. //console.log('session initiate ack');
  4373. var ack = {};
  4374. ack.source = 'offer';
  4375. $(document).trigger('ack.jingle', [self.sid, ack]);
  4376. },
  4377. function (stanza) {
  4378. self.state = 'error';
  4379. self.peerconnection.close();
  4380. var error = ($(stanza).find('error').length) ? {
  4381. code: $(stanza).find('error').attr('code'),
  4382. reason: $(stanza).find('error :first')[0].tagName,
  4383. }:{};
  4384. error.source = 'offer';
  4385. JingleSessionPC.onJingleError(self.sid, error);
  4386. },
  4387. 10000);
  4388. };
  4389. sendJingle();
  4390. }
  4391. this.lasticecandidate = true;
  4392. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  4393. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  4394. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  4395. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  4396. }
  4397. }
  4398. };
  4399. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  4400. console.log('sendIceCandidates', candidates);
  4401. var cand = $iq({to: this.peerjid, type: 'set'})
  4402. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4403. action: 'transport-info',
  4404. initiator: this.initiator,
  4405. sid: this.sid});
  4406. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  4407. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  4408. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  4409. if (cands.length > 0) {
  4410. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  4411. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4412. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  4413. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  4414. }).c('transport', ice);
  4415. for (var i = 0; i < cands.length; i++) {
  4416. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  4417. }
  4418. // add fingerprint
  4419. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  4420. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  4421. tmp.required = true;
  4422. cand.c(
  4423. 'fingerprint',
  4424. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  4425. .t(tmp.fingerprint);
  4426. delete tmp.fingerprint;
  4427. cand.attrs(tmp);
  4428. cand.up();
  4429. }
  4430. cand.up(); // transport
  4431. cand.up(); // content
  4432. }
  4433. }
  4434. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  4435. //console.log('was this the last candidate', this.lasticecandidate);
  4436. this.connection.sendIQ(cand,
  4437. function () {
  4438. var ack = {};
  4439. ack.source = 'transportinfo';
  4440. $(document).trigger('ack.jingle', [this.sid, ack]);
  4441. },
  4442. function (stanza) {
  4443. var error = ($(stanza).find('error').length) ? {
  4444. code: $(stanza).find('error').attr('code'),
  4445. reason: $(stanza).find('error :first')[0].tagName,
  4446. }:{};
  4447. error.source = 'transportinfo';
  4448. JingleSessionPC.onJingleError(this.sid, error);
  4449. },
  4450. 10000);
  4451. };
  4452. JingleSessionPC.prototype.sendOffer = function () {
  4453. //console.log('sendOffer...');
  4454. var self = this;
  4455. this.peerconnection.createOffer(function (sdp) {
  4456. self.createdOffer(sdp);
  4457. },
  4458. function (e) {
  4459. console.error('createOffer failed', e);
  4460. },
  4461. this.media_constraints
  4462. );
  4463. };
  4464. // FIXME createdOffer is never used in jitsi-meet
  4465. JingleSessionPC.prototype.createdOffer = function (sdp) {
  4466. //console.log('createdOffer', sdp);
  4467. var self = this;
  4468. this.localSDP = new SDP(sdp.sdp);
  4469. //this.localSDP.mangle();
  4470. var sendJingle = function () {
  4471. var init = $iq({to: this.peerjid,
  4472. type: 'set'})
  4473. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4474. action: 'session-initiate',
  4475. initiator: this.initiator,
  4476. sid: this.sid});
  4477. self.localSDP.toJingle(
  4478. init,
  4479. this.initiator == this.me ? 'initiator' : 'responder',
  4480. this.localStreamsSSRC);
  4481. SSRCReplacement.processSessionInit(init);
  4482. self.connection.sendIQ(init,
  4483. function () {
  4484. var ack = {};
  4485. ack.source = 'offer';
  4486. $(document).trigger('ack.jingle', [self.sid, ack]);
  4487. },
  4488. function (stanza) {
  4489. self.state = 'error';
  4490. self.peerconnection.close();
  4491. var error = ($(stanza).find('error').length) ? {
  4492. code: $(stanza).find('error').attr('code'),
  4493. reason: $(stanza).find('error :first')[0].tagName,
  4494. }:{};
  4495. error.source = 'offer';
  4496. JingleSessionPC.onJingleError(self.sid, error);
  4497. },
  4498. 10000);
  4499. }
  4500. sdp.sdp = this.localSDP.raw;
  4501. this.peerconnection.setLocalDescription(sdp,
  4502. function () {
  4503. if(self.usetrickle)
  4504. {
  4505. sendJingle();
  4506. }
  4507. self.setLocalDescription();
  4508. //console.log('setLocalDescription success');
  4509. },
  4510. function (e) {
  4511. console.error('setLocalDescription failed', e);
  4512. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4513. }
  4514. );
  4515. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  4516. for (var i = 0; i < cands.length; i++) {
  4517. var cand = SDPUtil.parse_icecandidate(cands[i]);
  4518. if (cand.type == 'srflx') {
  4519. this.hadstuncandidate = true;
  4520. } else if (cand.type == 'relay') {
  4521. this.hadturncandidate = true;
  4522. }
  4523. }
  4524. };
  4525. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  4526. var self = this;
  4527. $(contents).each(function (idx, content) {
  4528. var name = $(content).attr('name');
  4529. var mediaType = this.getAttribute('name');
  4530. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  4531. ssrcs.each(function () {
  4532. var ssrc = this.getAttribute('ssrc');
  4533. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  4534. function () {
  4535. var owner = this.getAttribute('owner');
  4536. self.ssrcOwners[ssrc] = owner;
  4537. }
  4538. );
  4539. });
  4540. });
  4541. };
  4542. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  4543. return this.ssrcOwners[ssrc];
  4544. };
  4545. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  4546. //console.log('setting remote description... ', desctype);
  4547. this.remoteSDP = new SDP('');
  4548. this.remoteSDP.fromJingle(elem);
  4549. this.readSsrcInfo($(elem).find(">content"));
  4550. if (this.peerconnection.remoteDescription !== null) {
  4551. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  4552. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  4553. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  4554. for (var i = 0; i < pranswer.media.length; i++) {
  4555. // make sure we have ice ufrag and pwd
  4556. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  4557. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  4558. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  4559. } else {
  4560. console.warn('no ice ufrag?');
  4561. }
  4562. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  4563. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  4564. } else {
  4565. console.warn('no ice pwd?');
  4566. }
  4567. }
  4568. // copy over candidates
  4569. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  4570. for (var j = 0; j < lines.length; j++) {
  4571. this.remoteSDP.media[i] += lines[j] + '\r\n';
  4572. }
  4573. }
  4574. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  4575. }
  4576. }
  4577. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  4578. this.peerconnection.setRemoteDescription(remotedesc,
  4579. function () {
  4580. //console.log('setRemoteDescription success');
  4581. },
  4582. function (e) {
  4583. console.error('setRemoteDescription error', e);
  4584. JingleSessionPC.onJingleFatalError(self, e);
  4585. }
  4586. );
  4587. };
  4588. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  4589. var self = this;
  4590. if (this.peerconnection.signalingState == 'closed') {
  4591. return;
  4592. }
  4593. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  4594. console.log('trickle ice candidate arriving before session accept...');
  4595. // create a PRANSWER for setRemoteDescription
  4596. if (!this.remoteSDP) {
  4597. var cobbled = 'v=0\r\n' +
  4598. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  4599. 's=-\r\n' +
  4600. 't=0 0\r\n';
  4601. // first, take some things from the local description
  4602. for (var i = 0; i < this.localSDP.media.length; i++) {
  4603. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  4604. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  4605. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  4606. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  4607. }
  4608. cobbled += 'a=inactive\r\n';
  4609. }
  4610. this.remoteSDP = new SDP(cobbled);
  4611. }
  4612. // then add things like ice and dtls from remote candidate
  4613. elem.each(function () {
  4614. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  4615. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4616. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4617. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  4618. var tmp = $(this).find('transport');
  4619. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  4620. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  4621. tmp = $(this).find('transport>fingerprint');
  4622. if (tmp.length) {
  4623. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  4624. } else {
  4625. console.log('no dtls fingerprint (webrtc issue #1718?)');
  4626. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  4627. }
  4628. break;
  4629. }
  4630. }
  4631. }
  4632. });
  4633. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  4634. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  4635. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  4636. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  4637. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  4638. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  4639. }).length == this.remoteSDP.media.length;
  4640. if (iscomplete) {
  4641. console.log('setting pranswer');
  4642. try {
  4643. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  4644. function() {
  4645. },
  4646. function(e) {
  4647. console.log('setRemoteDescription pranswer failed', e.toString());
  4648. });
  4649. } catch (e) {
  4650. console.error('setting pranswer failed', e);
  4651. }
  4652. } else {
  4653. //console.log('not yet setting pranswer');
  4654. }
  4655. }
  4656. // operate on each content element
  4657. elem.each(function () {
  4658. // would love to deactivate this, but firefox still requires it
  4659. var idx = -1;
  4660. var i;
  4661. for (i = 0; i < self.remoteSDP.media.length; i++) {
  4662. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4663. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4664. idx = i;
  4665. break;
  4666. }
  4667. }
  4668. if (idx == -1) { // fall back to localdescription
  4669. for (i = 0; i < self.localSDP.media.length; i++) {
  4670. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4671. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4672. idx = i;
  4673. break;
  4674. }
  4675. }
  4676. }
  4677. var name = $(this).attr('name');
  4678. // TODO: check ice-pwd and ice-ufrag?
  4679. $(this).find('transport>candidate').each(function () {
  4680. var line, candidate;
  4681. line = SDPUtil.candidateFromJingle(this);
  4682. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  4683. sdpMid: name,
  4684. candidate: line});
  4685. try {
  4686. self.peerconnection.addIceCandidate(candidate);
  4687. } catch (e) {
  4688. console.error('addIceCandidate failed', e.toString(), line);
  4689. }
  4690. });
  4691. });
  4692. };
  4693. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  4694. //console.log('createAnswer', provisional);
  4695. var self = this;
  4696. this.peerconnection.createAnswer(
  4697. function (sdp) {
  4698. self.createdAnswer(sdp, provisional);
  4699. },
  4700. function (e) {
  4701. console.error('createAnswer failed', e);
  4702. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4703. },
  4704. this.media_constraints
  4705. );
  4706. };
  4707. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  4708. //console.log('createAnswer callback');
  4709. var self = this;
  4710. this.localSDP = new SDP(sdp.sdp);
  4711. //this.localSDP.mangle();
  4712. this.usepranswer = provisional === true;
  4713. if (this.usetrickle) {
  4714. if (this.usepranswer) {
  4715. sdp.type = 'pranswer';
  4716. for (var i = 0; i < this.localSDP.media.length; i++) {
  4717. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  4718. }
  4719. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  4720. }
  4721. }
  4722. var self = this;
  4723. var sendJingle = function (ssrcs) {
  4724. // FIXME why do we generate session-accept in 3 different places ?
  4725. var accept = $iq({to: self.peerjid,
  4726. type: 'set'})
  4727. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4728. action: 'session-accept',
  4729. initiator: self.initiator,
  4730. responder: self.responder,
  4731. sid: self.sid });
  4732. self.localSDP.toJingle(
  4733. accept,
  4734. self.initiator == self.me ? 'initiator' : 'responder',
  4735. ssrcs);
  4736. SSRCReplacement.processSessionInit(accept);
  4737. self.connection.sendIQ(accept,
  4738. function () {
  4739. var ack = {};
  4740. ack.source = 'answer';
  4741. $(document).trigger('ack.jingle', [self.sid, ack]);
  4742. },
  4743. function (stanza) {
  4744. var error = ($(stanza).find('error').length) ? {
  4745. code: $(stanza).find('error').attr('code'),
  4746. reason: $(stanza).find('error :first')[0].tagName,
  4747. }:{};
  4748. error.source = 'answer';
  4749. JingleSessionPC.onJingleError(self.sid, error);
  4750. },
  4751. 10000);
  4752. }
  4753. sdp.sdp = this.localSDP.raw;
  4754. this.peerconnection.setLocalDescription(sdp,
  4755. function () {
  4756. //console.log('setLocalDescription success');
  4757. if (self.usetrickle && !self.usepranswer) {
  4758. sendJingle();
  4759. }
  4760. self.setLocalDescription();
  4761. },
  4762. function (e) {
  4763. console.error('setLocalDescription failed', e);
  4764. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4765. }
  4766. );
  4767. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  4768. for (var j = 0; j < cands.length; j++) {
  4769. var cand = SDPUtil.parse_icecandidate(cands[j]);
  4770. if (cand.type == 'srflx') {
  4771. this.hadstuncandidate = true;
  4772. } else if (cand.type == 'relay') {
  4773. this.hadturncandidate = true;
  4774. }
  4775. }
  4776. };
  4777. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  4778. var self = this,
  4779. term = $iq({to: this.peerjid,
  4780. type: 'set'})
  4781. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4782. action: 'session-terminate',
  4783. initiator: this.initiator,
  4784. sid: this.sid})
  4785. .c('reason')
  4786. .c(reason || 'success');
  4787. if (text) {
  4788. term.up().c('text').t(text);
  4789. }
  4790. this.connection.sendIQ(term,
  4791. function () {
  4792. self.peerconnection.close();
  4793. self.peerconnection = null;
  4794. self.terminate();
  4795. var ack = {};
  4796. ack.source = 'terminate';
  4797. $(document).trigger('ack.jingle', [self.sid, ack]);
  4798. },
  4799. function (stanza) {
  4800. var error = ($(stanza).find('error').length) ? {
  4801. code: $(stanza).find('error').attr('code'),
  4802. reason: $(stanza).find('error :first')[0].tagName,
  4803. }:{};
  4804. $(document).trigger('ack.jingle', [self.sid, error]);
  4805. },
  4806. 10000);
  4807. if (this.statsinterval !== null) {
  4808. window.clearInterval(this.statsinterval);
  4809. this.statsinterval = null;
  4810. }
  4811. };
  4812. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  4813. var self = this;
  4814. // FIXME: dirty waiting
  4815. if (!this.peerconnection.localDescription)
  4816. {
  4817. console.warn("addSource - localDescription not ready yet")
  4818. setTimeout(function()
  4819. {
  4820. self.addSource(elem, fromJid);
  4821. },
  4822. 200
  4823. );
  4824. return;
  4825. }
  4826. console.log('addssrc', new Date().getTime());
  4827. console.log('ice', this.peerconnection.iceConnectionState);
  4828. this.readSsrcInfo(elem);
  4829. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  4830. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  4831. $(elem).each(function (idx, content) {
  4832. var name = $(content).attr('name');
  4833. var lines = '';
  4834. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  4835. var semantics = this.getAttribute('semantics');
  4836. var ssrcs = $(this).find('>source').map(function () {
  4837. return this.getAttribute('ssrc');
  4838. }).get();
  4839. if (ssrcs.length != 0) {
  4840. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  4841. }
  4842. });
  4843. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  4844. tmp.each(function () {
  4845. var ssrc = $(this).attr('ssrc');
  4846. if(mySdp.containsSSRC(ssrc)){
  4847. /**
  4848. * This happens when multiple participants change their streams at the same time and
  4849. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  4850. * addssrc are scheduled for update IQ. See
  4851. */
  4852. console.warn("Got add stream request for my own ssrc: "+ssrc);
  4853. return;
  4854. }
  4855. if (sdp.containsSSRC(ssrc)) {
  4856. console.warn("Source-add request for existing SSRC: " + ssrc);
  4857. return;
  4858. }
  4859. $(this).find('>parameter').each(function () {
  4860. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  4861. if ($(this).attr('value') && $(this).attr('value').length)
  4862. lines += ':' + $(this).attr('value');
  4863. lines += '\r\n';
  4864. });
  4865. });
  4866. sdp.media.forEach(function(media, idx) {
  4867. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  4868. return;
  4869. sdp.media[idx] += lines;
  4870. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  4871. self.addssrc[idx] += lines;
  4872. });
  4873. sdp.raw = sdp.session + sdp.media.join('');
  4874. });
  4875. this.modifySourcesQueue.push(function() {
  4876. // When a source is added and if this is FF, a new channel is allocated
  4877. // for receiving the added source. We need to diffuse the SSRC of this
  4878. // new recvonly channel to the rest of the peers.
  4879. console.log('modify sources done');
  4880. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  4881. console.log("SDPs", mySdp, newSdp);
  4882. self.notifyMySSRCUpdate(mySdp, newSdp);
  4883. });
  4884. };
  4885. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  4886. var self = this;
  4887. // FIXME: dirty waiting
  4888. if (!this.peerconnection.localDescription)
  4889. {
  4890. console.warn("removeSource - localDescription not ready yet")
  4891. setTimeout(function()
  4892. {
  4893. self.removeSource(elem, fromJid);
  4894. },
  4895. 200
  4896. );
  4897. return;
  4898. }
  4899. console.log('removessrc', new Date().getTime());
  4900. console.log('ice', this.peerconnection.iceConnectionState);
  4901. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  4902. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  4903. $(elem).each(function (idx, content) {
  4904. var name = $(content).attr('name');
  4905. var lines = '';
  4906. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  4907. var semantics = this.getAttribute('semantics');
  4908. var ssrcs = $(this).find('>source').map(function () {
  4909. return this.getAttribute('ssrc');
  4910. }).get();
  4911. if (ssrcs.length != 0) {
  4912. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  4913. }
  4914. });
  4915. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  4916. tmp.each(function () {
  4917. var ssrc = $(this).attr('ssrc');
  4918. // This should never happen, but can be useful for bug detection
  4919. if(mySdp.containsSSRC(ssrc)){
  4920. console.error("Got remove stream request for my own ssrc: "+ssrc);
  4921. return;
  4922. }
  4923. $(this).find('>parameter').each(function () {
  4924. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  4925. if ($(this).attr('value') && $(this).attr('value').length)
  4926. lines += ':' + $(this).attr('value');
  4927. lines += '\r\n';
  4928. });
  4929. });
  4930. sdp.media.forEach(function(media, idx) {
  4931. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  4932. return;
  4933. sdp.media[idx] += lines;
  4934. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  4935. self.removessrc[idx] += lines;
  4936. });
  4937. sdp.raw = sdp.session + sdp.media.join('');
  4938. });
  4939. this.modifySourcesQueue.push(function() {
  4940. // When a source is removed and if this is FF, the recvonly channel that
  4941. // receives the remote stream is deactivated . We need to diffuse the
  4942. // recvonly SSRC removal to the rest of the peers.
  4943. console.log('modify sources done');
  4944. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  4945. console.log("SDPs", mySdp, newSdp);
  4946. self.notifyMySSRCUpdate(mySdp, newSdp);
  4947. });
  4948. };
  4949. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  4950. var self = this;
  4951. if (this.peerconnection.signalingState == 'closed') return;
  4952. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  4953. // There is nothing to do since scheduled job might have been executed by another succeeding call
  4954. this.setLocalDescription();
  4955. if(successCallback){
  4956. successCallback();
  4957. }
  4958. queueCallback();
  4959. return;
  4960. }
  4961. // Reset switch streams flag
  4962. this.switchstreams = false;
  4963. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  4964. // add sources
  4965. this.addssrc.forEach(function(lines, idx) {
  4966. sdp.media[idx] += lines;
  4967. });
  4968. this.addssrc = [];
  4969. // remove sources
  4970. this.removessrc.forEach(function(lines, idx) {
  4971. lines = lines.split('\r\n');
  4972. lines.pop(); // remove empty last element;
  4973. lines.forEach(function(line) {
  4974. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  4975. });
  4976. });
  4977. this.removessrc = [];
  4978. sdp.raw = sdp.session + sdp.media.join('');
  4979. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  4980. function() {
  4981. if(self.signalingState == 'closed') {
  4982. console.error("createAnswer attempt on closed state");
  4983. queueCallback("createAnswer attempt on closed state");
  4984. return;
  4985. }
  4986. self.peerconnection.createAnswer(
  4987. function(modifiedAnswer) {
  4988. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  4989. if (self.pendingop !== null) {
  4990. var sdp = new SDP(modifiedAnswer.sdp);
  4991. if (sdp.media.length > 1) {
  4992. switch(self.pendingop) {
  4993. case 'mute':
  4994. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  4995. break;
  4996. case 'unmute':
  4997. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  4998. break;
  4999. }
  5000. sdp.raw = sdp.session + sdp.media.join('');
  5001. modifiedAnswer.sdp = sdp.raw;
  5002. }
  5003. self.pendingop = null;
  5004. }
  5005. // FIXME: pushing down an answer while ice connection state
  5006. // is still checking is bad...
  5007. //console.log(self.peerconnection.iceConnectionState);
  5008. // trying to work around another chrome bug
  5009. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  5010. self.peerconnection.setLocalDescription(modifiedAnswer,
  5011. function() {
  5012. //console.log('modified setLocalDescription ok');
  5013. self.setLocalDescription();
  5014. if(successCallback){
  5015. successCallback();
  5016. }
  5017. queueCallback();
  5018. },
  5019. function(error) {
  5020. console.error('modified setLocalDescription failed', error);
  5021. queueCallback(error);
  5022. }
  5023. );
  5024. },
  5025. function(error) {
  5026. console.error('modified answer failed', error);
  5027. queueCallback(error);
  5028. }
  5029. );
  5030. },
  5031. function(error) {
  5032. console.error('modify failed', error);
  5033. queueCallback(error);
  5034. }
  5035. );
  5036. };
  5037. /**
  5038. * Switches video streams.
  5039. * @param new_stream new stream that will be used as video of this session.
  5040. * @param oldStream old video stream of this session.
  5041. * @param success_callback callback executed after successful stream switch.
  5042. */
  5043. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  5044. var self = this;
  5045. // Remember SDP to figure out added/removed SSRCs
  5046. var oldSdp = null;
  5047. if(self.peerconnection) {
  5048. if(self.peerconnection.localDescription) {
  5049. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  5050. }
  5051. self.peerconnection.removeStream(oldStream, true);
  5052. if(new_stream)
  5053. self.peerconnection.addStream(new_stream);
  5054. }
  5055. // Conference is not active
  5056. if(!oldSdp || !self.peerconnection) {
  5057. success_callback();
  5058. return;
  5059. }
  5060. self.switchstreams = true;
  5061. self.modifySourcesQueue.push(function() {
  5062. console.log('modify sources done');
  5063. success_callback();
  5064. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5065. console.log("SDPs", oldSdp, newSdp);
  5066. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5067. });
  5068. };
  5069. /**
  5070. * Adds streams.
  5071. * @param stream new stream that will be added.
  5072. * @param success_callback callback executed after successful stream addition.
  5073. */
  5074. JingleSessionPC.prototype.addStream = function (stream, callback) {
  5075. var self = this;
  5076. // Remember SDP to figure out added/removed SSRCs
  5077. var oldSdp = null;
  5078. if(this.peerconnection) {
  5079. if(this.peerconnection.localDescription) {
  5080. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  5081. }
  5082. if(stream)
  5083. this.peerconnection.addStream(stream);
  5084. }
  5085. // Conference is not active
  5086. if(!oldSdp || !this.peerconnection) {
  5087. callback();
  5088. return;
  5089. }
  5090. this.modifySourcesQueue.push(function() {
  5091. console.log('modify sources done');
  5092. callback();
  5093. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5094. console.log("SDPs", oldSdp, newSdp);
  5095. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5096. });
  5097. }
  5098. /**
  5099. * Figures out added/removed ssrcs and send update IQs.
  5100. * @param old_sdp SDP object for old description.
  5101. * @param new_sdp SDP object for new description.
  5102. */
  5103. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  5104. if (!(this.peerconnection.signalingState == 'stable' &&
  5105. this.peerconnection.iceConnectionState == 'connected')){
  5106. console.log("Too early to send updates");
  5107. return;
  5108. }
  5109. // send source-remove IQ.
  5110. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  5111. var remove = $iq({to: this.peerjid, type: 'set'})
  5112. .c('jingle', {
  5113. xmlns: 'urn:xmpp:jingle:1',
  5114. action: 'source-remove',
  5115. initiator: this.initiator,
  5116. sid: this.sid
  5117. }
  5118. );
  5119. var removed = sdpDiffer.toJingle(remove);
  5120. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  5121. // it in the current form
  5122. if (removed)
  5123. remove = SSRCReplacement.processSourceRemove(remove);
  5124. if (removed && remove) {
  5125. console.info("Sending source-remove", remove);
  5126. this.connection.sendIQ(remove,
  5127. function (res) {
  5128. console.info('got remove result', res);
  5129. },
  5130. function (err) {
  5131. console.error('got remove error', err);
  5132. }
  5133. );
  5134. } else {
  5135. console.log('removal not necessary');
  5136. }
  5137. // send source-add IQ.
  5138. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  5139. var add = $iq({to: this.peerjid, type: 'set'})
  5140. .c('jingle', {
  5141. xmlns: 'urn:xmpp:jingle:1',
  5142. action: 'source-add',
  5143. initiator: this.initiator,
  5144. sid: this.sid
  5145. }
  5146. );
  5147. var added = sdpDiffer.toJingle(add);
  5148. // Let 'source-add' IQ through the hack and see if we're allowed to send
  5149. // it in the current form
  5150. if (added)
  5151. add = SSRCReplacement.processSourceAdd(add);
  5152. if (added && add) {
  5153. console.info("Sending source-add", add);
  5154. this.connection.sendIQ(add,
  5155. function (res) {
  5156. console.info('got add result', res);
  5157. },
  5158. function (err) {
  5159. console.error('got add error', err);
  5160. }
  5161. );
  5162. } else {
  5163. console.log('addition not necessary');
  5164. }
  5165. };
  5166. /**
  5167. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  5168. *
  5169. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  5170. * tracks; otherwise, <tt>false</tt>
  5171. * @param callback a function to be invoked with <tt>mute</tt> after all video
  5172. * tracks have been enabled/disabled. The function may, optionally, return
  5173. * another function which is to be invoked after the whole mute/unmute operation
  5174. * has completed successfully.
  5175. * @param options an object which specifies optional arguments such as the
  5176. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  5177. * specifies whether the method was initiated in response to a user command (in
  5178. * contrast to an automatic decision made by the application logic)
  5179. */
  5180. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  5181. var byUser;
  5182. if (options) {
  5183. byUser = options.byUser;
  5184. if (typeof byUser === 'undefined') {
  5185. byUser = true;
  5186. }
  5187. } else {
  5188. byUser = true;
  5189. }
  5190. // The user's command to mute the (local) video takes precedence over any
  5191. // automatic decision made by the application logic.
  5192. if (byUser) {
  5193. this.videoMuteByUser = mute;
  5194. } else if (this.videoMuteByUser) {
  5195. return;
  5196. }
  5197. this.hardMuteVideo(mute);
  5198. var self = this;
  5199. var oldSdp = null;
  5200. if(self.peerconnection) {
  5201. if(self.peerconnection.localDescription) {
  5202. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  5203. }
  5204. }
  5205. this.modifySourcesQueue.push(function() {
  5206. console.log('modify sources done');
  5207. callback(mute);
  5208. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5209. console.log("SDPs", oldSdp, newSdp);
  5210. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5211. });
  5212. };
  5213. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  5214. this.pendingop = muted ? 'mute' : 'unmute';
  5215. };
  5216. JingleSessionPC.prototype.sendMute = function (muted, content) {
  5217. var info = $iq({to: this.peerjid,
  5218. type: 'set'})
  5219. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5220. action: 'session-info',
  5221. initiator: this.initiator,
  5222. sid: this.sid });
  5223. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  5224. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  5225. if (content) {
  5226. info.attrs({'name': content});
  5227. }
  5228. this.connection.send(info);
  5229. };
  5230. JingleSessionPC.prototype.sendRinging = function () {
  5231. var info = $iq({to: this.peerjid,
  5232. type: 'set'})
  5233. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5234. action: 'session-info',
  5235. initiator: this.initiator,
  5236. sid: this.sid });
  5237. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  5238. this.connection.send(info);
  5239. };
  5240. JingleSessionPC.prototype.getStats = function (interval) {
  5241. var self = this;
  5242. var recv = {audio: 0, video: 0};
  5243. var lost = {audio: 0, video: 0};
  5244. var lastrecv = {audio: 0, video: 0};
  5245. var lastlost = {audio: 0, video: 0};
  5246. var loss = {audio: 0, video: 0};
  5247. var delta = {audio: 0, video: 0};
  5248. this.statsinterval = window.setInterval(function () {
  5249. if (self && self.peerconnection && self.peerconnection.getStats) {
  5250. self.peerconnection.getStats(function (stats) {
  5251. var results = stats.result();
  5252. // TODO: there are so much statistics you can get from this..
  5253. for (var i = 0; i < results.length; ++i) {
  5254. if (results[i].type == 'ssrc') {
  5255. var packetsrecv = results[i].stat('packetsReceived');
  5256. var packetslost = results[i].stat('packetsLost');
  5257. if (packetsrecv && packetslost) {
  5258. packetsrecv = parseInt(packetsrecv, 10);
  5259. packetslost = parseInt(packetslost, 10);
  5260. if (results[i].stat('googFrameRateReceived')) {
  5261. lastlost.video = lost.video;
  5262. lastrecv.video = recv.video;
  5263. recv.video = packetsrecv;
  5264. lost.video = packetslost;
  5265. } else {
  5266. lastlost.audio = lost.audio;
  5267. lastrecv.audio = recv.audio;
  5268. recv.audio = packetsrecv;
  5269. lost.audio = packetslost;
  5270. }
  5271. }
  5272. }
  5273. }
  5274. delta.audio = recv.audio - lastrecv.audio;
  5275. delta.video = recv.video - lastrecv.video;
  5276. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  5277. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  5278. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  5279. });
  5280. }
  5281. }, interval || 3000);
  5282. return this.statsinterval;
  5283. };
  5284. JingleSessionPC.onJingleError = function (session, error)
  5285. {
  5286. console.error("Jingle error", error);
  5287. }
  5288. JingleSessionPC.onJingleFatalError = function (session, error)
  5289. {
  5290. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5291. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  5292. }
  5293. JingleSessionPC.prototype.setLocalDescription = function () {
  5294. var self = this;
  5295. var newssrcs = [];
  5296. var session = transform.parse(this.peerconnection.localDescription.sdp);
  5297. session.media.forEach(function (media) {
  5298. if (media.ssrcs != null && media.ssrcs.length > 0) {
  5299. // TODO(gp) maybe exclude FID streams?
  5300. media.ssrcs.forEach(function (ssrc) {
  5301. if (ssrc.attribute !== 'cname') {
  5302. return;
  5303. }
  5304. newssrcs.push({
  5305. 'ssrc': ssrc.id,
  5306. 'type': media.type
  5307. });
  5308. });
  5309. }
  5310. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  5311. {
  5312. newssrcs.push({
  5313. 'ssrc': self.localStreamsSSRC[media.type],
  5314. 'type': media.type
  5315. });
  5316. }
  5317. });
  5318. console.log('new ssrcs', newssrcs);
  5319. // Bind us as local SSRCs owner
  5320. if (newssrcs.length > 0) {
  5321. for (var i = 1; i <= newssrcs.length; i ++) {
  5322. var ssrc = newssrcs[i-1].ssrc;
  5323. var myJid = self.connection.emuc.myroomjid;
  5324. self.ssrcOwners[ssrc] = myJid;
  5325. }
  5326. }
  5327. }
  5328. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  5329. JingleSessionPC.prototype.sendKeyframe = function () {
  5330. var pc = this.peerconnection;
  5331. console.log('sendkeyframe', pc.iceConnectionState);
  5332. if (pc.iceConnectionState !== 'connected') return; // safe...
  5333. var self = this;
  5334. pc.setRemoteDescription(
  5335. pc.remoteDescription,
  5336. function () {
  5337. pc.createAnswer(
  5338. function (modifiedAnswer) {
  5339. pc.setLocalDescription(
  5340. modifiedAnswer,
  5341. function () {
  5342. // noop
  5343. },
  5344. function (error) {
  5345. console.log('triggerKeyframe setLocalDescription failed', error);
  5346. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  5347. }
  5348. );
  5349. },
  5350. function (error) {
  5351. console.log('triggerKeyframe createAnswer failed', error);
  5352. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  5353. }
  5354. );
  5355. },
  5356. function (error) {
  5357. console.log('triggerKeyframe setRemoteDescription failed', error);
  5358. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  5359. }
  5360. );
  5361. }
  5362. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  5363. var self = this;
  5364. var thessrc;
  5365. var streamId = RTC.getStreamID(data.stream);
  5366. // look up an associated JID for a stream id
  5367. if (!streamId) {
  5368. console.error("No stream ID for", data.stream);
  5369. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  5370. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  5371. var ssrclines
  5372. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  5373. ssrclines = ssrclines.filter(function (line) {
  5374. // NOTE(gp) previously we filtered on the mslabel, but that property
  5375. // is not always present.
  5376. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  5377. if (RTCBrowserType.isTemasysPluginUsed()) {
  5378. return ((line.indexOf('mslabel:' + streamId) !== -1));
  5379. } else {
  5380. return ((line.indexOf('msid:' + streamId) !== -1));
  5381. }
  5382. });
  5383. if (ssrclines.length) {
  5384. thessrc = ssrclines[0].substring(7).split(' ')[0];
  5385. if (!self.ssrcOwners[thessrc]) {
  5386. console.error("No SSRC owner known for: " + thessrc);
  5387. return;
  5388. }
  5389. data.peerjid = self.ssrcOwners[thessrc];
  5390. console.log('associated jid', self.ssrcOwners[thessrc]);
  5391. } else {
  5392. console.error("No SSRC lines for ", streamId);
  5393. }
  5394. }
  5395. this.room.remoteStreamAdded(data, this.sid, thessrc);
  5396. var isVideo = data.stream.getVideoTracks().length > 0;
  5397. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  5398. if (isVideo &&
  5399. data.peerjid && this.peerjid === data.peerjid &&
  5400. data.stream.getVideoTracks().length === 0 &&
  5401. RTC.localVideo.getTracks().length > 0) {
  5402. window.setTimeout(function () {
  5403. self.sendKeyframe();
  5404. }, 3000);
  5405. }
  5406. }
  5407. module.exports = JingleSessionPC;
  5408. },{"../../service/xmpp/XMPPEvents":76,"../RTC/RTC":13,"../RTC/RTCBrowserType":14,"./JingleSession":20,"./LocalSSRCReplacement":22,"./SDP":23,"./SDPDiffer":24,"./SDPUtil":25,"./TraceablePeerConnection":26,"async":34,"sdp-transform":67}],22:[function(require,module,exports){
  5409. /* global $ */
  5410. /*
  5411. Here we do modifications of local video SSRCs. There are 2 situations we have
  5412. to handle:
  5413. 1. We generate SSRC for local recvonly video stream. This is the case when we
  5414. have no local camera and it is not generated automatically, but SSRC=1 is
  5415. used implicitly. If that happens RTCP packets will be dropped by the JVB
  5416. and we won't be able to request video key frames correctly.
  5417. 2. A hack to re-use SSRC of the first video stream for any new stream created
  5418. in future. It turned out that Chrome may keep on using the SSRC of removed
  5419. video stream in RTCP even though a new one has been created. So we just
  5420. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  5421. notifications are blocked once first video SSRC is advertised to the focus.
  5422. What this hack does:
  5423. 1. Stores the SSRC of the first video stream created by
  5424. a) scanning Jingle session-accept/session-invite for existing video SSRC
  5425. b) watching for 'source-add' for new video stream if it has not been
  5426. created in step a)
  5427. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  5428. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  5429. returned to the other parts of the application.
  5430. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  5431. blocks those notifications. This makes Jicofo and all participants think
  5432. that it exists all the time even if the video stream has been removed or
  5433. replaced locally. Thanks to that there is no additional signaling activity
  5434. on video mute or when switching to the desktop stream.
  5435. */
  5436. var SDP = require('./SDP');
  5437. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5438. /**
  5439. * The hack is enabled on all browsers except FF by default
  5440. * FIXME finish the hack once removeStream method is implemented in FF
  5441. * @type {boolean}
  5442. */
  5443. var isEnabled = !RTCBrowserType.isFirefox();
  5444. /**
  5445. * Stored SSRC of local video stream.
  5446. */
  5447. var localVideoSSRC;
  5448. /**
  5449. * SSRC used for recvonly video stream when we have no local camera.
  5450. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  5451. * instead of 1.
  5452. */
  5453. var localRecvOnlySSRC;
  5454. /**
  5455. * cname for <tt>localRecvOnlySSRC</tt>
  5456. */
  5457. var localRecvOnlyCName;
  5458. /**
  5459. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  5460. * from given Jingle IQ.
  5461. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  5462. * @param actionName display name of the action which will be printed in log
  5463. * messages.
  5464. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  5465. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  5466. * other SSRCs left to be signaled after removing it.
  5467. */
  5468. var filterOutSource = function (modifyIq, actionName) {
  5469. var modifyIqTree = $(modifyIq.tree());
  5470. if (!localVideoSSRC)
  5471. return modifyIqTree[0];
  5472. var videoSSRC = modifyIqTree.find(
  5473. '>jingle>content[name="video"]' +
  5474. '>description>source[ssrc="' + localVideoSSRC + '"]');
  5475. if (!videoSSRC.length) {
  5476. return modifyIqTree[0];
  5477. }
  5478. console.info(
  5479. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  5480. videoSSRC.remove();
  5481. // Check if any sources still left to be added/removed
  5482. if (modifyIqTree.find('>jingle>content>description>source').length) {
  5483. return modifyIqTree[0];
  5484. } else {
  5485. return null;
  5486. }
  5487. };
  5488. /**
  5489. * Scans given Jingle IQ for video SSRC and stores it.
  5490. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  5491. */
  5492. var storeLocalVideoSSRC = function (jingleIq) {
  5493. var videoSSRCs =
  5494. $(jingleIq.tree())
  5495. .find('>jingle>content[name="video"]>description>source');
  5496. videoSSRCs.each(function (idx, ssrcElem) {
  5497. if (localVideoSSRC)
  5498. return;
  5499. // We consider SSRC real only if it has msid attribute
  5500. // recvonly streams in FF do not have it as well as local SSRCs
  5501. // we generate for recvonly streams in Chrome
  5502. var ssrSel = $(ssrcElem);
  5503. var msid = ssrSel.find('>parameter[name="msid"]');
  5504. if (msid.length) {
  5505. var ssrcVal = ssrSel.attr('ssrc');
  5506. if (ssrcVal) {
  5507. localVideoSSRC = ssrcVal;
  5508. console.info('Stored local video SSRC' +
  5509. ' for future re-use: ' + localVideoSSRC);
  5510. }
  5511. }
  5512. });
  5513. };
  5514. /**
  5515. * Generates new SSRC for local video recvonly stream.
  5516. * FIXME what about eventual SSRC collision ?
  5517. */
  5518. function generateRecvonlySSRC() {
  5519. //
  5520. localRecvOnlySSRC =
  5521. Math.random().toString(10).substring(2, 11);
  5522. localRecvOnlyCName =
  5523. Math.random().toString(36).substring(2);
  5524. console.info(
  5525. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  5526. ", cname: " + localRecvOnlyCName);
  5527. }
  5528. var LocalSSRCReplacement = {
  5529. /**
  5530. * Method must be called before 'session-initiate' or 'session-invite' is
  5531. * sent. Scans the IQ for local video SSRC and stores it if detected.
  5532. *
  5533. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  5534. * which will be scanned for local video SSRC.
  5535. */
  5536. processSessionInit: function (sessionInit) {
  5537. if (!isEnabled)
  5538. return;
  5539. if (localVideoSSRC) {
  5540. console.error("Local SSRC stored already: " + localVideoSSRC);
  5541. return;
  5542. }
  5543. storeLocalVideoSSRC(sessionInit);
  5544. },
  5545. /**
  5546. * If we have local video SSRC stored searched given
  5547. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  5548. * with the stored one.
  5549. * @param localDescription local description object that will have local
  5550. * video SSRC replaced with the stored one
  5551. * @returns modified <tt>localDescription</tt> object.
  5552. */
  5553. mungeLocalVideoSSRC: function (localDescription) {
  5554. if (!isEnabled)
  5555. return localDescription;
  5556. if (!localDescription) {
  5557. console.warn("localDescription is null or undefined");
  5558. return localDescription;
  5559. }
  5560. // IF we have local video SSRC stored make sure it is replaced
  5561. // with old SSRC
  5562. if (localVideoSSRC) {
  5563. var newSdp = new SDP(localDescription.sdp);
  5564. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  5565. !newSdp.containsSSRC(localVideoSSRC)) {
  5566. // Get new video SSRC
  5567. var map = newSdp.getMediaSsrcMap();
  5568. var videoPart = map[1];
  5569. var videoSSRCs = videoPart.ssrcs;
  5570. var newSSRC = Object.keys(videoSSRCs)[0];
  5571. console.info(
  5572. "Replacing new video SSRC: " + newSSRC +
  5573. " with " + localVideoSSRC);
  5574. localDescription.sdp =
  5575. newSdp.raw.replace(
  5576. new RegExp('a=ssrc:' + newSSRC, 'g'),
  5577. 'a=ssrc:' + localVideoSSRC);
  5578. }
  5579. } else {
  5580. // Make sure we have any SSRC for recvonly video stream
  5581. var sdp = new SDP(localDescription.sdp);
  5582. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  5583. sdp.media[1].indexOf('a=recvonly') !== -1) {
  5584. if (!localRecvOnlySSRC) {
  5585. generateRecvonlySSRC();
  5586. }
  5587. console.info('No SSRC in video recvonly stream' +
  5588. ' - adding SSRC: ' + localRecvOnlySSRC);
  5589. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  5590. ' cname:' + localRecvOnlyCName + '\r\n';
  5591. localDescription.sdp = sdp.session + sdp.media.join('');
  5592. }
  5593. }
  5594. return localDescription;
  5595. },
  5596. /**
  5597. * Method must be called before 'source-add' notification is sent. In case
  5598. * we have local video SSRC advertised already it will be removed from the
  5599. * notification. If no other SSRCs are described by given IQ null will be
  5600. * returned which means that there is no point in sending the notification.
  5601. * @param sourceAdd 'source-add' Jingle IQ to be processed
  5602. * @returns modified 'source-add' IQ which can be sent to the focus or
  5603. * <tt>null</tt> if no notification shall be sent. It is no longer
  5604. * a Strophe IQ Builder instance, but DOM element tree.
  5605. */
  5606. processSourceAdd: function (sourceAdd) {
  5607. if (!isEnabled)
  5608. return sourceAdd;
  5609. if (!localVideoSSRC) {
  5610. // Store local SSRC if available
  5611. storeLocalVideoSSRC(sourceAdd);
  5612. return sourceAdd;
  5613. } else {
  5614. return filterOutSource(sourceAdd, 'source-add');
  5615. }
  5616. },
  5617. /**
  5618. * Method must be called before 'source-remove' notification is sent.
  5619. * Removes local video SSRC from the notification. If there are no other
  5620. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  5621. * means that there is no point in sending the notification.
  5622. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  5623. * @returns modified 'source-remove' IQ which can be sent to the focus or
  5624. * <tt>null</tt> if no notification shall be sent. It is no longer
  5625. * a Strophe IQ Builder instance, but DOM element tree.
  5626. */
  5627. processSourceRemove: function (sourceRemove) {
  5628. if (!isEnabled)
  5629. return sourceRemove;
  5630. return filterOutSource(sourceRemove, 'source-remove');
  5631. },
  5632. /**
  5633. * Turns the hack on or off
  5634. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  5635. * to disable it
  5636. */
  5637. setEnabled: function (enabled) {
  5638. isEnabled = enabled;
  5639. }
  5640. };
  5641. module.exports = LocalSSRCReplacement;
  5642. },{"../RTC/RTCBrowserType":14,"./SDP":23}],23:[function(require,module,exports){
  5643. /* jshint -W117 */
  5644. var SDPUtil = require("./SDPUtil");
  5645. // SDP STUFF
  5646. function SDP(sdp) {
  5647. this.media = sdp.split('\r\nm=');
  5648. for (var i = 1; i < this.media.length; i++) {
  5649. this.media[i] = 'm=' + this.media[i];
  5650. if (i != this.media.length - 1) {
  5651. this.media[i] += '\r\n';
  5652. }
  5653. }
  5654. this.session = this.media.shift() + '\r\n';
  5655. this.raw = this.session + this.media.join('');
  5656. }
  5657. /**
  5658. * Returns map of MediaChannel mapped per channel idx.
  5659. */
  5660. SDP.prototype.getMediaSsrcMap = function() {
  5661. var self = this;
  5662. var media_ssrcs = {};
  5663. var tmp;
  5664. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  5665. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  5666. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  5667. var media = {
  5668. mediaindex: mediaindex,
  5669. mid: mid,
  5670. ssrcs: {},
  5671. ssrcGroups: []
  5672. };
  5673. media_ssrcs[mediaindex] = media;
  5674. tmp.forEach(function (line) {
  5675. var linessrc = line.substring(7).split(' ')[0];
  5676. // allocate new ChannelSsrc
  5677. if(!media.ssrcs[linessrc]) {
  5678. media.ssrcs[linessrc] = {
  5679. ssrc: linessrc,
  5680. lines: []
  5681. };
  5682. }
  5683. media.ssrcs[linessrc].lines.push(line);
  5684. });
  5685. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  5686. tmp.forEach(function(line){
  5687. var semantics = line.substr(0, idx).substr(13);
  5688. var ssrcs = line.substr(14 + semantics.length).split(' ');
  5689. if (ssrcs.length != 0) {
  5690. media.ssrcGroups.push({
  5691. semantics: semantics,
  5692. ssrcs: ssrcs
  5693. });
  5694. }
  5695. });
  5696. }
  5697. return media_ssrcs;
  5698. };
  5699. /**
  5700. * Returns <tt>true</tt> if this SDP contains given SSRC.
  5701. * @param ssrc the ssrc to check.
  5702. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  5703. */
  5704. SDP.prototype.containsSSRC = function(ssrc) {
  5705. var medias = this.getMediaSsrcMap();
  5706. var contains = false;
  5707. Object.keys(medias).forEach(function(mediaindex){
  5708. var media = medias[mediaindex];
  5709. //console.log("Check", channel, ssrc);
  5710. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  5711. contains = true;
  5712. }
  5713. });
  5714. return contains;
  5715. };
  5716. // remove iSAC and CN from SDP
  5717. SDP.prototype.mangle = function () {
  5718. var i, j, mline, lines, rtpmap, newdesc;
  5719. for (i = 0; i < this.media.length; i++) {
  5720. lines = this.media[i].split('\r\n');
  5721. lines.pop(); // remove empty last element
  5722. mline = SDPUtil.parse_mline(lines.shift());
  5723. if (mline.media != 'audio')
  5724. continue;
  5725. newdesc = '';
  5726. mline.fmt.length = 0;
  5727. for (j = 0; j < lines.length; j++) {
  5728. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  5729. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  5730. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  5731. continue;
  5732. mline.fmt.push(rtpmap.id);
  5733. newdesc += lines[j] + '\r\n';
  5734. } else {
  5735. newdesc += lines[j] + '\r\n';
  5736. }
  5737. }
  5738. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  5739. this.media[i] += newdesc;
  5740. }
  5741. this.raw = this.session + this.media.join('');
  5742. };
  5743. // remove lines matching prefix from session section
  5744. SDP.prototype.removeSessionLines = function(prefix) {
  5745. var self = this;
  5746. var lines = SDPUtil.find_lines(this.session, prefix);
  5747. lines.forEach(function(line) {
  5748. self.session = self.session.replace(line + '\r\n', '');
  5749. });
  5750. this.raw = this.session + this.media.join('');
  5751. return lines;
  5752. }
  5753. // remove lines matching prefix from a media section specified by mediaindex
  5754. // TODO: non-numeric mediaindex could match mid
  5755. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  5756. var self = this;
  5757. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  5758. lines.forEach(function(line) {
  5759. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  5760. });
  5761. this.raw = this.session + this.media.join('');
  5762. return lines;
  5763. }
  5764. // add content's to a jingle element
  5765. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  5766. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  5767. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  5768. var self = this;
  5769. // new bundle plan
  5770. if (SDPUtil.find_line(this.session, 'a=group:')) {
  5771. lines = SDPUtil.find_lines(this.session, 'a=group:');
  5772. for (i = 0; i < lines.length; i++) {
  5773. tmp = lines[i].split(' ');
  5774. var semantics = tmp.shift().substr(8);
  5775. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  5776. for (j = 0; j < tmp.length; j++) {
  5777. elem.c('content', {name: tmp[j]}).up();
  5778. }
  5779. elem.up();
  5780. }
  5781. }
  5782. for (i = 0; i < this.media.length; i++) {
  5783. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  5784. if (!(mline.media === 'audio' ||
  5785. mline.media === 'video' ||
  5786. mline.media === 'application'))
  5787. {
  5788. continue;
  5789. }
  5790. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  5791. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  5792. } else {
  5793. if(ssrcs && ssrcs[mline.media])
  5794. {
  5795. ssrc = ssrcs[mline.media];
  5796. }
  5797. else
  5798. ssrc = false;
  5799. }
  5800. elem.c('content', {creator: thecreator, name: mline.media});
  5801. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  5802. // prefer identifier from a=mid if present
  5803. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  5804. elem.attrs({ name: mid });
  5805. }
  5806. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  5807. {
  5808. elem.c('description',
  5809. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  5810. media: mline.media });
  5811. if (ssrc) {
  5812. elem.attrs({ssrc: ssrc});
  5813. }
  5814. for (j = 0; j < mline.fmt.length; j++) {
  5815. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  5816. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  5817. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  5818. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  5819. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  5820. for (k = 0; k < tmp.length; k++) {
  5821. elem.c('parameter', tmp[k]).up();
  5822. }
  5823. }
  5824. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  5825. elem.up();
  5826. }
  5827. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  5828. elem.c('encryption', {required: 1});
  5829. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  5830. crypto.forEach(function(line) {
  5831. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  5832. });
  5833. elem.up(); // end of encryption
  5834. }
  5835. if (ssrc) {
  5836. // new style mapping
  5837. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5838. // FIXME: group by ssrc and support multiple different ssrcs
  5839. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  5840. if(ssrclines.length > 0) {
  5841. ssrclines.forEach(function (line) {
  5842. idx = line.indexOf(' ');
  5843. var linessrc = line.substr(0, idx).substr(7);
  5844. if (linessrc != ssrc) {
  5845. elem.up();
  5846. ssrc = linessrc;
  5847. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5848. }
  5849. var kv = line.substr(idx + 1);
  5850. elem.c('parameter');
  5851. if (kv.indexOf(':') == -1) {
  5852. elem.attrs({ name: kv });
  5853. } else {
  5854. var k = kv.split(':', 2)[0];
  5855. elem.attrs({ name: k });
  5856. var v = kv.split(':', 2)[1];
  5857. v = SDPUtil.filter_special_chars(v);
  5858. elem.attrs({ value: v });
  5859. }
  5860. elem.up();
  5861. });
  5862. }
  5863. else
  5864. {
  5865. elem.up();
  5866. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5867. elem.c('parameter');
  5868. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  5869. elem.up();
  5870. var msid = null;
  5871. if(mline.media == "audio")
  5872. {
  5873. msid = APP.RTC.localAudio.getId();
  5874. }
  5875. else
  5876. {
  5877. msid = APP.RTC.localVideo.getId();
  5878. }
  5879. if(msid != null)
  5880. {
  5881. msid = SDPUtil.filter_special_chars(msid);
  5882. elem.c('parameter');
  5883. elem.attrs({name: "msid", value:msid});
  5884. elem.up();
  5885. elem.c('parameter');
  5886. elem.attrs({name: "mslabel", value:msid});
  5887. elem.up();
  5888. elem.c('parameter');
  5889. elem.attrs({name: "label", value:msid});
  5890. elem.up();
  5891. }
  5892. }
  5893. elem.up();
  5894. // XEP-0339 handle ssrc-group attributes
  5895. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  5896. ssrc_group_lines.forEach(function(line) {
  5897. idx = line.indexOf(' ');
  5898. var semantics = line.substr(0, idx).substr(13);
  5899. var ssrcs = line.substr(14 + semantics.length).split(' ');
  5900. if (ssrcs.length != 0) {
  5901. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5902. ssrcs.forEach(function(ssrc) {
  5903. elem.c('source', { ssrc: ssrc })
  5904. .up();
  5905. });
  5906. elem.up();
  5907. }
  5908. });
  5909. }
  5910. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  5911. elem.c('rtcp-mux').up();
  5912. }
  5913. // XEP-0293 -- map a=rtcp-fb:*
  5914. this.RtcpFbToJingle(i, elem, '*');
  5915. // XEP-0294
  5916. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  5917. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  5918. for (j = 0; j < lines.length; j++) {
  5919. tmp = SDPUtil.parse_extmap(lines[j]);
  5920. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  5921. uri: tmp.uri,
  5922. id: tmp.value });
  5923. if (tmp.hasOwnProperty('direction')) {
  5924. switch (tmp.direction) {
  5925. case 'sendonly':
  5926. elem.attrs({senders: 'responder'});
  5927. break;
  5928. case 'recvonly':
  5929. elem.attrs({senders: 'initiator'});
  5930. break;
  5931. case 'sendrecv':
  5932. elem.attrs({senders: 'both'});
  5933. break;
  5934. case 'inactive':
  5935. elem.attrs({senders: 'none'});
  5936. break;
  5937. }
  5938. }
  5939. // TODO: handle params
  5940. elem.up();
  5941. }
  5942. }
  5943. elem.up(); // end of description
  5944. }
  5945. // map ice-ufrag/pwd, dtls fingerprint, candidates
  5946. this.TransportToJingle(i, elem);
  5947. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  5948. elem.attrs({senders: 'both'});
  5949. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  5950. elem.attrs({senders: 'initiator'});
  5951. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  5952. elem.attrs({senders: 'responder'});
  5953. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  5954. elem.attrs({senders: 'none'});
  5955. }
  5956. if (mline.port == '0') {
  5957. // estos hack to reject an m-line
  5958. elem.attrs({senders: 'rejected'});
  5959. }
  5960. elem.up(); // end of content
  5961. }
  5962. elem.up();
  5963. return elem;
  5964. };
  5965. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  5966. var i = mediaindex;
  5967. var tmp;
  5968. var self = this;
  5969. elem.c('transport');
  5970. // XEP-0343 DTLS/SCTP
  5971. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  5972. {
  5973. var sctpmap = SDPUtil.find_line(
  5974. this.media[i], 'a=sctpmap:', self.session);
  5975. if (sctpmap)
  5976. {
  5977. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  5978. elem.c('sctpmap',
  5979. {
  5980. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  5981. number: sctpAttrs[0], /* SCTP port */
  5982. protocol: sctpAttrs[1], /* protocol */
  5983. });
  5984. // Optional stream count attribute
  5985. if (sctpAttrs.length > 2)
  5986. elem.attrs({ streams: sctpAttrs[2]});
  5987. elem.up();
  5988. }
  5989. }
  5990. // XEP-0320
  5991. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  5992. fingerprints.forEach(function(line) {
  5993. tmp = SDPUtil.parse_fingerprint(line);
  5994. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  5995. elem.c('fingerprint').t(tmp.fingerprint);
  5996. delete tmp.fingerprint;
  5997. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  5998. if (line) {
  5999. tmp.setup = line.substr(8);
  6000. }
  6001. elem.attrs(tmp);
  6002. elem.up(); // end of fingerprint
  6003. });
  6004. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  6005. if (tmp) {
  6006. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  6007. elem.attrs(tmp);
  6008. // XEP-0176
  6009. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  6010. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  6011. lines.forEach(function (line) {
  6012. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  6013. });
  6014. }
  6015. }
  6016. elem.up(); // end of transport
  6017. }
  6018. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  6019. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  6020. lines.forEach(function (line) {
  6021. var tmp = SDPUtil.parse_rtcpfb(line);
  6022. if (tmp.type == 'trr-int') {
  6023. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  6024. elem.up();
  6025. } else {
  6026. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  6027. if (tmp.params.length > 0) {
  6028. elem.attrs({'subtype': tmp.params[0]});
  6029. }
  6030. elem.up();
  6031. }
  6032. });
  6033. };
  6034. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  6035. var media = '';
  6036. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  6037. if (tmp.length) {
  6038. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  6039. if (tmp.attr('value')) {
  6040. media += tmp.attr('value');
  6041. } else {
  6042. media += '0';
  6043. }
  6044. media += '\r\n';
  6045. }
  6046. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  6047. tmp.each(function () {
  6048. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  6049. if ($(this).attr('subtype')) {
  6050. media += ' ' + $(this).attr('subtype');
  6051. }
  6052. media += '\r\n';
  6053. });
  6054. return media;
  6055. };
  6056. // construct an SDP from a jingle stanza
  6057. SDP.prototype.fromJingle = function (jingle) {
  6058. var self = this;
  6059. this.raw = 'v=0\r\n' +
  6060. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  6061. 's=-\r\n' +
  6062. 't=0 0\r\n';
  6063. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  6064. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  6065. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  6066. var contents = $(group).find('>content').map(function (idx, content) {
  6067. return content.getAttribute('name');
  6068. }).get();
  6069. if (contents.length > 0) {
  6070. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  6071. }
  6072. });
  6073. }
  6074. this.session = this.raw;
  6075. jingle.find('>content').each(function () {
  6076. var m = self.jingle2media($(this));
  6077. self.media.push(m);
  6078. });
  6079. // reconstruct msid-semantic -- apparently not necessary
  6080. /*
  6081. var msid = SDPUtil.parse_ssrc(this.raw);
  6082. if (msid.hasOwnProperty('mslabel')) {
  6083. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  6084. }
  6085. */
  6086. this.raw = this.session + this.media.join('');
  6087. };
  6088. // translate a jingle content element into an an SDP media part
  6089. SDP.prototype.jingle2media = function (content) {
  6090. var media = '',
  6091. desc = content.find('description'),
  6092. ssrc = desc.attr('ssrc'),
  6093. self = this,
  6094. tmp;
  6095. var sctp = content.find(
  6096. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  6097. tmp = { media: desc.attr('media') };
  6098. tmp.port = '1';
  6099. if (content.attr('senders') == 'rejected') {
  6100. // estos hack to reject an m-line.
  6101. tmp.port = '0';
  6102. }
  6103. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  6104. if (sctp.length)
  6105. tmp.proto = 'DTLS/SCTP';
  6106. else
  6107. tmp.proto = 'RTP/SAVPF';
  6108. } else {
  6109. tmp.proto = 'RTP/AVPF';
  6110. }
  6111. if (!sctp.length)
  6112. {
  6113. tmp.fmt = desc.find('payload-type').map(
  6114. function () { return this.getAttribute('id'); }).get();
  6115. media += SDPUtil.build_mline(tmp) + '\r\n';
  6116. }
  6117. else
  6118. {
  6119. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  6120. media += 'a=sctpmap:' + sctp.attr('number') +
  6121. ' ' + sctp.attr('protocol');
  6122. var streamCount = sctp.attr('streams');
  6123. if (streamCount)
  6124. media += ' ' + streamCount + '\r\n';
  6125. else
  6126. media += '\r\n';
  6127. }
  6128. media += 'c=IN IP4 0.0.0.0\r\n';
  6129. if (!sctp.length)
  6130. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  6131. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  6132. if (tmp.length) {
  6133. if (tmp.attr('ufrag')) {
  6134. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  6135. }
  6136. if (tmp.attr('pwd')) {
  6137. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  6138. }
  6139. tmp.find('>fingerprint').each(function () {
  6140. // FIXME: check namespace at some point
  6141. media += 'a=fingerprint:' + this.getAttribute('hash');
  6142. media += ' ' + $(this).text();
  6143. media += '\r\n';
  6144. if (this.getAttribute('setup')) {
  6145. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  6146. }
  6147. });
  6148. }
  6149. switch (content.attr('senders')) {
  6150. case 'initiator':
  6151. media += 'a=sendonly\r\n';
  6152. break;
  6153. case 'responder':
  6154. media += 'a=recvonly\r\n';
  6155. break;
  6156. case 'none':
  6157. media += 'a=inactive\r\n';
  6158. break;
  6159. case 'both':
  6160. media += 'a=sendrecv\r\n';
  6161. break;
  6162. }
  6163. media += 'a=mid:' + content.attr('name') + '\r\n';
  6164. // <description><rtcp-mux/></description>
  6165. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  6166. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  6167. if (desc.find('rtcp-mux').length) {
  6168. media += 'a=rtcp-mux\r\n';
  6169. }
  6170. if (desc.find('encryption').length) {
  6171. desc.find('encryption>crypto').each(function () {
  6172. media += 'a=crypto:' + this.getAttribute('tag');
  6173. media += ' ' + this.getAttribute('crypto-suite');
  6174. media += ' ' + this.getAttribute('key-params');
  6175. if (this.getAttribute('session-params')) {
  6176. media += ' ' + this.getAttribute('session-params');
  6177. }
  6178. media += '\r\n';
  6179. });
  6180. }
  6181. desc.find('payload-type').each(function () {
  6182. media += SDPUtil.build_rtpmap(this) + '\r\n';
  6183. if ($(this).find('>parameter').length) {
  6184. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  6185. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  6186. media += '\r\n';
  6187. }
  6188. // xep-0293
  6189. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  6190. });
  6191. // xep-0293
  6192. media += self.RtcpFbFromJingle(desc, '*');
  6193. // xep-0294
  6194. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  6195. tmp.each(function () {
  6196. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  6197. });
  6198. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  6199. media += SDPUtil.candidateFromJingle(this);
  6200. });
  6201. // XEP-0339 handle ssrc-group attributes
  6202. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6203. var semantics = this.getAttribute('semantics');
  6204. var ssrcs = $(this).find('>source').map(function() {
  6205. return this.getAttribute('ssrc');
  6206. }).get();
  6207. if (ssrcs.length != 0) {
  6208. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6209. }
  6210. });
  6211. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6212. tmp.each(function () {
  6213. var ssrc = this.getAttribute('ssrc');
  6214. $(this).find('>parameter').each(function () {
  6215. var name = this.getAttribute('name');
  6216. var value = this.getAttribute('value');
  6217. value = SDPUtil.filter_special_chars(value);
  6218. media += 'a=ssrc:' + ssrc + ' ' + name;
  6219. if (value && value.length)
  6220. media += ':' + value;
  6221. media += '\r\n';
  6222. });
  6223. });
  6224. return media;
  6225. };
  6226. module.exports = SDP;
  6227. },{"./SDPUtil":25}],24:[function(require,module,exports){
  6228. var SDPUtil = require("./SDPUtil");
  6229. function SDPDiffer(mySDP, otherSDP) {
  6230. this.mySDP = mySDP;
  6231. this.otherSDP = otherSDP;
  6232. }
  6233. /**
  6234. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  6235. * @param otherSdp the other SDP to check ssrc with.
  6236. */
  6237. SDPDiffer.prototype.getNewMedia = function() {
  6238. // this could be useful in Array.prototype.
  6239. function arrayEquals(array) {
  6240. // if the other array is a falsy value, return
  6241. if (!array)
  6242. return false;
  6243. // compare lengths - can save a lot of time
  6244. if (this.length != array.length)
  6245. return false;
  6246. for (var i = 0, l=this.length; i < l; i++) {
  6247. // Check if we have nested arrays
  6248. if (this[i] instanceof Array && array[i] instanceof Array) {
  6249. // recurse into the nested arrays
  6250. if (!this[i].equals(array[i]))
  6251. return false;
  6252. }
  6253. else if (this[i] != array[i]) {
  6254. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  6255. return false;
  6256. }
  6257. }
  6258. return true;
  6259. }
  6260. var myMedias = this.mySDP.getMediaSsrcMap();
  6261. var othersMedias = this.otherSDP.getMediaSsrcMap();
  6262. var newMedia = {};
  6263. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  6264. var myMedia = myMedias[othersMediaIdx];
  6265. var othersMedia = othersMedias[othersMediaIdx];
  6266. if(!myMedia && othersMedia) {
  6267. // Add whole channel
  6268. newMedia[othersMediaIdx] = othersMedia;
  6269. return;
  6270. }
  6271. // Look for new ssrcs accross the channel
  6272. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  6273. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  6274. // Allocate channel if we've found ssrc that doesn't exist in our channel
  6275. if(!newMedia[othersMediaIdx]){
  6276. newMedia[othersMediaIdx] = {
  6277. mediaindex: othersMedia.mediaindex,
  6278. mid: othersMedia.mid,
  6279. ssrcs: {},
  6280. ssrcGroups: []
  6281. };
  6282. }
  6283. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  6284. }
  6285. });
  6286. // Look for new ssrc groups across the channels
  6287. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  6288. // try to match the other ssrc-group with an ssrc-group of ours
  6289. var matched = false;
  6290. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  6291. var mySsrcGroup = myMedia.ssrcGroups[i];
  6292. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  6293. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  6294. matched = true;
  6295. break;
  6296. }
  6297. }
  6298. if (!matched) {
  6299. // Allocate channel if we've found an ssrc-group that doesn't
  6300. // exist in our channel
  6301. if(!newMedia[othersMediaIdx]){
  6302. newMedia[othersMediaIdx] = {
  6303. mediaindex: othersMedia.mediaindex,
  6304. mid: othersMedia.mid,
  6305. ssrcs: {},
  6306. ssrcGroups: []
  6307. };
  6308. }
  6309. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  6310. }
  6311. });
  6312. });
  6313. return newMedia;
  6314. };
  6315. /**
  6316. * Sends SSRC update IQ.
  6317. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  6318. * @param sid session identifier that will be put into the IQ.
  6319. * @param initiator initiator identifier.
  6320. * @param toJid destination Jid
  6321. * @param isAdd indicates if this is remove or add operation.
  6322. */
  6323. SDPDiffer.prototype.toJingle = function(modify) {
  6324. var sdpMediaSsrcs = this.getNewMedia();
  6325. var self = this;
  6326. // FIXME: only announce video ssrcs since we mix audio and dont need
  6327. // the audio ssrcs therefore
  6328. var modified = false;
  6329. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  6330. modified = true;
  6331. var media = sdpMediaSsrcs[mediaindex];
  6332. modify.c('content', {name: media.mid});
  6333. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  6334. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  6335. // generate sources from lines
  6336. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  6337. var mediaSsrc = media.ssrcs[ssrcNum];
  6338. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6339. modify.attrs({ssrc: mediaSsrc.ssrc});
  6340. // iterate over ssrc lines
  6341. mediaSsrc.lines.forEach(function (line) {
  6342. var idx = line.indexOf(' ');
  6343. var kv = line.substr(idx + 1);
  6344. modify.c('parameter');
  6345. if (kv.indexOf(':') == -1) {
  6346. modify.attrs({ name: kv });
  6347. } else {
  6348. var nv = kv.split(':', 2);
  6349. var name = nv[0];
  6350. var value = SDPUtil.filter_special_chars(nv[1]);
  6351. modify.attrs({ name: name });
  6352. modify.attrs({ value: value });
  6353. }
  6354. modify.up(); // end of parameter
  6355. });
  6356. modify.up(); // end of source
  6357. });
  6358. // generate source groups from lines
  6359. media.ssrcGroups.forEach(function(ssrcGroup) {
  6360. if (ssrcGroup.ssrcs.length != 0) {
  6361. modify.c('ssrc-group', {
  6362. semantics: ssrcGroup.semantics,
  6363. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  6364. });
  6365. ssrcGroup.ssrcs.forEach(function (ssrc) {
  6366. modify.c('source', { ssrc: ssrc })
  6367. .up(); // end of source
  6368. });
  6369. modify.up(); // end of ssrc-group
  6370. }
  6371. });
  6372. modify.up(); // end of description
  6373. modify.up(); // end of content
  6374. });
  6375. return modified;
  6376. };
  6377. module.exports = SDPDiffer;
  6378. },{"./SDPUtil":25}],25:[function(require,module,exports){
  6379. SDPUtil = {
  6380. filter_special_chars: function (text) {
  6381. return text.replace(/[\\\/\{,\}\+]/g, "");
  6382. },
  6383. iceparams: function (mediadesc, sessiondesc) {
  6384. var data = null;
  6385. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  6386. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  6387. data = {
  6388. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  6389. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  6390. };
  6391. }
  6392. return data;
  6393. },
  6394. parse_iceufrag: function (line) {
  6395. return line.substring(12);
  6396. },
  6397. build_iceufrag: function (frag) {
  6398. return 'a=ice-ufrag:' + frag;
  6399. },
  6400. parse_icepwd: function (line) {
  6401. return line.substring(10);
  6402. },
  6403. build_icepwd: function (pwd) {
  6404. return 'a=ice-pwd:' + pwd;
  6405. },
  6406. parse_mid: function (line) {
  6407. return line.substring(6);
  6408. },
  6409. parse_mline: function (line) {
  6410. var parts = line.substring(2).split(' '),
  6411. data = {};
  6412. data.media = parts.shift();
  6413. data.port = parts.shift();
  6414. data.proto = parts.shift();
  6415. if (parts[parts.length - 1] === '') { // trailing whitespace
  6416. parts.pop();
  6417. }
  6418. data.fmt = parts;
  6419. return data;
  6420. },
  6421. build_mline: function (mline) {
  6422. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  6423. },
  6424. parse_rtpmap: function (line) {
  6425. var parts = line.substring(9).split(' '),
  6426. data = {};
  6427. data.id = parts.shift();
  6428. parts = parts[0].split('/');
  6429. data.name = parts.shift();
  6430. data.clockrate = parts.shift();
  6431. data.channels = parts.length ? parts.shift() : '1';
  6432. return data;
  6433. },
  6434. /**
  6435. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  6436. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  6437. * @returns [SCTP port number, protocol, streams]
  6438. */
  6439. parse_sctpmap: function (line)
  6440. {
  6441. var parts = line.substring(10).split(' ');
  6442. var sctpPort = parts[0];
  6443. var protocol = parts[1];
  6444. // Stream count is optional
  6445. var streamCount = parts.length > 2 ? parts[2] : null;
  6446. return [sctpPort, protocol, streamCount];// SCTP port
  6447. },
  6448. build_rtpmap: function (el) {
  6449. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  6450. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  6451. line += '/' + el.getAttribute('channels');
  6452. }
  6453. return line;
  6454. },
  6455. parse_crypto: function (line) {
  6456. var parts = line.substring(9).split(' '),
  6457. data = {};
  6458. data.tag = parts.shift();
  6459. data['crypto-suite'] = parts.shift();
  6460. data['key-params'] = parts.shift();
  6461. if (parts.length) {
  6462. data['session-params'] = parts.join(' ');
  6463. }
  6464. return data;
  6465. },
  6466. parse_fingerprint: function (line) { // RFC 4572
  6467. var parts = line.substring(14).split(' '),
  6468. data = {};
  6469. data.hash = parts.shift();
  6470. data.fingerprint = parts.shift();
  6471. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  6472. return data;
  6473. },
  6474. parse_fmtp: function (line) {
  6475. var parts = line.split(' '),
  6476. i, key, value,
  6477. data = [];
  6478. parts.shift();
  6479. parts = parts.join(' ').split(';');
  6480. for (i = 0; i < parts.length; i++) {
  6481. key = parts[i].split('=')[0];
  6482. while (key.length && key[0] == ' ') {
  6483. key = key.substring(1);
  6484. }
  6485. value = parts[i].split('=')[1];
  6486. if (key && value) {
  6487. data.push({name: key, value: value});
  6488. } else if (key) {
  6489. // rfc 4733 (DTMF) style stuff
  6490. data.push({name: '', value: key});
  6491. }
  6492. }
  6493. return data;
  6494. },
  6495. parse_icecandidate: function (line) {
  6496. var candidate = {},
  6497. elems = line.split(' ');
  6498. candidate.foundation = elems[0].substring(12);
  6499. candidate.component = elems[1];
  6500. candidate.protocol = elems[2].toLowerCase();
  6501. candidate.priority = elems[3];
  6502. candidate.ip = elems[4];
  6503. candidate.port = elems[5];
  6504. // elems[6] => "typ"
  6505. candidate.type = elems[7];
  6506. candidate.generation = 0; // default value, may be overwritten below
  6507. for (var i = 8; i < elems.length; i += 2) {
  6508. switch (elems[i]) {
  6509. case 'raddr':
  6510. candidate['rel-addr'] = elems[i + 1];
  6511. break;
  6512. case 'rport':
  6513. candidate['rel-port'] = elems[i + 1];
  6514. break;
  6515. case 'generation':
  6516. candidate.generation = elems[i + 1];
  6517. break;
  6518. case 'tcptype':
  6519. candidate.tcptype = elems[i + 1];
  6520. break;
  6521. default: // TODO
  6522. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  6523. }
  6524. }
  6525. candidate.network = '1';
  6526. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  6527. return candidate;
  6528. },
  6529. build_icecandidate: function (cand) {
  6530. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  6531. line += ' ';
  6532. switch (cand.type) {
  6533. case 'srflx':
  6534. case 'prflx':
  6535. case 'relay':
  6536. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  6537. line += 'raddr';
  6538. line += ' ';
  6539. line += cand['rel-addr'];
  6540. line += ' ';
  6541. line += 'rport';
  6542. line += ' ';
  6543. line += cand['rel-port'];
  6544. line += ' ';
  6545. }
  6546. break;
  6547. }
  6548. if (cand.hasOwnAttribute('tcptype')) {
  6549. line += 'tcptype';
  6550. line += ' ';
  6551. line += cand.tcptype;
  6552. line += ' ';
  6553. }
  6554. line += 'generation';
  6555. line += ' ';
  6556. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  6557. return line;
  6558. },
  6559. parse_ssrc: function (desc) {
  6560. // proprietary mapping of a=ssrc lines
  6561. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  6562. // and parse according to that
  6563. var lines = desc.split('\r\n'),
  6564. data = {};
  6565. for (var i = 0; i < lines.length; i++) {
  6566. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  6567. var idx = lines[i].indexOf(' ');
  6568. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  6569. }
  6570. }
  6571. return data;
  6572. },
  6573. parse_rtcpfb: function (line) {
  6574. var parts = line.substr(10).split(' ');
  6575. var data = {};
  6576. data.pt = parts.shift();
  6577. data.type = parts.shift();
  6578. data.params = parts;
  6579. return data;
  6580. },
  6581. parse_extmap: function (line) {
  6582. var parts = line.substr(9).split(' ');
  6583. var data = {};
  6584. data.value = parts.shift();
  6585. if (data.value.indexOf('/') != -1) {
  6586. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  6587. data.value = data.value.substr(0, data.value.indexOf('/'));
  6588. } else {
  6589. data.direction = 'both';
  6590. }
  6591. data.uri = parts.shift();
  6592. data.params = parts;
  6593. return data;
  6594. },
  6595. find_line: function (haystack, needle, sessionpart) {
  6596. var lines = haystack.split('\r\n');
  6597. for (var i = 0; i < lines.length; i++) {
  6598. if (lines[i].substring(0, needle.length) == needle) {
  6599. return lines[i];
  6600. }
  6601. }
  6602. if (!sessionpart) {
  6603. return false;
  6604. }
  6605. // search session part
  6606. lines = sessionpart.split('\r\n');
  6607. for (var j = 0; j < lines.length; j++) {
  6608. if (lines[j].substring(0, needle.length) == needle) {
  6609. return lines[j];
  6610. }
  6611. }
  6612. return false;
  6613. },
  6614. find_lines: function (haystack, needle, sessionpart) {
  6615. var lines = haystack.split('\r\n'),
  6616. needles = [];
  6617. for (var i = 0; i < lines.length; i++) {
  6618. if (lines[i].substring(0, needle.length) == needle)
  6619. needles.push(lines[i]);
  6620. }
  6621. if (needles.length || !sessionpart) {
  6622. return needles;
  6623. }
  6624. // search session part
  6625. lines = sessionpart.split('\r\n');
  6626. for (var j = 0; j < lines.length; j++) {
  6627. if (lines[j].substring(0, needle.length) == needle) {
  6628. needles.push(lines[j]);
  6629. }
  6630. }
  6631. return needles;
  6632. },
  6633. candidateToJingle: function (line) {
  6634. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  6635. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  6636. if (line.indexOf('candidate:') === 0) {
  6637. line = 'a=' + line;
  6638. } else if (line.substring(0, 12) != 'a=candidate:') {
  6639. console.log('parseCandidate called with a line that is not a candidate line');
  6640. console.log(line);
  6641. return null;
  6642. }
  6643. if (line.substring(line.length - 2) == '\r\n') // chomp it
  6644. line = line.substring(0, line.length - 2);
  6645. var candidate = {},
  6646. elems = line.split(' '),
  6647. i;
  6648. if (elems[6] != 'typ') {
  6649. console.log('did not find typ in the right place');
  6650. console.log(line);
  6651. return null;
  6652. }
  6653. candidate.foundation = elems[0].substring(12);
  6654. candidate.component = elems[1];
  6655. candidate.protocol = elems[2].toLowerCase();
  6656. candidate.priority = elems[3];
  6657. candidate.ip = elems[4];
  6658. candidate.port = elems[5];
  6659. // elems[6] => "typ"
  6660. candidate.type = elems[7];
  6661. candidate.generation = '0'; // default, may be overwritten below
  6662. for (i = 8; i < elems.length; i += 2) {
  6663. switch (elems[i]) {
  6664. case 'raddr':
  6665. candidate['rel-addr'] = elems[i + 1];
  6666. break;
  6667. case 'rport':
  6668. candidate['rel-port'] = elems[i + 1];
  6669. break;
  6670. case 'generation':
  6671. candidate.generation = elems[i + 1];
  6672. break;
  6673. case 'tcptype':
  6674. candidate.tcptype = elems[i + 1];
  6675. break;
  6676. default: // TODO
  6677. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  6678. }
  6679. }
  6680. candidate.network = '1';
  6681. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  6682. return candidate;
  6683. },
  6684. candidateFromJingle: function (cand) {
  6685. var line = 'a=candidate:';
  6686. line += cand.getAttribute('foundation');
  6687. line += ' ';
  6688. line += cand.getAttribute('component');
  6689. line += ' ';
  6690. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  6691. line += ' ';
  6692. line += cand.getAttribute('priority');
  6693. line += ' ';
  6694. line += cand.getAttribute('ip');
  6695. line += ' ';
  6696. line += cand.getAttribute('port');
  6697. line += ' ';
  6698. line += 'typ';
  6699. line += ' ' + cand.getAttribute('type');
  6700. line += ' ';
  6701. switch (cand.getAttribute('type')) {
  6702. case 'srflx':
  6703. case 'prflx':
  6704. case 'relay':
  6705. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  6706. line += 'raddr';
  6707. line += ' ';
  6708. line += cand.getAttribute('rel-addr');
  6709. line += ' ';
  6710. line += 'rport';
  6711. line += ' ';
  6712. line += cand.getAttribute('rel-port');
  6713. line += ' ';
  6714. }
  6715. break;
  6716. }
  6717. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  6718. line += 'tcptype';
  6719. line += ' ';
  6720. line += cand.getAttribute('tcptype');
  6721. line += ' ';
  6722. }
  6723. line += 'generation';
  6724. line += ' ';
  6725. line += cand.getAttribute('generation') || '0';
  6726. return line + '\r\n';
  6727. }
  6728. };
  6729. module.exports = SDPUtil;
  6730. },{}],26:[function(require,module,exports){
  6731. var RTC = require('../RTC/RTC');
  6732. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  6733. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6734. var SSRCReplacement = require("./LocalSSRCReplacement");
  6735. function TraceablePeerConnection(ice_config, constraints, session) {
  6736. var self = this;
  6737. this.session = session;
  6738. var RTCPeerConnectionType = null;
  6739. if (RTCBrowserType.isFirefox()) {
  6740. RTCPeerConnectionType = mozRTCPeerConnection;
  6741. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  6742. RTCPeerConnectionType = RTCPeerConnection;
  6743. } else {
  6744. RTCPeerConnectionType = webkitRTCPeerConnection;
  6745. }
  6746. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  6747. this.updateLog = [];
  6748. this.stats = {};
  6749. this.statsinterval = null;
  6750. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  6751. var Interop = require('sdp-interop').Interop;
  6752. this.interop = new Interop();
  6753. var Simulcast = require('sdp-simulcast');
  6754. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  6755. // override as desired
  6756. this.trace = function (what, info) {
  6757. /*console.warn('WTRACE', what, info);
  6758. if (info && RTCBrowserType.isIExplorer()) {
  6759. if (info.length > 1024) {
  6760. console.warn('WTRACE', what, info.substr(1024));
  6761. }
  6762. if (info.length > 2048) {
  6763. console.warn('WTRACE', what, info.substr(2048));
  6764. }
  6765. }*/
  6766. self.updateLog.push({
  6767. time: new Date(),
  6768. type: what,
  6769. value: info || ""
  6770. });
  6771. };
  6772. this.onicecandidate = null;
  6773. this.peerconnection.onicecandidate = function (event) {
  6774. // FIXME: this causes stack overflow with Temasys Plugin
  6775. if (!RTCBrowserType.isTemasysPluginUsed())
  6776. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  6777. if (self.onicecandidate !== null) {
  6778. self.onicecandidate(event);
  6779. }
  6780. };
  6781. this.onaddstream = null;
  6782. this.peerconnection.onaddstream = function (event) {
  6783. self.trace('onaddstream', event.stream.id);
  6784. if (self.onaddstream !== null) {
  6785. self.onaddstream(event);
  6786. }
  6787. };
  6788. this.onremovestream = null;
  6789. this.peerconnection.onremovestream = function (event) {
  6790. self.trace('onremovestream', event.stream.id);
  6791. if (self.onremovestream !== null) {
  6792. self.onremovestream(event);
  6793. }
  6794. };
  6795. this.onsignalingstatechange = null;
  6796. this.peerconnection.onsignalingstatechange = function (event) {
  6797. self.trace('onsignalingstatechange', self.signalingState);
  6798. if (self.onsignalingstatechange !== null) {
  6799. self.onsignalingstatechange(event);
  6800. }
  6801. };
  6802. this.oniceconnectionstatechange = null;
  6803. this.peerconnection.oniceconnectionstatechange = function (event) {
  6804. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  6805. if (self.oniceconnectionstatechange !== null) {
  6806. self.oniceconnectionstatechange(event);
  6807. }
  6808. };
  6809. this.onnegotiationneeded = null;
  6810. this.peerconnection.onnegotiationneeded = function (event) {
  6811. self.trace('onnegotiationneeded');
  6812. if (self.onnegotiationneeded !== null) {
  6813. self.onnegotiationneeded(event);
  6814. }
  6815. };
  6816. self.ondatachannel = null;
  6817. this.peerconnection.ondatachannel = function (event) {
  6818. self.trace('ondatachannel', event);
  6819. if (self.ondatachannel !== null) {
  6820. self.ondatachannel(event);
  6821. }
  6822. };
  6823. // XXX: do all non-firefox browsers which we support also support this?
  6824. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  6825. this.statsinterval = window.setInterval(function() {
  6826. self.peerconnection.getStats(function(stats) {
  6827. var results = stats.result();
  6828. var now = new Date();
  6829. for (var i = 0; i < results.length; ++i) {
  6830. results[i].names().forEach(function (name) {
  6831. var id = results[i].id + '-' + name;
  6832. if (!self.stats[id]) {
  6833. self.stats[id] = {
  6834. startTime: now,
  6835. endTime: now,
  6836. values: [],
  6837. times: []
  6838. };
  6839. }
  6840. self.stats[id].values.push(results[i].stat(name));
  6841. self.stats[id].times.push(now.getTime());
  6842. if (self.stats[id].values.length > self.maxstats) {
  6843. self.stats[id].values.shift();
  6844. self.stats[id].times.shift();
  6845. }
  6846. self.stats[id].endTime = now;
  6847. });
  6848. }
  6849. });
  6850. }, 1000);
  6851. }
  6852. }
  6853. /**
  6854. * Returns a string representation of a SessionDescription object.
  6855. */
  6856. var dumpSDP = function(description) {
  6857. if (typeof description === 'undefined' || description == null) {
  6858. return '';
  6859. }
  6860. return 'type: ' + description.type + '\r\n' + description.sdp;
  6861. };
  6862. /**
  6863. * Takes a SessionDescription object and returns a "normalized" version.
  6864. * Currently it only takes care of ordering the a=ssrc lines.
  6865. */
  6866. var normalizePlanB = function(desc) {
  6867. if (typeof desc !== 'object' || desc === null ||
  6868. typeof desc.sdp !== 'string') {
  6869. console.warn('An empty description was passed as an argument.');
  6870. return desc;
  6871. }
  6872. var transform = require('sdp-transform');
  6873. var session = transform.parse(desc.sdp);
  6874. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  6875. Array.isArray(session.media)) {
  6876. session.media.forEach(function (mLine) {
  6877. // Chrome appears to be picky about the order in which a=ssrc lines
  6878. // are listed in an m-line when rtx is enabled (and thus there are
  6879. // a=ssrc-group lines with FID semantics). Specifically if we have
  6880. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  6881. // the "a=ssrc:S1" lines, SRD fails.
  6882. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  6883. // first.
  6884. var firstSsrcs = [];
  6885. var newSsrcLines = [];
  6886. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  6887. mLine.ssrcGroups.forEach(function (group) {
  6888. if (typeof group.semantics !== 'undefined' &&
  6889. group.semantics === 'FID') {
  6890. if (typeof group.ssrcs !== 'undefined') {
  6891. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  6892. }
  6893. }
  6894. });
  6895. }
  6896. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  6897. for (var i = 0; i<mLine.ssrcs.length; i++){
  6898. if (typeof mLine.ssrcs[i] === 'object'
  6899. && typeof mLine.ssrcs[i].id !== 'undefined'
  6900. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  6901. newSsrcLines.push(mLine.ssrcs[i]);
  6902. delete mLine.ssrcs[i];
  6903. }
  6904. }
  6905. for (var i = 0; i<mLine.ssrcs.length; i++){
  6906. if (typeof mLine.ssrcs[i] !== 'undefined') {
  6907. newSsrcLines.push(mLine.ssrcs[i]);
  6908. }
  6909. }
  6910. mLine.ssrcs = newSsrcLines;
  6911. }
  6912. });
  6913. }
  6914. var resStr = transform.write(session);
  6915. return new RTCSessionDescription({
  6916. type: desc.type,
  6917. sdp: resStr
  6918. });
  6919. };
  6920. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  6921. TraceablePeerConnection.prototype.__defineGetter__(
  6922. 'signalingState',
  6923. function() { return this.peerconnection.signalingState; });
  6924. TraceablePeerConnection.prototype.__defineGetter__(
  6925. 'iceConnectionState',
  6926. function() { return this.peerconnection.iceConnectionState; });
  6927. TraceablePeerConnection.prototype.__defineGetter__(
  6928. 'localDescription',
  6929. function() {
  6930. var desc = this.peerconnection.localDescription;
  6931. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  6932. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  6933. // if we're running on FF, transform to Plan B first.
  6934. if (RTCBrowserType.usesUnifiedPlan()) {
  6935. desc = this.interop.toPlanB(desc);
  6936. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  6937. }
  6938. return desc;
  6939. });
  6940. TraceablePeerConnection.prototype.__defineGetter__(
  6941. 'remoteDescription',
  6942. function() {
  6943. var desc = this.peerconnection.remoteDescription;
  6944. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  6945. // if we're running on FF, transform to Plan B first.
  6946. if (RTCBrowserType.usesUnifiedPlan()) {
  6947. desc = this.interop.toPlanB(desc);
  6948. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  6949. }
  6950. return desc;
  6951. });
  6952. }
  6953. TraceablePeerConnection.prototype.addStream = function (stream) {
  6954. this.trace('addStream', stream.id);
  6955. try
  6956. {
  6957. this.peerconnection.addStream(stream);
  6958. }
  6959. catch (e)
  6960. {
  6961. console.error(e);
  6962. }
  6963. };
  6964. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  6965. this.trace('removeStream', stream.id);
  6966. if(stopStreams) {
  6967. stream.getAudioTracks().forEach(function (track) {
  6968. // stop() not supported with IE
  6969. if (track.stop) {
  6970. track.stop();
  6971. }
  6972. });
  6973. stream.getVideoTracks().forEach(function (track) {
  6974. // stop() not supported with IE
  6975. if (track.stop) {
  6976. track.stop();
  6977. }
  6978. });
  6979. if (stream.stop) {
  6980. stream.stop();
  6981. }
  6982. }
  6983. try {
  6984. // FF doesn't support this yet.
  6985. if (this.peerconnection.removeStream)
  6986. this.peerconnection.removeStream(stream);
  6987. } catch (e) {
  6988. console.error(e);
  6989. }
  6990. };
  6991. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  6992. this.trace('createDataChannel', label, opts);
  6993. return this.peerconnection.createDataChannel(label, opts);
  6994. };
  6995. TraceablePeerConnection.prototype.setLocalDescription
  6996. = function (description, successCallback, failureCallback) {
  6997. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  6998. // if we're running on FF, transform to Plan A first.
  6999. if (RTCBrowserType.usesUnifiedPlan()) {
  7000. description = this.interop.toUnifiedPlan(description);
  7001. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  7002. }
  7003. var self = this;
  7004. this.peerconnection.setLocalDescription(description,
  7005. function () {
  7006. self.trace('setLocalDescriptionOnSuccess');
  7007. successCallback();
  7008. },
  7009. function (err) {
  7010. self.trace('setLocalDescriptionOnFailure', err);
  7011. failureCallback(err);
  7012. }
  7013. );
  7014. /*
  7015. if (this.statsinterval === null && this.maxstats > 0) {
  7016. // start gathering stats
  7017. }
  7018. */
  7019. };
  7020. TraceablePeerConnection.prototype.setRemoteDescription
  7021. = function (description, successCallback, failureCallback) {
  7022. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  7023. // TODO the focus should squeze or explode the remote simulcast
  7024. description = this.simulcast.mungeRemoteDescription(description);
  7025. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  7026. // if we're running on FF, transform to Plan A first.
  7027. if (RTCBrowserType.usesUnifiedPlan()) {
  7028. description = this.interop.toUnifiedPlan(description);
  7029. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  7030. }
  7031. if (RTCBrowserType.usesPlanB()) {
  7032. description = normalizePlanB(description);
  7033. }
  7034. var self = this;
  7035. this.peerconnection.setRemoteDescription(description,
  7036. function () {
  7037. self.trace('setRemoteDescriptionOnSuccess');
  7038. successCallback();
  7039. },
  7040. function (err) {
  7041. self.trace('setRemoteDescriptionOnFailure', err);
  7042. failureCallback(err);
  7043. }
  7044. );
  7045. /*
  7046. if (this.statsinterval === null && this.maxstats > 0) {
  7047. // start gathering stats
  7048. }
  7049. */
  7050. };
  7051. TraceablePeerConnection.prototype.close = function () {
  7052. this.trace('stop');
  7053. if (this.statsinterval !== null) {
  7054. window.clearInterval(this.statsinterval);
  7055. this.statsinterval = null;
  7056. }
  7057. this.peerconnection.close();
  7058. };
  7059. TraceablePeerConnection.prototype.createOffer
  7060. = function (successCallback, failureCallback, constraints) {
  7061. var self = this;
  7062. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  7063. this.peerconnection.createOffer(
  7064. function (offer) {
  7065. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  7066. // NOTE this is not tested because in meet the focus generates the
  7067. // offer.
  7068. // if we're running on FF, transform to Plan B first.
  7069. if (RTCBrowserType.usesUnifiedPlan()) {
  7070. offer = self.interop.toPlanB(offer);
  7071. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  7072. }
  7073. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  7074. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  7075. offer = self.simulcast.mungeLocalDescription(offer);
  7076. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  7077. }
  7078. successCallback(offer);
  7079. },
  7080. function(err) {
  7081. self.trace('createOfferOnFailure', err);
  7082. failureCallback(err);
  7083. },
  7084. constraints
  7085. );
  7086. };
  7087. TraceablePeerConnection.prototype.createAnswer
  7088. = function (successCallback, failureCallback, constraints) {
  7089. var self = this;
  7090. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  7091. this.peerconnection.createAnswer(
  7092. function (answer) {
  7093. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  7094. // if we're running on FF, transform to Plan A first.
  7095. if (RTCBrowserType.usesUnifiedPlan()) {
  7096. answer = self.interop.toPlanB(answer);
  7097. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  7098. }
  7099. // munge local video SSRC
  7100. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  7101. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  7102. answer = self.simulcast.mungeLocalDescription(answer);
  7103. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  7104. }
  7105. successCallback(answer);
  7106. },
  7107. function(err) {
  7108. self.trace('createAnswerOnFailure', err);
  7109. failureCallback(err);
  7110. },
  7111. constraints
  7112. );
  7113. };
  7114. TraceablePeerConnection.prototype.addIceCandidate
  7115. = function (candidate, successCallback, failureCallback) {
  7116. //var self = this;
  7117. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  7118. this.peerconnection.addIceCandidate(candidate);
  7119. /* maybe later
  7120. this.peerconnection.addIceCandidate(candidate,
  7121. function () {
  7122. self.trace('addIceCandidateOnSuccess');
  7123. successCallback();
  7124. },
  7125. function (err) {
  7126. self.trace('addIceCandidateOnFailure', err);
  7127. failureCallback(err);
  7128. }
  7129. );
  7130. */
  7131. };
  7132. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  7133. // TODO: Is this the correct way to handle Opera, Temasys?
  7134. if (RTCBrowserType.isFirefox()) {
  7135. // ignore for now...
  7136. if(!errback)
  7137. errback = function () {};
  7138. this.peerconnection.getStats(null, callback, errback);
  7139. } else {
  7140. this.peerconnection.getStats(callback);
  7141. }
  7142. };
  7143. module.exports = TraceablePeerConnection;
  7144. },{"../../service/xmpp/XMPPEvents":76,"../RTC/RTC":13,"../RTC/RTCBrowserType.js":14,"./LocalSSRCReplacement":22,"sdp-interop":53,"sdp-simulcast":60,"sdp-transform":67}],27:[function(require,module,exports){
  7145. /* global $, $iq, APP, config, messageHandler,
  7146. roomName, sessionTerminated, Strophe, Util */
  7147. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7148. var Settings = require("../settings/Settings");
  7149. var AuthenticationEvents
  7150. = require("../../service/authentication/AuthenticationEvents");
  7151. function createExpBackoffTimer(step) {
  7152. var count = 1;
  7153. return function (reset) {
  7154. // Reset call
  7155. if (reset) {
  7156. count = 1;
  7157. return;
  7158. }
  7159. // Calculate next timeout
  7160. var timeout = Math.pow(2, count - 1);
  7161. count += 1;
  7162. return timeout * step;
  7163. };
  7164. }
  7165. function Moderator(roomName, xmpp, emitter) {
  7166. this.roomName = roomName;
  7167. this.xmppService = xmpp;
  7168. this.getNextTimeout = createExpBackoffTimer(1000);
  7169. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  7170. // External authentication stuff
  7171. this.externalAuthEnabled = false;
  7172. this.settings = new Settings(roomName);
  7173. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  7174. // it will be enabled automatically if focus detects the component through
  7175. // service discovery.
  7176. this.sipGatewayEnabled = this.xmppService.options.hosts.call_control !== undefined;
  7177. this.eventEmitter = emitter;
  7178. this.connection = this.xmppService.connection;
  7179. this.focusUserJid;
  7180. //FIXME:
  7181. // Message listener that talks to POPUP window
  7182. function listener(event) {
  7183. if (event.data && event.data.sessionId) {
  7184. if (event.origin !== window.location.origin) {
  7185. console.warn("Ignoring sessionId from different origin: " +
  7186. event.origin);
  7187. return;
  7188. }
  7189. localStorage.setItem('sessionId', event.data.sessionId);
  7190. // After popup is closed we will authenticate
  7191. }
  7192. }
  7193. // Register
  7194. if (window.addEventListener) {
  7195. window.addEventListener("message", listener, false);
  7196. } else {
  7197. window.attachEvent("onmessage", listener);
  7198. }
  7199. }
  7200. Moderator.prototype.isExternalAuthEnabled = function () {
  7201. return this.externalAuthEnabled;
  7202. };
  7203. Moderator.prototype.isSipGatewayEnabled = function () {
  7204. return this.sipGatewayEnabled;
  7205. };
  7206. Moderator.prototype.onMucMemberLeft = function (jid) {
  7207. console.info("Someone left is it focus ? " + jid);
  7208. var resource = Strophe.getResourceFromJid(jid);
  7209. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  7210. console.info(
  7211. "Focus has left the room - leaving conference");
  7212. //hangUp();
  7213. // We'd rather reload to have everything re-initialized
  7214. //FIXME: show some message before reload
  7215. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  7216. }
  7217. };
  7218. Moderator.prototype.setFocusUserJid = function (focusJid) {
  7219. if (!this.focusUserJid) {
  7220. this.focusUserJid = focusJid;
  7221. console.info("Focus jid set to: " + this.focusUserJid);
  7222. }
  7223. };
  7224. Moderator.prototype.getFocusUserJid = function () {
  7225. return this.focusUserJid;
  7226. };
  7227. Moderator.prototype.getFocusComponent = function () {
  7228. // Get focus component address
  7229. var focusComponent = this.xmppService.options.hosts.focus;
  7230. // If not specified use default: 'focus.domain'
  7231. if (!focusComponent) {
  7232. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  7233. }
  7234. return focusComponent;
  7235. };
  7236. Moderator.prototype.createConferenceIq = function () {
  7237. // Generate create conference IQ
  7238. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  7239. // Session Id used for authentication
  7240. var sessionId = localStorage.getItem('sessionId');
  7241. var machineUID = this.settings.getSettings().uid;
  7242. console.info(
  7243. "Session ID: " + sessionId + " machine UID: " + machineUID);
  7244. elem.c('conference', {
  7245. xmlns: 'http://jitsi.org/protocol/focus',
  7246. room: this.roomName,
  7247. 'machine-uid': machineUID
  7248. });
  7249. if (sessionId) {
  7250. elem.attrs({ 'session-id': sessionId});
  7251. }
  7252. if (this.xmppService.options.hosts.bridge !== undefined) {
  7253. elem.c(
  7254. 'property',
  7255. {name: 'bridge',value: this.xmppService.options.hosts.bridge})
  7256. .up();
  7257. }
  7258. // Tell the focus we have Jigasi configured
  7259. if (this.xmppService.options.hosts.call_control !== undefined) {
  7260. elem.c(
  7261. 'property',
  7262. {name: 'call_control',value: this.xmppService.options.hosts.call_control})
  7263. .up();
  7264. }
  7265. if (this.xmppService.options.channelLastN !== undefined) {
  7266. elem.c(
  7267. 'property',
  7268. {name: 'channelLastN',value: this.xmppService.options.channelLastN})
  7269. .up();
  7270. }
  7271. if (this.xmppService.options.adaptiveLastN !== undefined) {
  7272. elem.c(
  7273. 'property',
  7274. {name: 'adaptiveLastN',value: this.xmppService.options.adaptiveLastN})
  7275. .up();
  7276. }
  7277. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  7278. elem.c(
  7279. 'property',
  7280. {name: 'adaptiveSimulcast',value: this.xmppService.options.adaptiveSimulcast})
  7281. .up();
  7282. }
  7283. if (this.xmppService.options.openSctp !== undefined) {
  7284. elem.c(
  7285. 'property',
  7286. {name: 'openSctp',value: this.xmppService.options.openSctp})
  7287. .up();
  7288. }
  7289. if(this.xmppService.options.startAudioMuted !== undefined)
  7290. {
  7291. elem.c(
  7292. 'property',
  7293. {name: 'startAudioMuted',value: this.xmppService.options.startAudioMuted})
  7294. .up();
  7295. }
  7296. if(this.xmppService.options.startVideoMuted !== undefined)
  7297. {
  7298. elem.c(
  7299. 'property',
  7300. {name: 'startVideoMuted',value: this.xmppService.options.startVideoMuted})
  7301. .up();
  7302. }
  7303. elem.c(
  7304. 'property',
  7305. {name: 'simulcastMode',value: 'rewriting'})
  7306. .up();
  7307. elem.up();
  7308. return elem;
  7309. };
  7310. Moderator.prototype.parseSessionId = function (resultIq) {
  7311. var sessionId = $(resultIq).find('conference').attr('session-id');
  7312. if (sessionId) {
  7313. console.info('Received sessionId: ' + sessionId);
  7314. localStorage.setItem('sessionId', sessionId);
  7315. }
  7316. };
  7317. Moderator.prototype.parseConfigOptions = function (resultIq) {
  7318. this.setFocusUserJid(
  7319. $(resultIq).find('conference').attr('focusjid'));
  7320. var authenticationEnabled
  7321. = $(resultIq).find(
  7322. '>conference>property' +
  7323. '[name=\'authentication\'][value=\'true\']').length > 0;
  7324. console.info("Authentication enabled: " + authenticationEnabled);
  7325. this.externalAuthEnabled = $(resultIq).find(
  7326. '>conference>property' +
  7327. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  7328. console.info('External authentication enabled: ' + this.externalAuthEnabled);
  7329. if (!this.externalAuthEnabled) {
  7330. // We expect to receive sessionId in 'internal' authentication mode
  7331. this.parseSessionId(resultIq);
  7332. }
  7333. var authIdentity = $(resultIq).find('>conference').attr('identity');
  7334. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  7335. authenticationEnabled, authIdentity);
  7336. // Check if focus has auto-detected Jigasi component(this will be also
  7337. // included if we have passed our host from the config)
  7338. if ($(resultIq).find(
  7339. '>conference>property' +
  7340. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  7341. this.sipGatewayEnabled = true;
  7342. }
  7343. console.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  7344. };
  7345. // FIXME = we need to show the fact that we're waiting for the focus
  7346. // to the user(or that focus is not available)
  7347. Moderator.prototype.allocateConferenceFocus = function ( callback) {
  7348. // Try to use focus user JID from the config
  7349. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  7350. // Send create conference IQ
  7351. var iq = this.createConferenceIq();
  7352. var self = this;
  7353. this.connection.sendIQ(
  7354. iq,
  7355. function (result) {
  7356. // Setup config options
  7357. self.parseConfigOptions(result);
  7358. if ('true' === $(result).find('conference').attr('ready')) {
  7359. // Reset both timers
  7360. self.getNextTimeout(true);
  7361. self.getNextErrorTimeout(true);
  7362. // Exec callback
  7363. callback();
  7364. } else {
  7365. var waitMs = self.getNextTimeout();
  7366. console.info("Waiting for the focus... " + waitMs);
  7367. // Reset error timeout
  7368. self.getNextErrorTimeout(true);
  7369. window.setTimeout(
  7370. function () {
  7371. self.allocateConferenceFocus(callback);
  7372. }, waitMs);
  7373. }
  7374. },
  7375. function (error) {
  7376. // Invalid session ? remove and try again
  7377. // without session ID to get a new one
  7378. var invalidSession
  7379. = $(error).find('>error>session-invalid').length;
  7380. if (invalidSession) {
  7381. console.info("Session expired! - removing");
  7382. localStorage.removeItem("sessionId");
  7383. }
  7384. if ($(error).find('>error>graceful-shutdown').length) {
  7385. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  7386. return;
  7387. }
  7388. // Check for error returned by the reservation system
  7389. var reservationErr = $(error).find('>error>reservation-error');
  7390. if (reservationErr.length) {
  7391. // Trigger error event
  7392. var errorCode = reservationErr.attr('error-code');
  7393. var errorMsg;
  7394. if ($(error).find('>error>text')) {
  7395. errorMsg = $(error).find('>error>text').text();
  7396. }
  7397. self.eventEmitter.emit(
  7398. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  7399. return;
  7400. }
  7401. // Not authorized to create new room
  7402. if ($(error).find('>error>not-authorized').length) {
  7403. console.warn("Unauthorized to start the conference", error);
  7404. var toDomain
  7405. = Strophe.getDomainFromJid(error.getAttribute('to'));
  7406. if (toDomain !== this.xmppService.options.hosts.anonymousdomain) {
  7407. //FIXME: "is external" should come either from
  7408. // the focus or config.js
  7409. self.externalAuthEnabled = true;
  7410. }
  7411. self.eventEmitter.emit(
  7412. XMPPEvents.AUTHENTICATION_REQUIRED,
  7413. function () {
  7414. self.allocateConferenceFocus(
  7415. callback);
  7416. });
  7417. return;
  7418. }
  7419. var waitMs = self.getNextErrorTimeout();
  7420. console.error("Focus error, retry after " + waitMs, error);
  7421. // Show message
  7422. var focusComponent = self.getFocusComponent();
  7423. var retrySec = waitMs / 1000;
  7424. //FIXME: message is duplicated ?
  7425. // Do not show in case of session invalid
  7426. // which means just a retry
  7427. if (!invalidSession) {
  7428. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  7429. focusComponent, retrySec);
  7430. }
  7431. // Reset response timeout
  7432. self.getNextTimeout(true);
  7433. window.setTimeout(
  7434. function () {
  7435. self.allocateConferenceFocus(callback);
  7436. }, waitMs);
  7437. }
  7438. );
  7439. };
  7440. Moderator.prototype.getLoginUrl = function (urlCallback) {
  7441. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  7442. iq.c('login-url', {
  7443. xmlns: 'http://jitsi.org/protocol/focus',
  7444. room: this.roomName,
  7445. 'machine-uid': this.settings.getSettings().uid
  7446. });
  7447. this.connection.sendIQ(
  7448. iq,
  7449. function (result) {
  7450. var url = $(result).find('login-url').attr('url');
  7451. url = url = decodeURIComponent(url);
  7452. if (url) {
  7453. console.info("Got auth url: " + url);
  7454. urlCallback(url);
  7455. } else {
  7456. console.error(
  7457. "Failed to get auth url from the focus", result);
  7458. }
  7459. },
  7460. function (error) {
  7461. console.error("Get auth url error", error);
  7462. }
  7463. );
  7464. };
  7465. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  7466. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  7467. iq.c('login-url', {
  7468. xmlns: 'http://jitsi.org/protocol/focus',
  7469. room: this.roomName,
  7470. 'machine-uid': this.settings.getSettings().uid,
  7471. popup: true
  7472. });
  7473. this.connection.sendIQ(
  7474. iq,
  7475. function (result) {
  7476. var url = $(result).find('login-url').attr('url');
  7477. url = url = decodeURIComponent(url);
  7478. if (url) {
  7479. console.info("Got POPUP auth url: " + url);
  7480. urlCallback(url);
  7481. } else {
  7482. console.error(
  7483. "Failed to get POPUP auth url from the focus", result);
  7484. }
  7485. },
  7486. function (error) {
  7487. console.error('Get POPUP auth url error', error);
  7488. }
  7489. );
  7490. };
  7491. Moderator.prototype.logout = function (callback) {
  7492. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  7493. var sessionId = localStorage.getItem('sessionId');
  7494. if (!sessionId) {
  7495. callback();
  7496. return;
  7497. }
  7498. iq.c('logout', {
  7499. xmlns: 'http://jitsi.org/protocol/focus',
  7500. 'session-id': sessionId
  7501. });
  7502. this.connection.sendIQ(
  7503. iq,
  7504. function (result) {
  7505. var logoutUrl = $(result).find('logout').attr('logout-url');
  7506. if (logoutUrl) {
  7507. logoutUrl = decodeURIComponent(logoutUrl);
  7508. }
  7509. console.info("Log out OK, url: " + logoutUrl, result);
  7510. localStorage.removeItem('sessionId');
  7511. callback(logoutUrl);
  7512. },
  7513. function (error) {
  7514. console.error("Logout error", error);
  7515. }
  7516. );
  7517. };
  7518. module.exports = Moderator;
  7519. },{"../../service/authentication/AuthenticationEvents":74,"../../service/xmpp/XMPPEvents":76,"../settings/Settings":18}],28:[function(require,module,exports){
  7520. /* jshint -W117 */
  7521. /* a simple MUC connection plugin
  7522. * can only handle a single MUC room
  7523. */
  7524. var ChatRoom = require("./ChatRoom");
  7525. module.exports = function(XMPP) {
  7526. Strophe.addConnectionPlugin('emuc', {
  7527. connection: null,
  7528. rooms: {},//map with the rooms
  7529. init: function (conn) {
  7530. this.connection = conn;
  7531. // add handlers (just once)
  7532. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  7533. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  7534. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  7535. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  7536. },
  7537. createRoom: function (jid, password, options) {
  7538. var roomJid = Strophe.getBareJidFromJid(jid);
  7539. if (this.rooms[roomJid]) {
  7540. console.error("You are already in the room!");
  7541. return;
  7542. }
  7543. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  7544. return this.rooms[roomJid];
  7545. },
  7546. doLeave: function (jid) {
  7547. this.rooms[jid].doLeave();
  7548. delete this.rooms[jid];
  7549. },
  7550. onPresence: function (pres) {
  7551. var from = pres.getAttribute('from');
  7552. // What is this for? A workaround for something?
  7553. if (pres.getAttribute('type')) {
  7554. return true;
  7555. }
  7556. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7557. if(!room)
  7558. return;
  7559. // Parse status.
  7560. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  7561. room.createNonAnonymousRoom();
  7562. }
  7563. room.onPresence(pres);
  7564. return true;
  7565. },
  7566. onPresenceUnavailable: function (pres) {
  7567. var from = pres.getAttribute('from');
  7568. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7569. if(!room)
  7570. return;
  7571. room.onPresenceUnavailable(pres, from);
  7572. return true;
  7573. },
  7574. onPresenceError: function (pres) {
  7575. var from = pres.getAttribute('from');
  7576. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7577. if(!room)
  7578. return;
  7579. room.onPresenceError(pres, from);
  7580. return true;
  7581. },
  7582. onMessage: function (msg) {
  7583. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  7584. var from = msg.getAttribute('from');
  7585. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7586. if(!room)
  7587. return;
  7588. room.onMessage(msg, from);
  7589. return true;
  7590. },
  7591. setJingleSession: function (from, session) {
  7592. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7593. if(!room)
  7594. return;
  7595. room.setJingleSession(session);
  7596. }
  7597. });
  7598. };
  7599. },{"./ChatRoom":19}],29:[function(require,module,exports){
  7600. /* jshint -W117 */
  7601. var JingleSession = require("./JingleSessionPC");
  7602. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7603. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7604. module.exports = function(XMPP, eventEmitter) {
  7605. Strophe.addConnectionPlugin('jingle', {
  7606. connection: null,
  7607. sessions: {},
  7608. jid2session: {},
  7609. ice_config: {iceServers: []},
  7610. media_constraints: {
  7611. mandatory: {
  7612. 'OfferToReceiveAudio': true,
  7613. 'OfferToReceiveVideo': true
  7614. }
  7615. // MozDontOfferDataChannel: true when this is firefox
  7616. },
  7617. init: function (conn) {
  7618. this.connection = conn;
  7619. if (this.connection.disco) {
  7620. // http://xmpp.org/extensions/xep-0167.html#support
  7621. // http://xmpp.org/extensions/xep-0176.html#support
  7622. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  7623. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  7624. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  7625. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  7626. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  7627. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  7628. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  7629. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  7630. || RTCBrowserType.isTemasysPluginUsed()) {
  7631. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  7632. }
  7633. // this is dealt with by SDP O/A so we don't need to announce this
  7634. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  7635. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  7636. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  7637. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  7638. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  7639. }
  7640. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  7641. },
  7642. onJingle: function (iq) {
  7643. var sid = $(iq).find('jingle').attr('sid');
  7644. var action = $(iq).find('jingle').attr('action');
  7645. var fromJid = iq.getAttribute('from');
  7646. // send ack first
  7647. var ack = $iq({type: 'result',
  7648. to: fromJid,
  7649. id: iq.getAttribute('id')
  7650. });
  7651. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  7652. var sess = this.sessions[sid];
  7653. if ('session-initiate' != action) {
  7654. if (sess === null) {
  7655. ack.type = 'error';
  7656. ack.c('error', {type: 'cancel'})
  7657. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  7658. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  7659. this.connection.send(ack);
  7660. return true;
  7661. }
  7662. // local jid is not checked
  7663. if (fromJid != sess.peerjid) {
  7664. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  7665. ack.type = 'error';
  7666. ack.c('error', {type: 'cancel'})
  7667. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  7668. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  7669. this.connection.send(ack);
  7670. return true;
  7671. }
  7672. } else if (sess !== undefined) {
  7673. // existing session with same session id
  7674. // this might be out-of-order if the sess.peerjid is the same as from
  7675. ack.type = 'error';
  7676. ack.c('error', {type: 'cancel'})
  7677. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  7678. console.warn('duplicate session id', sid);
  7679. this.connection.send(ack);
  7680. return true;
  7681. }
  7682. // FIXME: check for a defined action
  7683. this.connection.send(ack);
  7684. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  7685. switch (action) {
  7686. case 'session-initiate':
  7687. var startMuted = $(iq).find('jingle>startmuted');
  7688. if (startMuted && startMuted.length > 0) {
  7689. var audioMuted = startMuted.attr("audio");
  7690. var videoMuted = startMuted.attr("video");
  7691. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  7692. audioMuted === "true", videoMuted === "true");
  7693. }
  7694. sess = new JingleSession(
  7695. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  7696. this.connection, XMPP);
  7697. // configure session
  7698. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  7699. this.connection.emuc.setJingleSession(fromBareJid, sess);
  7700. sess.media_constraints = this.media_constraints;
  7701. sess.ice_config = this.ice_config;
  7702. sess.initialize(fromJid, false);
  7703. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  7704. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  7705. sess.setOffer($(iq).find('>jingle'));
  7706. this.sessions[sess.sid] = sess;
  7707. this.jid2session[sess.peerjid] = sess;
  7708. // the callback should either
  7709. // .sendAnswer and .accept
  7710. // or .sendTerminate -- not necessarily synchronous
  7711. sess.sendAnswer();
  7712. sess.accept();
  7713. break;
  7714. case 'session-accept':
  7715. sess.setAnswer($(iq).find('>jingle'));
  7716. sess.accept();
  7717. break;
  7718. case 'session-terminate':
  7719. // If this is not the focus sending the terminate, we have
  7720. // nothing more to do here.
  7721. if (Object.keys(this.sessions).length < 1
  7722. || !(this.sessions[Object.keys(this.sessions)[0]]
  7723. instanceof JingleSession))
  7724. {
  7725. break;
  7726. }
  7727. console.log('terminating...', sess.sid);
  7728. sess.terminate();
  7729. this.terminate(sess.sid);
  7730. if ($(iq).find('>jingle>reason').length) {
  7731. $(document).trigger('callterminated.jingle', [
  7732. sess.sid,
  7733. sess.peerjid,
  7734. $(iq).find('>jingle>reason>:first')[0].tagName,
  7735. $(iq).find('>jingle>reason>text').text()
  7736. ]);
  7737. } else {
  7738. $(document).trigger('callterminated.jingle',
  7739. [sess.sid, sess.peerjid]);
  7740. }
  7741. break;
  7742. case 'transport-info':
  7743. sess.addIceCandidate($(iq).find('>jingle>content'));
  7744. break;
  7745. case 'session-info':
  7746. var affected;
  7747. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7748. $(document).trigger('ringing.jingle', [sess.sid]);
  7749. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7750. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  7751. $(document).trigger('mute.jingle', [sess.sid, affected]);
  7752. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7753. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  7754. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  7755. }
  7756. break;
  7757. case 'addsource': // FIXME: proprietary, un-jingleish
  7758. case 'source-add': // FIXME: proprietary
  7759. sess.addSource($(iq).find('>jingle>content'), fromJid);
  7760. break;
  7761. case 'removesource': // FIXME: proprietary, un-jingleish
  7762. case 'source-remove': // FIXME: proprietary
  7763. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  7764. break;
  7765. default:
  7766. console.warn('jingle action not implemented', action);
  7767. break;
  7768. }
  7769. return true;
  7770. },
  7771. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  7772. if (sid === null || sid === undefined) {
  7773. for (sid in this.sessions) {
  7774. if (this.sessions[sid].state != 'ended') {
  7775. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  7776. this.sessions[sid].terminate();
  7777. }
  7778. delete this.jid2session[this.sessions[sid].peerjid];
  7779. delete this.sessions[sid];
  7780. }
  7781. } else if (this.sessions.hasOwnProperty(sid)) {
  7782. if (this.sessions[sid].state != 'ended') {
  7783. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  7784. this.sessions[sid].terminate();
  7785. }
  7786. delete this.jid2session[this.sessions[sid].peerjid];
  7787. delete this.sessions[sid];
  7788. }
  7789. },
  7790. getStunAndTurnCredentials: function () {
  7791. // get stun and turn configuration from server via xep-0215
  7792. // uses time-limited credentials as described in
  7793. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  7794. //
  7795. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  7796. // for a prosody module which implements this
  7797. //
  7798. // currently, this doesn't work with updateIce and therefore credentials with a long
  7799. // validity have to be fetched before creating the peerconnection
  7800. // TODO: implement refresh via updateIce as described in
  7801. // https://code.google.com/p/webrtc/issues/detail?id=1650
  7802. var self = this;
  7803. this.connection.sendIQ(
  7804. $iq({type: 'get', to: this.connection.domain})
  7805. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  7806. function (res) {
  7807. var iceservers = [];
  7808. $(res).find('>services>service').each(function (idx, el) {
  7809. el = $(el);
  7810. var dict = {};
  7811. var type = el.attr('type');
  7812. switch (type) {
  7813. case 'stun':
  7814. dict.url = 'stun:' + el.attr('host');
  7815. if (el.attr('port')) {
  7816. dict.url += ':' + el.attr('port');
  7817. }
  7818. iceservers.push(dict);
  7819. break;
  7820. case 'turn':
  7821. case 'turns':
  7822. dict.url = type + ':';
  7823. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  7824. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  7825. dict.url += el.attr('username') + '@';
  7826. } else {
  7827. dict.username = el.attr('username'); // only works in M28
  7828. }
  7829. }
  7830. dict.url += el.attr('host');
  7831. if (el.attr('port') && el.attr('port') != '3478') {
  7832. dict.url += ':' + el.attr('port');
  7833. }
  7834. if (el.attr('transport') && el.attr('transport') != 'udp') {
  7835. dict.url += '?transport=' + el.attr('transport');
  7836. }
  7837. if (el.attr('password')) {
  7838. dict.credential = el.attr('password');
  7839. }
  7840. iceservers.push(dict);
  7841. break;
  7842. }
  7843. });
  7844. self.ice_config.iceServers = iceservers;
  7845. },
  7846. function (err) {
  7847. console.warn('getting turn credentials failed', err);
  7848. console.warn('is mod_turncredentials or similar installed?');
  7849. }
  7850. );
  7851. // implement push?
  7852. },
  7853. /**
  7854. * Returns the data saved in 'updateLog' in a format to be logged.
  7855. */
  7856. getLog: function () {
  7857. var data = {};
  7858. var self = this;
  7859. Object.keys(this.sessions).forEach(function (sid) {
  7860. var session = self.sessions[sid];
  7861. if (session.peerconnection && session.peerconnection.updateLog) {
  7862. // FIXME: should probably be a .dump call
  7863. data["jingle_" + session.sid] = {
  7864. updateLog: session.peerconnection.updateLog,
  7865. stats: session.peerconnection.stats,
  7866. url: window.location.href
  7867. };
  7868. }
  7869. });
  7870. return data;
  7871. }
  7872. });
  7873. };
  7874. },{"../../service/xmpp/XMPPEvents":76,"../RTC/RTCBrowserType":14,"./JingleSessionPC":21}],30:[function(require,module,exports){
  7875. /* global Strophe */
  7876. module.exports = function () {
  7877. Strophe.addConnectionPlugin('logger', {
  7878. // logs raw stanzas and makes them available for download as JSON
  7879. connection: null,
  7880. log: [],
  7881. init: function (conn) {
  7882. this.connection = conn;
  7883. this.connection.rawInput = this.log_incoming.bind(this);
  7884. this.connection.rawOutput = this.log_outgoing.bind(this);
  7885. },
  7886. log_incoming: function (stanza) {
  7887. this.log.push([new Date().getTime(), 'incoming', stanza]);
  7888. },
  7889. log_outgoing: function (stanza) {
  7890. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  7891. }
  7892. });
  7893. };
  7894. },{}],31:[function(require,module,exports){
  7895. /* jshint -W117 */
  7896. module.exports = function() {
  7897. Strophe.addConnectionPlugin('rayo',
  7898. {
  7899. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  7900. connection: null,
  7901. init: function (conn) {
  7902. this.connection = conn;
  7903. if (this.connection.disco) {
  7904. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  7905. }
  7906. this.connection.addHandler(
  7907. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  7908. },
  7909. onRayo: function (iq) {
  7910. console.info("Rayo IQ", iq);
  7911. },
  7912. dial: function (to, from, roomName, roomPass) {
  7913. var self = this;
  7914. var req = $iq(
  7915. {
  7916. type: 'set',
  7917. to: this.connection.emuc.focusMucJid
  7918. }
  7919. );
  7920. req.c('dial',
  7921. {
  7922. xmlns: this.RAYO_XMLNS,
  7923. to: to,
  7924. from: from
  7925. });
  7926. req.c('header',
  7927. {
  7928. name: 'JvbRoomName',
  7929. value: roomName
  7930. }).up();
  7931. if (roomPass !== null && roomPass.length) {
  7932. req.c('header',
  7933. {
  7934. name: 'JvbRoomPassword',
  7935. value: roomPass
  7936. }).up();
  7937. }
  7938. this.connection.sendIQ(
  7939. req,
  7940. function (result) {
  7941. console.info('Dial result ', result);
  7942. var resource = $(result).find('ref').attr('uri');
  7943. this.call_resource = resource.substr('xmpp:'.length);
  7944. console.info(
  7945. "Received call resource: " + this.call_resource);
  7946. },
  7947. function (error) {
  7948. console.info('Dial error ', error);
  7949. }
  7950. );
  7951. },
  7952. hang_up: function () {
  7953. if (!this.call_resource) {
  7954. console.warn("No call in progress");
  7955. return;
  7956. }
  7957. var self = this;
  7958. var req = $iq(
  7959. {
  7960. type: 'set',
  7961. to: this.call_resource
  7962. }
  7963. );
  7964. req.c('hangup',
  7965. {
  7966. xmlns: this.RAYO_XMLNS
  7967. });
  7968. this.connection.sendIQ(
  7969. req,
  7970. function (result) {
  7971. console.info('Hangup result ', result);
  7972. self.call_resource = null;
  7973. },
  7974. function (error) {
  7975. console.info('Hangup error ', error);
  7976. self.call_resource = null;
  7977. }
  7978. );
  7979. }
  7980. }
  7981. );
  7982. };
  7983. },{}],32:[function(require,module,exports){
  7984. /**
  7985. * Strophe logger implementation. Logs from level WARN and above.
  7986. */
  7987. module.exports = function () {
  7988. Strophe.log = function (level, msg) {
  7989. switch (level) {
  7990. case Strophe.LogLevel.WARN:
  7991. console.warn("Strophe: " + msg);
  7992. break;
  7993. case Strophe.LogLevel.ERROR:
  7994. case Strophe.LogLevel.FATAL:
  7995. console.error("Strophe: " + msg);
  7996. break;
  7997. }
  7998. };
  7999. Strophe.getStatusString = function (status) {
  8000. switch (status) {
  8001. case Strophe.Status.ERROR:
  8002. return "ERROR";
  8003. case Strophe.Status.CONNECTING:
  8004. return "CONNECTING";
  8005. case Strophe.Status.CONNFAIL:
  8006. return "CONNFAIL";
  8007. case Strophe.Status.AUTHENTICATING:
  8008. return "AUTHENTICATING";
  8009. case Strophe.Status.AUTHFAIL:
  8010. return "AUTHFAIL";
  8011. case Strophe.Status.CONNECTED:
  8012. return "CONNECTED";
  8013. case Strophe.Status.DISCONNECTED:
  8014. return "DISCONNECTED";
  8015. case Strophe.Status.DISCONNECTING:
  8016. return "DISCONNECTING";
  8017. case Strophe.Status.ATTACHED:
  8018. return "ATTACHED";
  8019. default:
  8020. return "unknown";
  8021. }
  8022. };
  8023. };
  8024. },{}],33:[function(require,module,exports){
  8025. /* global $, APP, config, Strophe*/
  8026. var EventEmitter = require("events");
  8027. var Pako = require("pako");
  8028. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  8029. var RTCEvents = require("../../service/RTC/RTCEvents");
  8030. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8031. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  8032. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  8033. var RTC = require("../RTC/RTC");
  8034. var authenticatedUser = false;
  8035. function createConnection(bosh) {
  8036. bosh = bosh || '/http-bind';
  8037. return new Strophe.Connection(bosh);
  8038. };
  8039. //!!!!!!!!!! FIXME: ...
  8040. function initStrophePlugins(XMPP)
  8041. {
  8042. require("./strophe.emuc")(XMPP);
  8043. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  8044. // require("./strophe.moderate")(XMPP, eventEmitter);
  8045. require("./strophe.util")();
  8046. require("./strophe.rayo")();
  8047. require("./strophe.logger")();
  8048. }
  8049. //!!!!!!!!!! FIXME: ...
  8050. ///**
  8051. // * If given <tt>localStream</tt> is video one this method will advertise it's
  8052. // * video type in MUC presence.
  8053. // * @param localStream new or modified <tt>LocalStream</tt>.
  8054. // */
  8055. //function broadcastLocalVideoType(localStream) {
  8056. // if (localStream.videoType)
  8057. // XMPP.addToPresence('videoType', localStream.videoType);
  8058. //}
  8059. //
  8060. //function registerListeners() {
  8061. // RTC.addStreamListener(
  8062. // broadcastLocalVideoType,
  8063. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  8064. // );
  8065. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  8066. // XMPP.addToPresence("devices", devices);
  8067. // });
  8068. //}
  8069. function XMPP(options) {
  8070. this.eventEmitter = new EventEmitter();
  8071. this.connection = null;
  8072. this.disconnectInProgress = false;
  8073. this.forceMuted = false;
  8074. this.options = options;
  8075. initStrophePlugins(this);
  8076. // registerListeners();
  8077. this.connection = createConnection(options.bosh);
  8078. }
  8079. XMPP.prototype.getConnection = function(){ return connection; };
  8080. XMPP.prototype._connect = function (jid, password) {
  8081. var self = this;
  8082. // connection.connect() starts the connection process.
  8083. //
  8084. // As the connection process proceeds, the user supplied callback will
  8085. // be triggered multiple times with status updates. The callback should
  8086. // take two arguments - the status code and the error condition.
  8087. //
  8088. // The status code will be one of the values in the Strophe.Status
  8089. // constants. The error condition will be one of the conditions defined
  8090. // in RFC 3920 or the condition ‘strophe-parsererror’.
  8091. //
  8092. // The Parameters wait, hold and route are optional and only relevant
  8093. // for BOSH connections. Please see XEP 124 for a more detailed
  8094. // explanation of the optional parameters.
  8095. //
  8096. // Connection status constants for use by the connection handler
  8097. // callback.
  8098. //
  8099. // Status.ERROR - An error has occurred (websockets specific)
  8100. // Status.CONNECTING - The connection is currently being made
  8101. // Status.CONNFAIL - The connection attempt failed
  8102. // Status.AUTHENTICATING - The connection is authenticating
  8103. // Status.AUTHFAIL - The authentication attempt failed
  8104. // Status.CONNECTED - The connection has succeeded
  8105. // Status.DISCONNECTED - The connection has been terminated
  8106. // Status.DISCONNECTING - The connection is currently being terminated
  8107. // Status.ATTACHED - The connection has been attached
  8108. var anonymousConnectionFailed = false;
  8109. var connectionFailed = false;
  8110. var lastErrorMsg;
  8111. this.connection.connect(jid, password, function (status, msg) {
  8112. console.log('Strophe status changed to',
  8113. Strophe.getStatusString(status), msg);
  8114. if (status === Strophe.Status.CONNECTED) {
  8115. if (self.options.useStunTurn) {
  8116. self.connection.jingle.getStunAndTurnCredentials();
  8117. }
  8118. console.info("My Jabber ID: " + self.connection.jid);
  8119. if (password)
  8120. authenticatedUser = true;
  8121. if (self.connection && self.connection.connected &&
  8122. Strophe.getResourceFromJid(self.connection.jid)) {
  8123. // .connected is true while connecting?
  8124. // self.connection.send($pres());
  8125. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  8126. Strophe.getResourceFromJid(self.connection.jid));
  8127. }
  8128. } else if (status === Strophe.Status.CONNFAIL) {
  8129. if (msg === 'x-strophe-bad-non-anon-jid') {
  8130. anonymousConnectionFailed = true;
  8131. }
  8132. else
  8133. {
  8134. connectionFailed = true;
  8135. }
  8136. lastErrorMsg = msg;
  8137. } else if (status === Strophe.Status.DISCONNECTED) {
  8138. self.disconnectInProgress = false;
  8139. if (anonymousConnectionFailed) {
  8140. // prompt user for username and password
  8141. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8142. JitsiConnectionErrors.PASSWORD_REQUIRED);
  8143. } else if(connectionFailed) {
  8144. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8145. JitsiConnectionErrors.OTHER_ERROR,
  8146. msg ? msg : lastErrorMsg);
  8147. } else {
  8148. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  8149. msg ? msg : lastErrorMsg);
  8150. }
  8151. } else if (status === Strophe.Status.AUTHFAIL) {
  8152. // wrong password or username, prompt user
  8153. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8154. JitsiConnectionErrors.PASSWORD_REQUIRED);
  8155. }
  8156. });
  8157. }
  8158. XMPP.prototype.connect = function (jid, password) {
  8159. if(!jid) {
  8160. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  8161. // Force authenticated domain if room is appended with '?login=true'
  8162. if (this.options.hosts.anonymousdomain &&
  8163. window.location.search.indexOf("login=true") !== -1) {
  8164. configDomain = this.options.hosts.domain;
  8165. }
  8166. jid = configDomain || window.location.hostname;
  8167. }
  8168. return this._connect(jid, password);
  8169. };
  8170. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  8171. var roomjid = roomName + '@' + this.options.hosts.muc;
  8172. if (useNicks) {
  8173. if (nick) {
  8174. roomjid += '/' + nick;
  8175. } else {
  8176. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  8177. }
  8178. } else {
  8179. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  8180. if(!authenticatedUser)
  8181. tmpJid = tmpJid.substr(0, 8);
  8182. roomjid += '/' + tmpJid;
  8183. }
  8184. return this.connection.emuc.createRoom(roomjid, null, options);
  8185. }
  8186. XMPP.prototype.addListener = function(type, listener) {
  8187. this.eventEmitter.on(type, listener);
  8188. };
  8189. XMPP.prototype.removeListener = function (type, listener) {
  8190. this.eventEmitter.removeListener(type, listener);
  8191. };
  8192. //FIXME: this should work with the room
  8193. XMPP.prototype.leaveRoom = function (jid) {
  8194. var handler = this.connection.jingle.jid2session[jid];
  8195. if (handler && handler.peerconnection) {
  8196. // FIXME: probably removing streams is not required and close() should
  8197. // be enough
  8198. if (RTC.localAudio) {
  8199. handler.peerconnection.removeStream(
  8200. RTC.localAudio.getOriginalStream(), true);
  8201. }
  8202. if (RTC.localVideo) {
  8203. handler.peerconnection.removeStream(
  8204. RTC.localVideo.getOriginalStream(), true);
  8205. }
  8206. handler.peerconnection.close();
  8207. }
  8208. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  8209. this.connection.emuc.doLeave(jid);
  8210. };
  8211. /**
  8212. * Sends 'data' as a log message to the focus. Returns true iff a message
  8213. * was sent.
  8214. * @param data
  8215. * @returns {boolean} true iff a message was sent.
  8216. */
  8217. XMPP.prototype.sendLogs = function (data) {
  8218. if(!this.connection.emuc.focusMucJid)
  8219. return false;
  8220. var deflate = true;
  8221. var content = JSON.stringify(data);
  8222. if (deflate) {
  8223. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  8224. }
  8225. content = Base64.encode(content);
  8226. // XEP-0337-ish
  8227. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  8228. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  8229. id: 'PeerConnectionStats'});
  8230. message.c('message').t(content).up();
  8231. if (deflate) {
  8232. message.c('tag', {name: "deflated", value: "true"}).up();
  8233. }
  8234. message.up();
  8235. this.connection.send(message);
  8236. return true;
  8237. };
  8238. // Gets the logs from strophe.jingle.
  8239. XMPP.prototype.getJingleLog = function () {
  8240. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  8241. };
  8242. // Gets the logs from strophe.
  8243. XMPP.prototype.getXmppLog = function () {
  8244. return this.connection.logger ? this.connection.logger.log : null;
  8245. };
  8246. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  8247. this.connection.rayo.dial(to, from, roomName,roomPass);
  8248. };
  8249. XMPP.prototype.setMute = function (jid, mute) {
  8250. this.connection.moderate.setMute(jid, mute);
  8251. };
  8252. XMPP.prototype.eject = function (jid) {
  8253. this.connection.moderate.eject(jid);
  8254. };
  8255. XMPP.prototype.getJidFromSSRC = function (ssrc) {
  8256. if (!this.isConferenceInProgress())
  8257. return null;
  8258. return this.connection.jingle.activecall.getSsrcOwner(ssrc);
  8259. };
  8260. XMPP.prototype.getSessions = function () {
  8261. return this.connection.jingle.sessions;
  8262. };
  8263. XMPP.prototype.disconnect = function () {
  8264. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  8265. {
  8266. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  8267. return;
  8268. }
  8269. this.disconnectInProgress = true;
  8270. this.connection.disconnect();
  8271. };
  8272. module.exports = XMPP;
  8273. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":71,"../../service/RTC/StreamEventTypes":73,"../../service/xmpp/XMPPEvents":76,"../RTC/RTC":13,"./strophe.emuc":28,"./strophe.jingle":29,"./strophe.logger":30,"./strophe.rayo":31,"./strophe.util":32,"events":77,"pako":36}],34:[function(require,module,exports){
  8274. (function (process){
  8275. /*!
  8276. * async
  8277. * https://github.com/caolan/async
  8278. *
  8279. * Copyright 2010-2014 Caolan McMahon
  8280. * Released under the MIT license
  8281. */
  8282. /*jshint onevar: false, indent:4 */
  8283. /*global setImmediate: false, setTimeout: false, console: false */
  8284. (function () {
  8285. var async = {};
  8286. // global on the server, window in the browser
  8287. var root, previous_async;
  8288. root = this;
  8289. if (root != null) {
  8290. previous_async = root.async;
  8291. }
  8292. async.noConflict = function () {
  8293. root.async = previous_async;
  8294. return async;
  8295. };
  8296. function only_once(fn) {
  8297. var called = false;
  8298. return function() {
  8299. if (called) throw new Error("Callback was already called.");
  8300. called = true;
  8301. fn.apply(root, arguments);
  8302. }
  8303. }
  8304. //// cross-browser compatiblity functions ////
  8305. var _toString = Object.prototype.toString;
  8306. var _isArray = Array.isArray || function (obj) {
  8307. return _toString.call(obj) === '[object Array]';
  8308. };
  8309. var _each = function (arr, iterator) {
  8310. if (arr.forEach) {
  8311. return arr.forEach(iterator);
  8312. }
  8313. for (var i = 0; i < arr.length; i += 1) {
  8314. iterator(arr[i], i, arr);
  8315. }
  8316. };
  8317. var _map = function (arr, iterator) {
  8318. if (arr.map) {
  8319. return arr.map(iterator);
  8320. }
  8321. var results = [];
  8322. _each(arr, function (x, i, a) {
  8323. results.push(iterator(x, i, a));
  8324. });
  8325. return results;
  8326. };
  8327. var _reduce = function (arr, iterator, memo) {
  8328. if (arr.reduce) {
  8329. return arr.reduce(iterator, memo);
  8330. }
  8331. _each(arr, function (x, i, a) {
  8332. memo = iterator(memo, x, i, a);
  8333. });
  8334. return memo;
  8335. };
  8336. var _keys = function (obj) {
  8337. if (Object.keys) {
  8338. return Object.keys(obj);
  8339. }
  8340. var keys = [];
  8341. for (var k in obj) {
  8342. if (obj.hasOwnProperty(k)) {
  8343. keys.push(k);
  8344. }
  8345. }
  8346. return keys;
  8347. };
  8348. //// exported async module functions ////
  8349. //// nextTick implementation with browser-compatible fallback ////
  8350. if (typeof process === 'undefined' || !(process.nextTick)) {
  8351. if (typeof setImmediate === 'function') {
  8352. async.nextTick = function (fn) {
  8353. // not a direct alias for IE10 compatibility
  8354. setImmediate(fn);
  8355. };
  8356. async.setImmediate = async.nextTick;
  8357. }
  8358. else {
  8359. async.nextTick = function (fn) {
  8360. setTimeout(fn, 0);
  8361. };
  8362. async.setImmediate = async.nextTick;
  8363. }
  8364. }
  8365. else {
  8366. async.nextTick = process.nextTick;
  8367. if (typeof setImmediate !== 'undefined') {
  8368. async.setImmediate = function (fn) {
  8369. // not a direct alias for IE10 compatibility
  8370. setImmediate(fn);
  8371. };
  8372. }
  8373. else {
  8374. async.setImmediate = async.nextTick;
  8375. }
  8376. }
  8377. async.each = function (arr, iterator, callback) {
  8378. callback = callback || function () {};
  8379. if (!arr.length) {
  8380. return callback();
  8381. }
  8382. var completed = 0;
  8383. _each(arr, function (x) {
  8384. iterator(x, only_once(done) );
  8385. });
  8386. function done(err) {
  8387. if (err) {
  8388. callback(err);
  8389. callback = function () {};
  8390. }
  8391. else {
  8392. completed += 1;
  8393. if (completed >= arr.length) {
  8394. callback();
  8395. }
  8396. }
  8397. }
  8398. };
  8399. async.forEach = async.each;
  8400. async.eachSeries = function (arr, iterator, callback) {
  8401. callback = callback || function () {};
  8402. if (!arr.length) {
  8403. return callback();
  8404. }
  8405. var completed = 0;
  8406. var iterate = function () {
  8407. iterator(arr[completed], function (err) {
  8408. if (err) {
  8409. callback(err);
  8410. callback = function () {};
  8411. }
  8412. else {
  8413. completed += 1;
  8414. if (completed >= arr.length) {
  8415. callback();
  8416. }
  8417. else {
  8418. iterate();
  8419. }
  8420. }
  8421. });
  8422. };
  8423. iterate();
  8424. };
  8425. async.forEachSeries = async.eachSeries;
  8426. async.eachLimit = function (arr, limit, iterator, callback) {
  8427. var fn = _eachLimit(limit);
  8428. fn.apply(null, [arr, iterator, callback]);
  8429. };
  8430. async.forEachLimit = async.eachLimit;
  8431. var _eachLimit = function (limit) {
  8432. return function (arr, iterator, callback) {
  8433. callback = callback || function () {};
  8434. if (!arr.length || limit <= 0) {
  8435. return callback();
  8436. }
  8437. var completed = 0;
  8438. var started = 0;
  8439. var running = 0;
  8440. (function replenish () {
  8441. if (completed >= arr.length) {
  8442. return callback();
  8443. }
  8444. while (running < limit && started < arr.length) {
  8445. started += 1;
  8446. running += 1;
  8447. iterator(arr[started - 1], function (err) {
  8448. if (err) {
  8449. callback(err);
  8450. callback = function () {};
  8451. }
  8452. else {
  8453. completed += 1;
  8454. running -= 1;
  8455. if (completed >= arr.length) {
  8456. callback();
  8457. }
  8458. else {
  8459. replenish();
  8460. }
  8461. }
  8462. });
  8463. }
  8464. })();
  8465. };
  8466. };
  8467. var doParallel = function (fn) {
  8468. return function () {
  8469. var args = Array.prototype.slice.call(arguments);
  8470. return fn.apply(null, [async.each].concat(args));
  8471. };
  8472. };
  8473. var doParallelLimit = function(limit, fn) {
  8474. return function () {
  8475. var args = Array.prototype.slice.call(arguments);
  8476. return fn.apply(null, [_eachLimit(limit)].concat(args));
  8477. };
  8478. };
  8479. var doSeries = function (fn) {
  8480. return function () {
  8481. var args = Array.prototype.slice.call(arguments);
  8482. return fn.apply(null, [async.eachSeries].concat(args));
  8483. };
  8484. };
  8485. var _asyncMap = function (eachfn, arr, iterator, callback) {
  8486. arr = _map(arr, function (x, i) {
  8487. return {index: i, value: x};
  8488. });
  8489. if (!callback) {
  8490. eachfn(arr, function (x, callback) {
  8491. iterator(x.value, function (err) {
  8492. callback(err);
  8493. });
  8494. });
  8495. } else {
  8496. var results = [];
  8497. eachfn(arr, function (x, callback) {
  8498. iterator(x.value, function (err, v) {
  8499. results[x.index] = v;
  8500. callback(err);
  8501. });
  8502. }, function (err) {
  8503. callback(err, results);
  8504. });
  8505. }
  8506. };
  8507. async.map = doParallel(_asyncMap);
  8508. async.mapSeries = doSeries(_asyncMap);
  8509. async.mapLimit = function (arr, limit, iterator, callback) {
  8510. return _mapLimit(limit)(arr, iterator, callback);
  8511. };
  8512. var _mapLimit = function(limit) {
  8513. return doParallelLimit(limit, _asyncMap);
  8514. };
  8515. // reduce only has a series version, as doing reduce in parallel won't
  8516. // work in many situations.
  8517. async.reduce = function (arr, memo, iterator, callback) {
  8518. async.eachSeries(arr, function (x, callback) {
  8519. iterator(memo, x, function (err, v) {
  8520. memo = v;
  8521. callback(err);
  8522. });
  8523. }, function (err) {
  8524. callback(err, memo);
  8525. });
  8526. };
  8527. // inject alias
  8528. async.inject = async.reduce;
  8529. // foldl alias
  8530. async.foldl = async.reduce;
  8531. async.reduceRight = function (arr, memo, iterator, callback) {
  8532. var reversed = _map(arr, function (x) {
  8533. return x;
  8534. }).reverse();
  8535. async.reduce(reversed, memo, iterator, callback);
  8536. };
  8537. // foldr alias
  8538. async.foldr = async.reduceRight;
  8539. var _filter = function (eachfn, arr, iterator, callback) {
  8540. var results = [];
  8541. arr = _map(arr, function (x, i) {
  8542. return {index: i, value: x};
  8543. });
  8544. eachfn(arr, function (x, callback) {
  8545. iterator(x.value, function (v) {
  8546. if (v) {
  8547. results.push(x);
  8548. }
  8549. callback();
  8550. });
  8551. }, function (err) {
  8552. callback(_map(results.sort(function (a, b) {
  8553. return a.index - b.index;
  8554. }), function (x) {
  8555. return x.value;
  8556. }));
  8557. });
  8558. };
  8559. async.filter = doParallel(_filter);
  8560. async.filterSeries = doSeries(_filter);
  8561. // select alias
  8562. async.select = async.filter;
  8563. async.selectSeries = async.filterSeries;
  8564. var _reject = function (eachfn, arr, iterator, callback) {
  8565. var results = [];
  8566. arr = _map(arr, function (x, i) {
  8567. return {index: i, value: x};
  8568. });
  8569. eachfn(arr, function (x, callback) {
  8570. iterator(x.value, function (v) {
  8571. if (!v) {
  8572. results.push(x);
  8573. }
  8574. callback();
  8575. });
  8576. }, function (err) {
  8577. callback(_map(results.sort(function (a, b) {
  8578. return a.index - b.index;
  8579. }), function (x) {
  8580. return x.value;
  8581. }));
  8582. });
  8583. };
  8584. async.reject = doParallel(_reject);
  8585. async.rejectSeries = doSeries(_reject);
  8586. var _detect = function (eachfn, arr, iterator, main_callback) {
  8587. eachfn(arr, function (x, callback) {
  8588. iterator(x, function (result) {
  8589. if (result) {
  8590. main_callback(x);
  8591. main_callback = function () {};
  8592. }
  8593. else {
  8594. callback();
  8595. }
  8596. });
  8597. }, function (err) {
  8598. main_callback();
  8599. });
  8600. };
  8601. async.detect = doParallel(_detect);
  8602. async.detectSeries = doSeries(_detect);
  8603. async.some = function (arr, iterator, main_callback) {
  8604. async.each(arr, function (x, callback) {
  8605. iterator(x, function (v) {
  8606. if (v) {
  8607. main_callback(true);
  8608. main_callback = function () {};
  8609. }
  8610. callback();
  8611. });
  8612. }, function (err) {
  8613. main_callback(false);
  8614. });
  8615. };
  8616. // any alias
  8617. async.any = async.some;
  8618. async.every = function (arr, iterator, main_callback) {
  8619. async.each(arr, function (x, callback) {
  8620. iterator(x, function (v) {
  8621. if (!v) {
  8622. main_callback(false);
  8623. main_callback = function () {};
  8624. }
  8625. callback();
  8626. });
  8627. }, function (err) {
  8628. main_callback(true);
  8629. });
  8630. };
  8631. // all alias
  8632. async.all = async.every;
  8633. async.sortBy = function (arr, iterator, callback) {
  8634. async.map(arr, function (x, callback) {
  8635. iterator(x, function (err, criteria) {
  8636. if (err) {
  8637. callback(err);
  8638. }
  8639. else {
  8640. callback(null, {value: x, criteria: criteria});
  8641. }
  8642. });
  8643. }, function (err, results) {
  8644. if (err) {
  8645. return callback(err);
  8646. }
  8647. else {
  8648. var fn = function (left, right) {
  8649. var a = left.criteria, b = right.criteria;
  8650. return a < b ? -1 : a > b ? 1 : 0;
  8651. };
  8652. callback(null, _map(results.sort(fn), function (x) {
  8653. return x.value;
  8654. }));
  8655. }
  8656. });
  8657. };
  8658. async.auto = function (tasks, callback) {
  8659. callback = callback || function () {};
  8660. var keys = _keys(tasks);
  8661. var remainingTasks = keys.length
  8662. if (!remainingTasks) {
  8663. return callback();
  8664. }
  8665. var results = {};
  8666. var listeners = [];
  8667. var addListener = function (fn) {
  8668. listeners.unshift(fn);
  8669. };
  8670. var removeListener = function (fn) {
  8671. for (var i = 0; i < listeners.length; i += 1) {
  8672. if (listeners[i] === fn) {
  8673. listeners.splice(i, 1);
  8674. return;
  8675. }
  8676. }
  8677. };
  8678. var taskComplete = function () {
  8679. remainingTasks--
  8680. _each(listeners.slice(0), function (fn) {
  8681. fn();
  8682. });
  8683. };
  8684. addListener(function () {
  8685. if (!remainingTasks) {
  8686. var theCallback = callback;
  8687. // prevent final callback from calling itself if it errors
  8688. callback = function () {};
  8689. theCallback(null, results);
  8690. }
  8691. });
  8692. _each(keys, function (k) {
  8693. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  8694. var taskCallback = function (err) {
  8695. var args = Array.prototype.slice.call(arguments, 1);
  8696. if (args.length <= 1) {
  8697. args = args[0];
  8698. }
  8699. if (err) {
  8700. var safeResults = {};
  8701. _each(_keys(results), function(rkey) {
  8702. safeResults[rkey] = results[rkey];
  8703. });
  8704. safeResults[k] = args;
  8705. callback(err, safeResults);
  8706. // stop subsequent errors hitting callback multiple times
  8707. callback = function () {};
  8708. }
  8709. else {
  8710. results[k] = args;
  8711. async.setImmediate(taskComplete);
  8712. }
  8713. };
  8714. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  8715. var ready = function () {
  8716. return _reduce(requires, function (a, x) {
  8717. return (a && results.hasOwnProperty(x));
  8718. }, true) && !results.hasOwnProperty(k);
  8719. };
  8720. if (ready()) {
  8721. task[task.length - 1](taskCallback, results);
  8722. }
  8723. else {
  8724. var listener = function () {
  8725. if (ready()) {
  8726. removeListener(listener);
  8727. task[task.length - 1](taskCallback, results);
  8728. }
  8729. };
  8730. addListener(listener);
  8731. }
  8732. });
  8733. };
  8734. async.retry = function(times, task, callback) {
  8735. var DEFAULT_TIMES = 5;
  8736. var attempts = [];
  8737. // Use defaults if times not passed
  8738. if (typeof times === 'function') {
  8739. callback = task;
  8740. task = times;
  8741. times = DEFAULT_TIMES;
  8742. }
  8743. // Make sure times is a number
  8744. times = parseInt(times, 10) || DEFAULT_TIMES;
  8745. var wrappedTask = function(wrappedCallback, wrappedResults) {
  8746. var retryAttempt = function(task, finalAttempt) {
  8747. return function(seriesCallback) {
  8748. task(function(err, result){
  8749. seriesCallback(!err || finalAttempt, {err: err, result: result});
  8750. }, wrappedResults);
  8751. };
  8752. };
  8753. while (times) {
  8754. attempts.push(retryAttempt(task, !(times-=1)));
  8755. }
  8756. async.series(attempts, function(done, data){
  8757. data = data[data.length - 1];
  8758. (wrappedCallback || callback)(data.err, data.result);
  8759. });
  8760. }
  8761. // If a callback is passed, run this as a controll flow
  8762. return callback ? wrappedTask() : wrappedTask
  8763. };
  8764. async.waterfall = function (tasks, callback) {
  8765. callback = callback || function () {};
  8766. if (!_isArray(tasks)) {
  8767. var err = new Error('First argument to waterfall must be an array of functions');
  8768. return callback(err);
  8769. }
  8770. if (!tasks.length) {
  8771. return callback();
  8772. }
  8773. var wrapIterator = function (iterator) {
  8774. return function (err) {
  8775. if (err) {
  8776. callback.apply(null, arguments);
  8777. callback = function () {};
  8778. }
  8779. else {
  8780. var args = Array.prototype.slice.call(arguments, 1);
  8781. var next = iterator.next();
  8782. if (next) {
  8783. args.push(wrapIterator(next));
  8784. }
  8785. else {
  8786. args.push(callback);
  8787. }
  8788. async.setImmediate(function () {
  8789. iterator.apply(null, args);
  8790. });
  8791. }
  8792. };
  8793. };
  8794. wrapIterator(async.iterator(tasks))();
  8795. };
  8796. var _parallel = function(eachfn, tasks, callback) {
  8797. callback = callback || function () {};
  8798. if (_isArray(tasks)) {
  8799. eachfn.map(tasks, function (fn, callback) {
  8800. if (fn) {
  8801. fn(function (err) {
  8802. var args = Array.prototype.slice.call(arguments, 1);
  8803. if (args.length <= 1) {
  8804. args = args[0];
  8805. }
  8806. callback.call(null, err, args);
  8807. });
  8808. }
  8809. }, callback);
  8810. }
  8811. else {
  8812. var results = {};
  8813. eachfn.each(_keys(tasks), function (k, callback) {
  8814. tasks[k](function (err) {
  8815. var args = Array.prototype.slice.call(arguments, 1);
  8816. if (args.length <= 1) {
  8817. args = args[0];
  8818. }
  8819. results[k] = args;
  8820. callback(err);
  8821. });
  8822. }, function (err) {
  8823. callback(err, results);
  8824. });
  8825. }
  8826. };
  8827. async.parallel = function (tasks, callback) {
  8828. _parallel({ map: async.map, each: async.each }, tasks, callback);
  8829. };
  8830. async.parallelLimit = function(tasks, limit, callback) {
  8831. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  8832. };
  8833. async.series = function (tasks, callback) {
  8834. callback = callback || function () {};
  8835. if (_isArray(tasks)) {
  8836. async.mapSeries(tasks, function (fn, callback) {
  8837. if (fn) {
  8838. fn(function (err) {
  8839. var args = Array.prototype.slice.call(arguments, 1);
  8840. if (args.length <= 1) {
  8841. args = args[0];
  8842. }
  8843. callback.call(null, err, args);
  8844. });
  8845. }
  8846. }, callback);
  8847. }
  8848. else {
  8849. var results = {};
  8850. async.eachSeries(_keys(tasks), function (k, callback) {
  8851. tasks[k](function (err) {
  8852. var args = Array.prototype.slice.call(arguments, 1);
  8853. if (args.length <= 1) {
  8854. args = args[0];
  8855. }
  8856. results[k] = args;
  8857. callback(err);
  8858. });
  8859. }, function (err) {
  8860. callback(err, results);
  8861. });
  8862. }
  8863. };
  8864. async.iterator = function (tasks) {
  8865. var makeCallback = function (index) {
  8866. var fn = function () {
  8867. if (tasks.length) {
  8868. tasks[index].apply(null, arguments);
  8869. }
  8870. return fn.next();
  8871. };
  8872. fn.next = function () {
  8873. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  8874. };
  8875. return fn;
  8876. };
  8877. return makeCallback(0);
  8878. };
  8879. async.apply = function (fn) {
  8880. var args = Array.prototype.slice.call(arguments, 1);
  8881. return function () {
  8882. return fn.apply(
  8883. null, args.concat(Array.prototype.slice.call(arguments))
  8884. );
  8885. };
  8886. };
  8887. var _concat = function (eachfn, arr, fn, callback) {
  8888. var r = [];
  8889. eachfn(arr, function (x, cb) {
  8890. fn(x, function (err, y) {
  8891. r = r.concat(y || []);
  8892. cb(err);
  8893. });
  8894. }, function (err) {
  8895. callback(err, r);
  8896. });
  8897. };
  8898. async.concat = doParallel(_concat);
  8899. async.concatSeries = doSeries(_concat);
  8900. async.whilst = function (test, iterator, callback) {
  8901. if (test()) {
  8902. iterator(function (err) {
  8903. if (err) {
  8904. return callback(err);
  8905. }
  8906. async.whilst(test, iterator, callback);
  8907. });
  8908. }
  8909. else {
  8910. callback();
  8911. }
  8912. };
  8913. async.doWhilst = function (iterator, test, callback) {
  8914. iterator(function (err) {
  8915. if (err) {
  8916. return callback(err);
  8917. }
  8918. var args = Array.prototype.slice.call(arguments, 1);
  8919. if (test.apply(null, args)) {
  8920. async.doWhilst(iterator, test, callback);
  8921. }
  8922. else {
  8923. callback();
  8924. }
  8925. });
  8926. };
  8927. async.until = function (test, iterator, callback) {
  8928. if (!test()) {
  8929. iterator(function (err) {
  8930. if (err) {
  8931. return callback(err);
  8932. }
  8933. async.until(test, iterator, callback);
  8934. });
  8935. }
  8936. else {
  8937. callback();
  8938. }
  8939. };
  8940. async.doUntil = function (iterator, test, callback) {
  8941. iterator(function (err) {
  8942. if (err) {
  8943. return callback(err);
  8944. }
  8945. var args = Array.prototype.slice.call(arguments, 1);
  8946. if (!test.apply(null, args)) {
  8947. async.doUntil(iterator, test, callback);
  8948. }
  8949. else {
  8950. callback();
  8951. }
  8952. });
  8953. };
  8954. async.queue = function (worker, concurrency) {
  8955. if (concurrency === undefined) {
  8956. concurrency = 1;
  8957. }
  8958. function _insert(q, data, pos, callback) {
  8959. if (!q.started){
  8960. q.started = true;
  8961. }
  8962. if (!_isArray(data)) {
  8963. data = [data];
  8964. }
  8965. if(data.length == 0) {
  8966. // call drain immediately if there are no tasks
  8967. return async.setImmediate(function() {
  8968. if (q.drain) {
  8969. q.drain();
  8970. }
  8971. });
  8972. }
  8973. _each(data, function(task) {
  8974. var item = {
  8975. data: task,
  8976. callback: typeof callback === 'function' ? callback : null
  8977. };
  8978. if (pos) {
  8979. q.tasks.unshift(item);
  8980. } else {
  8981. q.tasks.push(item);
  8982. }
  8983. if (q.saturated && q.tasks.length === q.concurrency) {
  8984. q.saturated();
  8985. }
  8986. async.setImmediate(q.process);
  8987. });
  8988. }
  8989. var workers = 0;
  8990. var q = {
  8991. tasks: [],
  8992. concurrency: concurrency,
  8993. saturated: null,
  8994. empty: null,
  8995. drain: null,
  8996. started: false,
  8997. paused: false,
  8998. push: function (data, callback) {
  8999. _insert(q, data, false, callback);
  9000. },
  9001. kill: function () {
  9002. q.drain = null;
  9003. q.tasks = [];
  9004. },
  9005. unshift: function (data, callback) {
  9006. _insert(q, data, true, callback);
  9007. },
  9008. process: function () {
  9009. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  9010. var task = q.tasks.shift();
  9011. if (q.empty && q.tasks.length === 0) {
  9012. q.empty();
  9013. }
  9014. workers += 1;
  9015. var next = function () {
  9016. workers -= 1;
  9017. if (task.callback) {
  9018. task.callback.apply(task, arguments);
  9019. }
  9020. if (q.drain && q.tasks.length + workers === 0) {
  9021. q.drain();
  9022. }
  9023. q.process();
  9024. };
  9025. var cb = only_once(next);
  9026. worker(task.data, cb);
  9027. }
  9028. },
  9029. length: function () {
  9030. return q.tasks.length;
  9031. },
  9032. running: function () {
  9033. return workers;
  9034. },
  9035. idle: function() {
  9036. return q.tasks.length + workers === 0;
  9037. },
  9038. pause: function () {
  9039. if (q.paused === true) { return; }
  9040. q.paused = true;
  9041. q.process();
  9042. },
  9043. resume: function () {
  9044. if (q.paused === false) { return; }
  9045. q.paused = false;
  9046. q.process();
  9047. }
  9048. };
  9049. return q;
  9050. };
  9051. async.priorityQueue = function (worker, concurrency) {
  9052. function _compareTasks(a, b){
  9053. return a.priority - b.priority;
  9054. };
  9055. function _binarySearch(sequence, item, compare) {
  9056. var beg = -1,
  9057. end = sequence.length - 1;
  9058. while (beg < end) {
  9059. var mid = beg + ((end - beg + 1) >>> 1);
  9060. if (compare(item, sequence[mid]) >= 0) {
  9061. beg = mid;
  9062. } else {
  9063. end = mid - 1;
  9064. }
  9065. }
  9066. return beg;
  9067. }
  9068. function _insert(q, data, priority, callback) {
  9069. if (!q.started){
  9070. q.started = true;
  9071. }
  9072. if (!_isArray(data)) {
  9073. data = [data];
  9074. }
  9075. if(data.length == 0) {
  9076. // call drain immediately if there are no tasks
  9077. return async.setImmediate(function() {
  9078. if (q.drain) {
  9079. q.drain();
  9080. }
  9081. });
  9082. }
  9083. _each(data, function(task) {
  9084. var item = {
  9085. data: task,
  9086. priority: priority,
  9087. callback: typeof callback === 'function' ? callback : null
  9088. };
  9089. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  9090. if (q.saturated && q.tasks.length === q.concurrency) {
  9091. q.saturated();
  9092. }
  9093. async.setImmediate(q.process);
  9094. });
  9095. }
  9096. // Start with a normal queue
  9097. var q = async.queue(worker, concurrency);
  9098. // Override push to accept second parameter representing priority
  9099. q.push = function (data, priority, callback) {
  9100. _insert(q, data, priority, callback);
  9101. };
  9102. // Remove unshift function
  9103. delete q.unshift;
  9104. return q;
  9105. };
  9106. async.cargo = function (worker, payload) {
  9107. var working = false,
  9108. tasks = [];
  9109. var cargo = {
  9110. tasks: tasks,
  9111. payload: payload,
  9112. saturated: null,
  9113. empty: null,
  9114. drain: null,
  9115. drained: true,
  9116. push: function (data, callback) {
  9117. if (!_isArray(data)) {
  9118. data = [data];
  9119. }
  9120. _each(data, function(task) {
  9121. tasks.push({
  9122. data: task,
  9123. callback: typeof callback === 'function' ? callback : null
  9124. });
  9125. cargo.drained = false;
  9126. if (cargo.saturated && tasks.length === payload) {
  9127. cargo.saturated();
  9128. }
  9129. });
  9130. async.setImmediate(cargo.process);
  9131. },
  9132. process: function process() {
  9133. if (working) return;
  9134. if (tasks.length === 0) {
  9135. if(cargo.drain && !cargo.drained) cargo.drain();
  9136. cargo.drained = true;
  9137. return;
  9138. }
  9139. var ts = typeof payload === 'number'
  9140. ? tasks.splice(0, payload)
  9141. : tasks.splice(0, tasks.length);
  9142. var ds = _map(ts, function (task) {
  9143. return task.data;
  9144. });
  9145. if(cargo.empty) cargo.empty();
  9146. working = true;
  9147. worker(ds, function () {
  9148. working = false;
  9149. var args = arguments;
  9150. _each(ts, function (data) {
  9151. if (data.callback) {
  9152. data.callback.apply(null, args);
  9153. }
  9154. });
  9155. process();
  9156. });
  9157. },
  9158. length: function () {
  9159. return tasks.length;
  9160. },
  9161. running: function () {
  9162. return working;
  9163. }
  9164. };
  9165. return cargo;
  9166. };
  9167. var _console_fn = function (name) {
  9168. return function (fn) {
  9169. var args = Array.prototype.slice.call(arguments, 1);
  9170. fn.apply(null, args.concat([function (err) {
  9171. var args = Array.prototype.slice.call(arguments, 1);
  9172. if (typeof console !== 'undefined') {
  9173. if (err) {
  9174. if (console.error) {
  9175. console.error(err);
  9176. }
  9177. }
  9178. else if (console[name]) {
  9179. _each(args, function (x) {
  9180. console[name](x);
  9181. });
  9182. }
  9183. }
  9184. }]));
  9185. };
  9186. };
  9187. async.log = _console_fn('log');
  9188. async.dir = _console_fn('dir');
  9189. /*async.info = _console_fn('info');
  9190. async.warn = _console_fn('warn');
  9191. async.error = _console_fn('error');*/
  9192. async.memoize = function (fn, hasher) {
  9193. var memo = {};
  9194. var queues = {};
  9195. hasher = hasher || function (x) {
  9196. return x;
  9197. };
  9198. var memoized = function () {
  9199. var args = Array.prototype.slice.call(arguments);
  9200. var callback = args.pop();
  9201. var key = hasher.apply(null, args);
  9202. if (key in memo) {
  9203. async.nextTick(function () {
  9204. callback.apply(null, memo[key]);
  9205. });
  9206. }
  9207. else if (key in queues) {
  9208. queues[key].push(callback);
  9209. }
  9210. else {
  9211. queues[key] = [callback];
  9212. fn.apply(null, args.concat([function () {
  9213. memo[key] = arguments;
  9214. var q = queues[key];
  9215. delete queues[key];
  9216. for (var i = 0, l = q.length; i < l; i++) {
  9217. q[i].apply(null, arguments);
  9218. }
  9219. }]));
  9220. }
  9221. };
  9222. memoized.memo = memo;
  9223. memoized.unmemoized = fn;
  9224. return memoized;
  9225. };
  9226. async.unmemoize = function (fn) {
  9227. return function () {
  9228. return (fn.unmemoized || fn).apply(null, arguments);
  9229. };
  9230. };
  9231. async.times = function (count, iterator, callback) {
  9232. var counter = [];
  9233. for (var i = 0; i < count; i++) {
  9234. counter.push(i);
  9235. }
  9236. return async.map(counter, iterator, callback);
  9237. };
  9238. async.timesSeries = function (count, iterator, callback) {
  9239. var counter = [];
  9240. for (var i = 0; i < count; i++) {
  9241. counter.push(i);
  9242. }
  9243. return async.mapSeries(counter, iterator, callback);
  9244. };
  9245. async.seq = function (/* functions... */) {
  9246. var fns = arguments;
  9247. return function () {
  9248. var that = this;
  9249. var args = Array.prototype.slice.call(arguments);
  9250. var callback = args.pop();
  9251. async.reduce(fns, args, function (newargs, fn, cb) {
  9252. fn.apply(that, newargs.concat([function () {
  9253. var err = arguments[0];
  9254. var nextargs = Array.prototype.slice.call(arguments, 1);
  9255. cb(err, nextargs);
  9256. }]))
  9257. },
  9258. function (err, results) {
  9259. callback.apply(that, [err].concat(results));
  9260. });
  9261. };
  9262. };
  9263. async.compose = function (/* functions... */) {
  9264. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  9265. };
  9266. var _applyEach = function (eachfn, fns /*args...*/) {
  9267. var go = function () {
  9268. var that = this;
  9269. var args = Array.prototype.slice.call(arguments);
  9270. var callback = args.pop();
  9271. return eachfn(fns, function (fn, cb) {
  9272. fn.apply(that, args.concat([cb]));
  9273. },
  9274. callback);
  9275. };
  9276. if (arguments.length > 2) {
  9277. var args = Array.prototype.slice.call(arguments, 2);
  9278. return go.apply(this, args);
  9279. }
  9280. else {
  9281. return go;
  9282. }
  9283. };
  9284. async.applyEach = doParallel(_applyEach);
  9285. async.applyEachSeries = doSeries(_applyEach);
  9286. async.forever = function (fn, callback) {
  9287. function next(err) {
  9288. if (err) {
  9289. if (callback) {
  9290. return callback(err);
  9291. }
  9292. throw err;
  9293. }
  9294. fn(next);
  9295. }
  9296. next();
  9297. };
  9298. // Node.js
  9299. if (typeof module !== 'undefined' && module.exports) {
  9300. module.exports = async;
  9301. }
  9302. // AMD / RequireJS
  9303. else if (typeof define !== 'undefined' && define.amd) {
  9304. define([], function () {
  9305. return async;
  9306. });
  9307. }
  9308. // included directly via <script> tag
  9309. else {
  9310. root.async = async;
  9311. }
  9312. }());
  9313. }).call(this,require('_process'))
  9314. },{"_process":78}],35:[function(require,module,exports){
  9315. (function (process,global){
  9316. /*!
  9317. * @overview es6-promise - a tiny implementation of Promises/A+.
  9318. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  9319. * @license Licensed under MIT license
  9320. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  9321. * @version 3.0.2
  9322. */
  9323. (function() {
  9324. "use strict";
  9325. function lib$es6$promise$utils$$objectOrFunction(x) {
  9326. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  9327. }
  9328. function lib$es6$promise$utils$$isFunction(x) {
  9329. return typeof x === 'function';
  9330. }
  9331. function lib$es6$promise$utils$$isMaybeThenable(x) {
  9332. return typeof x === 'object' && x !== null;
  9333. }
  9334. var lib$es6$promise$utils$$_isArray;
  9335. if (!Array.isArray) {
  9336. lib$es6$promise$utils$$_isArray = function (x) {
  9337. return Object.prototype.toString.call(x) === '[object Array]';
  9338. };
  9339. } else {
  9340. lib$es6$promise$utils$$_isArray = Array.isArray;
  9341. }
  9342. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  9343. var lib$es6$promise$asap$$len = 0;
  9344. var lib$es6$promise$asap$$toString = {}.toString;
  9345. var lib$es6$promise$asap$$vertxNext;
  9346. var lib$es6$promise$asap$$customSchedulerFn;
  9347. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  9348. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  9349. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  9350. lib$es6$promise$asap$$len += 2;
  9351. if (lib$es6$promise$asap$$len === 2) {
  9352. // If len is 2, that means that we need to schedule an async flush.
  9353. // If additional callbacks are queued before the queue is flushed, they
  9354. // will be processed by this flush that we are scheduling.
  9355. if (lib$es6$promise$asap$$customSchedulerFn) {
  9356. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  9357. } else {
  9358. lib$es6$promise$asap$$scheduleFlush();
  9359. }
  9360. }
  9361. }
  9362. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  9363. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  9364. }
  9365. function lib$es6$promise$asap$$setAsap(asapFn) {
  9366. lib$es6$promise$asap$$asap = asapFn;
  9367. }
  9368. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  9369. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  9370. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  9371. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  9372. // test for web worker but not in IE10
  9373. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  9374. typeof importScripts !== 'undefined' &&
  9375. typeof MessageChannel !== 'undefined';
  9376. // node
  9377. function lib$es6$promise$asap$$useNextTick() {
  9378. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  9379. // see https://github.com/cujojs/when/issues/410 for details
  9380. return function() {
  9381. process.nextTick(lib$es6$promise$asap$$flush);
  9382. };
  9383. }
  9384. // vertx
  9385. function lib$es6$promise$asap$$useVertxTimer() {
  9386. return function() {
  9387. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  9388. };
  9389. }
  9390. function lib$es6$promise$asap$$useMutationObserver() {
  9391. var iterations = 0;
  9392. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  9393. var node = document.createTextNode('');
  9394. observer.observe(node, { characterData: true });
  9395. return function() {
  9396. node.data = (iterations = ++iterations % 2);
  9397. };
  9398. }
  9399. // web worker
  9400. function lib$es6$promise$asap$$useMessageChannel() {
  9401. var channel = new MessageChannel();
  9402. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  9403. return function () {
  9404. channel.port2.postMessage(0);
  9405. };
  9406. }
  9407. function lib$es6$promise$asap$$useSetTimeout() {
  9408. return function() {
  9409. setTimeout(lib$es6$promise$asap$$flush, 1);
  9410. };
  9411. }
  9412. var lib$es6$promise$asap$$queue = new Array(1000);
  9413. function lib$es6$promise$asap$$flush() {
  9414. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  9415. var callback = lib$es6$promise$asap$$queue[i];
  9416. var arg = lib$es6$promise$asap$$queue[i+1];
  9417. callback(arg);
  9418. lib$es6$promise$asap$$queue[i] = undefined;
  9419. lib$es6$promise$asap$$queue[i+1] = undefined;
  9420. }
  9421. lib$es6$promise$asap$$len = 0;
  9422. }
  9423. function lib$es6$promise$asap$$attemptVertx() {
  9424. try {
  9425. var r = require;
  9426. var vertx = r('vertx');
  9427. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  9428. return lib$es6$promise$asap$$useVertxTimer();
  9429. } catch(e) {
  9430. return lib$es6$promise$asap$$useSetTimeout();
  9431. }
  9432. }
  9433. var lib$es6$promise$asap$$scheduleFlush;
  9434. // Decide what async method to use to triggering processing of queued callbacks:
  9435. if (lib$es6$promise$asap$$isNode) {
  9436. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  9437. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  9438. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  9439. } else if (lib$es6$promise$asap$$isWorker) {
  9440. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  9441. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  9442. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  9443. } else {
  9444. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  9445. }
  9446. function lib$es6$promise$$internal$$noop() {}
  9447. var lib$es6$promise$$internal$$PENDING = void 0;
  9448. var lib$es6$promise$$internal$$FULFILLED = 1;
  9449. var lib$es6$promise$$internal$$REJECTED = 2;
  9450. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  9451. function lib$es6$promise$$internal$$selfFulfillment() {
  9452. return new TypeError("You cannot resolve a promise with itself");
  9453. }
  9454. function lib$es6$promise$$internal$$cannotReturnOwn() {
  9455. return new TypeError('A promises callback cannot return that same promise.');
  9456. }
  9457. function lib$es6$promise$$internal$$getThen(promise) {
  9458. try {
  9459. return promise.then;
  9460. } catch(error) {
  9461. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  9462. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  9463. }
  9464. }
  9465. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  9466. try {
  9467. then.call(value, fulfillmentHandler, rejectionHandler);
  9468. } catch(e) {
  9469. return e;
  9470. }
  9471. }
  9472. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  9473. lib$es6$promise$asap$$asap(function(promise) {
  9474. var sealed = false;
  9475. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  9476. if (sealed) { return; }
  9477. sealed = true;
  9478. if (thenable !== value) {
  9479. lib$es6$promise$$internal$$resolve(promise, value);
  9480. } else {
  9481. lib$es6$promise$$internal$$fulfill(promise, value);
  9482. }
  9483. }, function(reason) {
  9484. if (sealed) { return; }
  9485. sealed = true;
  9486. lib$es6$promise$$internal$$reject(promise, reason);
  9487. }, 'Settle: ' + (promise._label || ' unknown promise'));
  9488. if (!sealed && error) {
  9489. sealed = true;
  9490. lib$es6$promise$$internal$$reject(promise, error);
  9491. }
  9492. }, promise);
  9493. }
  9494. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  9495. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  9496. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  9497. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  9498. lib$es6$promise$$internal$$reject(promise, thenable._result);
  9499. } else {
  9500. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  9501. lib$es6$promise$$internal$$resolve(promise, value);
  9502. }, function(reason) {
  9503. lib$es6$promise$$internal$$reject(promise, reason);
  9504. });
  9505. }
  9506. }
  9507. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  9508. if (maybeThenable.constructor === promise.constructor) {
  9509. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  9510. } else {
  9511. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  9512. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  9513. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  9514. } else if (then === undefined) {
  9515. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  9516. } else if (lib$es6$promise$utils$$isFunction(then)) {
  9517. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  9518. } else {
  9519. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  9520. }
  9521. }
  9522. }
  9523. function lib$es6$promise$$internal$$resolve(promise, value) {
  9524. if (promise === value) {
  9525. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  9526. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  9527. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  9528. } else {
  9529. lib$es6$promise$$internal$$fulfill(promise, value);
  9530. }
  9531. }
  9532. function lib$es6$promise$$internal$$publishRejection(promise) {
  9533. if (promise._onerror) {
  9534. promise._onerror(promise._result);
  9535. }
  9536. lib$es6$promise$$internal$$publish(promise);
  9537. }
  9538. function lib$es6$promise$$internal$$fulfill(promise, value) {
  9539. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  9540. promise._result = value;
  9541. promise._state = lib$es6$promise$$internal$$FULFILLED;
  9542. if (promise._subscribers.length !== 0) {
  9543. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  9544. }
  9545. }
  9546. function lib$es6$promise$$internal$$reject(promise, reason) {
  9547. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  9548. promise._state = lib$es6$promise$$internal$$REJECTED;
  9549. promise._result = reason;
  9550. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  9551. }
  9552. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  9553. var subscribers = parent._subscribers;
  9554. var length = subscribers.length;
  9555. parent._onerror = null;
  9556. subscribers[length] = child;
  9557. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  9558. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  9559. if (length === 0 && parent._state) {
  9560. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  9561. }
  9562. }
  9563. function lib$es6$promise$$internal$$publish(promise) {
  9564. var subscribers = promise._subscribers;
  9565. var settled = promise._state;
  9566. if (subscribers.length === 0) { return; }
  9567. var child, callback, detail = promise._result;
  9568. for (var i = 0; i < subscribers.length; i += 3) {
  9569. child = subscribers[i];
  9570. callback = subscribers[i + settled];
  9571. if (child) {
  9572. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  9573. } else {
  9574. callback(detail);
  9575. }
  9576. }
  9577. promise._subscribers.length = 0;
  9578. }
  9579. function lib$es6$promise$$internal$$ErrorObject() {
  9580. this.error = null;
  9581. }
  9582. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  9583. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  9584. try {
  9585. return callback(detail);
  9586. } catch(e) {
  9587. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  9588. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  9589. }
  9590. }
  9591. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  9592. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  9593. value, error, succeeded, failed;
  9594. if (hasCallback) {
  9595. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  9596. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  9597. failed = true;
  9598. error = value.error;
  9599. value = null;
  9600. } else {
  9601. succeeded = true;
  9602. }
  9603. if (promise === value) {
  9604. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  9605. return;
  9606. }
  9607. } else {
  9608. value = detail;
  9609. succeeded = true;
  9610. }
  9611. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  9612. // noop
  9613. } else if (hasCallback && succeeded) {
  9614. lib$es6$promise$$internal$$resolve(promise, value);
  9615. } else if (failed) {
  9616. lib$es6$promise$$internal$$reject(promise, error);
  9617. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  9618. lib$es6$promise$$internal$$fulfill(promise, value);
  9619. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  9620. lib$es6$promise$$internal$$reject(promise, value);
  9621. }
  9622. }
  9623. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  9624. try {
  9625. resolver(function resolvePromise(value){
  9626. lib$es6$promise$$internal$$resolve(promise, value);
  9627. }, function rejectPromise(reason) {
  9628. lib$es6$promise$$internal$$reject(promise, reason);
  9629. });
  9630. } catch(e) {
  9631. lib$es6$promise$$internal$$reject(promise, e);
  9632. }
  9633. }
  9634. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  9635. var enumerator = this;
  9636. enumerator._instanceConstructor = Constructor;
  9637. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  9638. if (enumerator._validateInput(input)) {
  9639. enumerator._input = input;
  9640. enumerator.length = input.length;
  9641. enumerator._remaining = input.length;
  9642. enumerator._init();
  9643. if (enumerator.length === 0) {
  9644. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  9645. } else {
  9646. enumerator.length = enumerator.length || 0;
  9647. enumerator._enumerate();
  9648. if (enumerator._remaining === 0) {
  9649. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  9650. }
  9651. }
  9652. } else {
  9653. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  9654. }
  9655. }
  9656. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  9657. return lib$es6$promise$utils$$isArray(input);
  9658. };
  9659. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  9660. return new Error('Array Methods must be provided an Array');
  9661. };
  9662. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  9663. this._result = new Array(this.length);
  9664. };
  9665. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  9666. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  9667. var enumerator = this;
  9668. var length = enumerator.length;
  9669. var promise = enumerator.promise;
  9670. var input = enumerator._input;
  9671. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9672. enumerator._eachEntry(input[i], i);
  9673. }
  9674. };
  9675. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  9676. var enumerator = this;
  9677. var c = enumerator._instanceConstructor;
  9678. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  9679. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  9680. entry._onerror = null;
  9681. enumerator._settledAt(entry._state, i, entry._result);
  9682. } else {
  9683. enumerator._willSettleAt(c.resolve(entry), i);
  9684. }
  9685. } else {
  9686. enumerator._remaining--;
  9687. enumerator._result[i] = entry;
  9688. }
  9689. };
  9690. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  9691. var enumerator = this;
  9692. var promise = enumerator.promise;
  9693. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  9694. enumerator._remaining--;
  9695. if (state === lib$es6$promise$$internal$$REJECTED) {
  9696. lib$es6$promise$$internal$$reject(promise, value);
  9697. } else {
  9698. enumerator._result[i] = value;
  9699. }
  9700. }
  9701. if (enumerator._remaining === 0) {
  9702. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  9703. }
  9704. };
  9705. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  9706. var enumerator = this;
  9707. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  9708. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  9709. }, function(reason) {
  9710. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  9711. });
  9712. };
  9713. function lib$es6$promise$promise$all$$all(entries) {
  9714. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  9715. }
  9716. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  9717. function lib$es6$promise$promise$race$$race(entries) {
  9718. /*jshint validthis:true */
  9719. var Constructor = this;
  9720. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9721. if (!lib$es6$promise$utils$$isArray(entries)) {
  9722. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  9723. return promise;
  9724. }
  9725. var length = entries.length;
  9726. function onFulfillment(value) {
  9727. lib$es6$promise$$internal$$resolve(promise, value);
  9728. }
  9729. function onRejection(reason) {
  9730. lib$es6$promise$$internal$$reject(promise, reason);
  9731. }
  9732. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9733. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  9734. }
  9735. return promise;
  9736. }
  9737. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  9738. function lib$es6$promise$promise$resolve$$resolve(object) {
  9739. /*jshint validthis:true */
  9740. var Constructor = this;
  9741. if (object && typeof object === 'object' && object.constructor === Constructor) {
  9742. return object;
  9743. }
  9744. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9745. lib$es6$promise$$internal$$resolve(promise, object);
  9746. return promise;
  9747. }
  9748. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  9749. function lib$es6$promise$promise$reject$$reject(reason) {
  9750. /*jshint validthis:true */
  9751. var Constructor = this;
  9752. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9753. lib$es6$promise$$internal$$reject(promise, reason);
  9754. return promise;
  9755. }
  9756. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  9757. var lib$es6$promise$promise$$counter = 0;
  9758. function lib$es6$promise$promise$$needsResolver() {
  9759. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  9760. }
  9761. function lib$es6$promise$promise$$needsNew() {
  9762. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  9763. }
  9764. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  9765. /**
  9766. Promise objects represent the eventual result of an asynchronous operation. The
  9767. primary way of interacting with a promise is through its `then` method, which
  9768. registers callbacks to receive either a promise's eventual value or the reason
  9769. why the promise cannot be fulfilled.
  9770. Terminology
  9771. -----------
  9772. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  9773. - `thenable` is an object or function that defines a `then` method.
  9774. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  9775. - `exception` is a value that is thrown using the throw statement.
  9776. - `reason` is a value that indicates why a promise was rejected.
  9777. - `settled` the final resting state of a promise, fulfilled or rejected.
  9778. A promise can be in one of three states: pending, fulfilled, or rejected.
  9779. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  9780. state. Promises that are rejected have a rejection reason and are in the
  9781. rejected state. A fulfillment value is never a thenable.
  9782. Promises can also be said to *resolve* a value. If this value is also a
  9783. promise, then the original promise's settled state will match the value's
  9784. settled state. So a promise that *resolves* a promise that rejects will
  9785. itself reject, and a promise that *resolves* a promise that fulfills will
  9786. itself fulfill.
  9787. Basic Usage:
  9788. ------------
  9789. ```js
  9790. var promise = new Promise(function(resolve, reject) {
  9791. // on success
  9792. resolve(value);
  9793. // on failure
  9794. reject(reason);
  9795. });
  9796. promise.then(function(value) {
  9797. // on fulfillment
  9798. }, function(reason) {
  9799. // on rejection
  9800. });
  9801. ```
  9802. Advanced Usage:
  9803. ---------------
  9804. Promises shine when abstracting away asynchronous interactions such as
  9805. `XMLHttpRequest`s.
  9806. ```js
  9807. function getJSON(url) {
  9808. return new Promise(function(resolve, reject){
  9809. var xhr = new XMLHttpRequest();
  9810. xhr.open('GET', url);
  9811. xhr.onreadystatechange = handler;
  9812. xhr.responseType = 'json';
  9813. xhr.setRequestHeader('Accept', 'application/json');
  9814. xhr.send();
  9815. function handler() {
  9816. if (this.readyState === this.DONE) {
  9817. if (this.status === 200) {
  9818. resolve(this.response);
  9819. } else {
  9820. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  9821. }
  9822. }
  9823. };
  9824. });
  9825. }
  9826. getJSON('/posts.json').then(function(json) {
  9827. // on fulfillment
  9828. }, function(reason) {
  9829. // on rejection
  9830. });
  9831. ```
  9832. Unlike callbacks, promises are great composable primitives.
  9833. ```js
  9834. Promise.all([
  9835. getJSON('/posts'),
  9836. getJSON('/comments')
  9837. ]).then(function(values){
  9838. values[0] // => postsJSON
  9839. values[1] // => commentsJSON
  9840. return values;
  9841. });
  9842. ```
  9843. @class Promise
  9844. @param {function} resolver
  9845. Useful for tooling.
  9846. @constructor
  9847. */
  9848. function lib$es6$promise$promise$$Promise(resolver) {
  9849. this._id = lib$es6$promise$promise$$counter++;
  9850. this._state = undefined;
  9851. this._result = undefined;
  9852. this._subscribers = [];
  9853. if (lib$es6$promise$$internal$$noop !== resolver) {
  9854. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  9855. lib$es6$promise$promise$$needsResolver();
  9856. }
  9857. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  9858. lib$es6$promise$promise$$needsNew();
  9859. }
  9860. lib$es6$promise$$internal$$initializePromise(this, resolver);
  9861. }
  9862. }
  9863. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  9864. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  9865. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  9866. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  9867. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  9868. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  9869. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  9870. lib$es6$promise$promise$$Promise.prototype = {
  9871. constructor: lib$es6$promise$promise$$Promise,
  9872. /**
  9873. The primary way of interacting with a promise is through its `then` method,
  9874. which registers callbacks to receive either a promise's eventual value or the
  9875. reason why the promise cannot be fulfilled.
  9876. ```js
  9877. findUser().then(function(user){
  9878. // user is available
  9879. }, function(reason){
  9880. // user is unavailable, and you are given the reason why
  9881. });
  9882. ```
  9883. Chaining
  9884. --------
  9885. The return value of `then` is itself a promise. This second, 'downstream'
  9886. promise is resolved with the return value of the first promise's fulfillment
  9887. or rejection handler, or rejected if the handler throws an exception.
  9888. ```js
  9889. findUser().then(function (user) {
  9890. return user.name;
  9891. }, function (reason) {
  9892. return 'default name';
  9893. }).then(function (userName) {
  9894. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  9895. // will be `'default name'`
  9896. });
  9897. findUser().then(function (user) {
  9898. throw new Error('Found user, but still unhappy');
  9899. }, function (reason) {
  9900. throw new Error('`findUser` rejected and we're unhappy');
  9901. }).then(function (value) {
  9902. // never reached
  9903. }, function (reason) {
  9904. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  9905. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  9906. });
  9907. ```
  9908. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  9909. ```js
  9910. findUser().then(function (user) {
  9911. throw new PedagogicalException('Upstream error');
  9912. }).then(function (value) {
  9913. // never reached
  9914. }).then(function (value) {
  9915. // never reached
  9916. }, function (reason) {
  9917. // The `PedgagocialException` is propagated all the way down to here
  9918. });
  9919. ```
  9920. Assimilation
  9921. ------------
  9922. Sometimes the value you want to propagate to a downstream promise can only be
  9923. retrieved asynchronously. This can be achieved by returning a promise in the
  9924. fulfillment or rejection handler. The downstream promise will then be pending
  9925. until the returned promise is settled. This is called *assimilation*.
  9926. ```js
  9927. findUser().then(function (user) {
  9928. return findCommentsByAuthor(user);
  9929. }).then(function (comments) {
  9930. // The user's comments are now available
  9931. });
  9932. ```
  9933. If the assimliated promise rejects, then the downstream promise will also reject.
  9934. ```js
  9935. findUser().then(function (user) {
  9936. return findCommentsByAuthor(user);
  9937. }).then(function (comments) {
  9938. // If `findCommentsByAuthor` fulfills, we'll have the value here
  9939. }, function (reason) {
  9940. // If `findCommentsByAuthor` rejects, we'll have the reason here
  9941. });
  9942. ```
  9943. Simple Example
  9944. --------------
  9945. Synchronous Example
  9946. ```javascript
  9947. var result;
  9948. try {
  9949. result = findResult();
  9950. // success
  9951. } catch(reason) {
  9952. // failure
  9953. }
  9954. ```
  9955. Errback Example
  9956. ```js
  9957. findResult(function(result, err){
  9958. if (err) {
  9959. // failure
  9960. } else {
  9961. // success
  9962. }
  9963. });
  9964. ```
  9965. Promise Example;
  9966. ```javascript
  9967. findResult().then(function(result){
  9968. // success
  9969. }, function(reason){
  9970. // failure
  9971. });
  9972. ```
  9973. Advanced Example
  9974. --------------
  9975. Synchronous Example
  9976. ```javascript
  9977. var author, books;
  9978. try {
  9979. author = findAuthor();
  9980. books = findBooksByAuthor(author);
  9981. // success
  9982. } catch(reason) {
  9983. // failure
  9984. }
  9985. ```
  9986. Errback Example
  9987. ```js
  9988. function foundBooks(books) {
  9989. }
  9990. function failure(reason) {
  9991. }
  9992. findAuthor(function(author, err){
  9993. if (err) {
  9994. failure(err);
  9995. // failure
  9996. } else {
  9997. try {
  9998. findBoooksByAuthor(author, function(books, err) {
  9999. if (err) {
  10000. failure(err);
  10001. } else {
  10002. try {
  10003. foundBooks(books);
  10004. } catch(reason) {
  10005. failure(reason);
  10006. }
  10007. }
  10008. });
  10009. } catch(error) {
  10010. failure(err);
  10011. }
  10012. // success
  10013. }
  10014. });
  10015. ```
  10016. Promise Example;
  10017. ```javascript
  10018. findAuthor().
  10019. then(findBooksByAuthor).
  10020. then(function(books){
  10021. // found books
  10022. }).catch(function(reason){
  10023. // something went wrong
  10024. });
  10025. ```
  10026. @method then
  10027. @param {Function} onFulfilled
  10028. @param {Function} onRejected
  10029. Useful for tooling.
  10030. @return {Promise}
  10031. */
  10032. then: function(onFulfillment, onRejection) {
  10033. var parent = this;
  10034. var state = parent._state;
  10035. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  10036. return this;
  10037. }
  10038. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  10039. var result = parent._result;
  10040. if (state) {
  10041. var callback = arguments[state - 1];
  10042. lib$es6$promise$asap$$asap(function(){
  10043. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  10044. });
  10045. } else {
  10046. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  10047. }
  10048. return child;
  10049. },
  10050. /**
  10051. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  10052. as the catch block of a try/catch statement.
  10053. ```js
  10054. function findAuthor(){
  10055. throw new Error('couldn't find that author');
  10056. }
  10057. // synchronous
  10058. try {
  10059. findAuthor();
  10060. } catch(reason) {
  10061. // something went wrong
  10062. }
  10063. // async with promises
  10064. findAuthor().catch(function(reason){
  10065. // something went wrong
  10066. });
  10067. ```
  10068. @method catch
  10069. @param {Function} onRejection
  10070. Useful for tooling.
  10071. @return {Promise}
  10072. */
  10073. 'catch': function(onRejection) {
  10074. return this.then(null, onRejection);
  10075. }
  10076. };
  10077. function lib$es6$promise$polyfill$$polyfill() {
  10078. var local;
  10079. if (typeof global !== 'undefined') {
  10080. local = global;
  10081. } else if (typeof self !== 'undefined') {
  10082. local = self;
  10083. } else {
  10084. try {
  10085. local = Function('return this')();
  10086. } catch (e) {
  10087. throw new Error('polyfill failed because global object is unavailable in this environment');
  10088. }
  10089. }
  10090. var P = local.Promise;
  10091. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  10092. return;
  10093. }
  10094. local.Promise = lib$es6$promise$promise$$default;
  10095. }
  10096. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  10097. var lib$es6$promise$umd$$ES6Promise = {
  10098. 'Promise': lib$es6$promise$promise$$default,
  10099. 'polyfill': lib$es6$promise$polyfill$$default
  10100. };
  10101. /* global define:true module:true window: true */
  10102. if (typeof define === 'function' && define['amd']) {
  10103. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  10104. } else if (typeof module !== 'undefined' && module['exports']) {
  10105. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  10106. } else if (typeof this !== 'undefined') {
  10107. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  10108. }
  10109. lib$es6$promise$polyfill$$default();
  10110. }).call(this);
  10111. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  10112. },{"_process":78}],36:[function(require,module,exports){
  10113. // Top level file is just a mixin of submodules & constants
  10114. 'use strict';
  10115. var assign = require('./lib/utils/common').assign;
  10116. var deflate = require('./lib/deflate');
  10117. var inflate = require('./lib/inflate');
  10118. var constants = require('./lib/zlib/constants');
  10119. var pako = {};
  10120. assign(pako, deflate, inflate, constants);
  10121. module.exports = pako;
  10122. },{"./lib/deflate":37,"./lib/inflate":38,"./lib/utils/common":39,"./lib/zlib/constants":42}],37:[function(require,module,exports){
  10123. 'use strict';
  10124. var zlib_deflate = require('./zlib/deflate.js');
  10125. var utils = require('./utils/common');
  10126. var strings = require('./utils/strings');
  10127. var msg = require('./zlib/messages');
  10128. var zstream = require('./zlib/zstream');
  10129. var toString = Object.prototype.toString;
  10130. /* Public constants ==========================================================*/
  10131. /* ===========================================================================*/
  10132. var Z_NO_FLUSH = 0;
  10133. var Z_FINISH = 4;
  10134. var Z_OK = 0;
  10135. var Z_STREAM_END = 1;
  10136. var Z_SYNC_FLUSH = 2;
  10137. var Z_DEFAULT_COMPRESSION = -1;
  10138. var Z_DEFAULT_STRATEGY = 0;
  10139. var Z_DEFLATED = 8;
  10140. /* ===========================================================================*/
  10141. /**
  10142. * class Deflate
  10143. *
  10144. * Generic JS-style wrapper for zlib calls. If you don't need
  10145. * streaming behaviour - use more simple functions: [[deflate]],
  10146. * [[deflateRaw]] and [[gzip]].
  10147. **/
  10148. /* internal
  10149. * Deflate.chunks -> Array
  10150. *
  10151. * Chunks of output data, if [[Deflate#onData]] not overriden.
  10152. **/
  10153. /**
  10154. * Deflate.result -> Uint8Array|Array
  10155. *
  10156. * Compressed result, generated by default [[Deflate#onData]]
  10157. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  10158. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  10159. * push a chunk with explicit flush (call [[Deflate#push]] with
  10160. * `Z_SYNC_FLUSH` param).
  10161. **/
  10162. /**
  10163. * Deflate.err -> Number
  10164. *
  10165. * Error code after deflate finished. 0 (Z_OK) on success.
  10166. * You will not need it in real life, because deflate errors
  10167. * are possible only on wrong options or bad `onData` / `onEnd`
  10168. * custom handlers.
  10169. **/
  10170. /**
  10171. * Deflate.msg -> String
  10172. *
  10173. * Error message, if [[Deflate.err]] != 0
  10174. **/
  10175. /**
  10176. * new Deflate(options)
  10177. * - options (Object): zlib deflate options.
  10178. *
  10179. * Creates new deflator instance with specified params. Throws exception
  10180. * on bad params. Supported options:
  10181. *
  10182. * - `level`
  10183. * - `windowBits`
  10184. * - `memLevel`
  10185. * - `strategy`
  10186. *
  10187. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10188. * for more information on these.
  10189. *
  10190. * Additional options, for internal needs:
  10191. *
  10192. * - `chunkSize` - size of generated data chunks (16K by default)
  10193. * - `raw` (Boolean) - do raw deflate
  10194. * - `gzip` (Boolean) - create gzip wrapper
  10195. * - `to` (String) - if equal to 'string', then result will be "binary string"
  10196. * (each char code [0..255])
  10197. * - `header` (Object) - custom header for gzip
  10198. * - `text` (Boolean) - true if compressed data believed to be text
  10199. * - `time` (Number) - modification time, unix timestamp
  10200. * - `os` (Number) - operation system code
  10201. * - `extra` (Array) - array of bytes with extra data (max 65536)
  10202. * - `name` (String) - file name (binary string)
  10203. * - `comment` (String) - comment (binary string)
  10204. * - `hcrc` (Boolean) - true if header crc should be added
  10205. *
  10206. * ##### Example:
  10207. *
  10208. * ```javascript
  10209. * var pako = require('pako')
  10210. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  10211. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  10212. *
  10213. * var deflate = new pako.Deflate({ level: 3});
  10214. *
  10215. * deflate.push(chunk1, false);
  10216. * deflate.push(chunk2, true); // true -> last chunk
  10217. *
  10218. * if (deflate.err) { throw new Error(deflate.err); }
  10219. *
  10220. * console.log(deflate.result);
  10221. * ```
  10222. **/
  10223. var Deflate = function(options) {
  10224. this.options = utils.assign({
  10225. level: Z_DEFAULT_COMPRESSION,
  10226. method: Z_DEFLATED,
  10227. chunkSize: 16384,
  10228. windowBits: 15,
  10229. memLevel: 8,
  10230. strategy: Z_DEFAULT_STRATEGY,
  10231. to: ''
  10232. }, options || {});
  10233. var opt = this.options;
  10234. if (opt.raw && (opt.windowBits > 0)) {
  10235. opt.windowBits = -opt.windowBits;
  10236. }
  10237. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  10238. opt.windowBits += 16;
  10239. }
  10240. this.err = 0; // error code, if happens (0 = Z_OK)
  10241. this.msg = ''; // error message
  10242. this.ended = false; // used to avoid multiple onEnd() calls
  10243. this.chunks = []; // chunks of compressed data
  10244. this.strm = new zstream();
  10245. this.strm.avail_out = 0;
  10246. var status = zlib_deflate.deflateInit2(
  10247. this.strm,
  10248. opt.level,
  10249. opt.method,
  10250. opt.windowBits,
  10251. opt.memLevel,
  10252. opt.strategy
  10253. );
  10254. if (status !== Z_OK) {
  10255. throw new Error(msg[status]);
  10256. }
  10257. if (opt.header) {
  10258. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  10259. }
  10260. };
  10261. /**
  10262. * Deflate#push(data[, mode]) -> Boolean
  10263. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  10264. * converted to utf8 byte sequence.
  10265. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  10266. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  10267. *
  10268. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  10269. * new compressed chunks. Returns `true` on success. The last data block must have
  10270. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  10271. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  10272. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  10273. *
  10274. * On fail call [[Deflate#onEnd]] with error code and return false.
  10275. *
  10276. * We strongly recommend to use `Uint8Array` on input for best speed (output
  10277. * array format is detected automatically). Also, don't skip last param and always
  10278. * use the same type in your code (boolean or number). That will improve JS speed.
  10279. *
  10280. * For regular `Array`-s make sure all elements are [0..255].
  10281. *
  10282. * ##### Example
  10283. *
  10284. * ```javascript
  10285. * push(chunk, false); // push one of data chunks
  10286. * ...
  10287. * push(chunk, true); // push last chunk
  10288. * ```
  10289. **/
  10290. Deflate.prototype.push = function(data, mode) {
  10291. var strm = this.strm;
  10292. var chunkSize = this.options.chunkSize;
  10293. var status, _mode;
  10294. if (this.ended) { return false; }
  10295. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  10296. // Convert data if needed
  10297. if (typeof data === 'string') {
  10298. // If we need to compress text, change encoding to utf8.
  10299. strm.input = strings.string2buf(data);
  10300. } else if (toString.call(data) === '[object ArrayBuffer]') {
  10301. strm.input = new Uint8Array(data);
  10302. } else {
  10303. strm.input = data;
  10304. }
  10305. strm.next_in = 0;
  10306. strm.avail_in = strm.input.length;
  10307. do {
  10308. if (strm.avail_out === 0) {
  10309. strm.output = new utils.Buf8(chunkSize);
  10310. strm.next_out = 0;
  10311. strm.avail_out = chunkSize;
  10312. }
  10313. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  10314. if (status !== Z_STREAM_END && status !== Z_OK) {
  10315. this.onEnd(status);
  10316. this.ended = true;
  10317. return false;
  10318. }
  10319. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  10320. if (this.options.to === 'string') {
  10321. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  10322. } else {
  10323. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  10324. }
  10325. }
  10326. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  10327. // Finalize on the last chunk.
  10328. if (_mode === Z_FINISH) {
  10329. status = zlib_deflate.deflateEnd(this.strm);
  10330. this.onEnd(status);
  10331. this.ended = true;
  10332. return status === Z_OK;
  10333. }
  10334. // callback interim results if Z_SYNC_FLUSH.
  10335. if (_mode === Z_SYNC_FLUSH) {
  10336. this.onEnd(Z_OK);
  10337. strm.avail_out = 0;
  10338. return true;
  10339. }
  10340. return true;
  10341. };
  10342. /**
  10343. * Deflate#onData(chunk) -> Void
  10344. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  10345. * on js engine support. When string output requested, each chunk
  10346. * will be string.
  10347. *
  10348. * By default, stores data blocks in `chunks[]` property and glue
  10349. * those in `onEnd`. Override this handler, if you need another behaviour.
  10350. **/
  10351. Deflate.prototype.onData = function(chunk) {
  10352. this.chunks.push(chunk);
  10353. };
  10354. /**
  10355. * Deflate#onEnd(status) -> Void
  10356. * - status (Number): deflate status. 0 (Z_OK) on success,
  10357. * other if not.
  10358. *
  10359. * Called once after you tell deflate that the input stream is
  10360. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  10361. * or if an error happened. By default - join collected chunks,
  10362. * free memory and fill `results` / `err` properties.
  10363. **/
  10364. Deflate.prototype.onEnd = function(status) {
  10365. // On success - join
  10366. if (status === Z_OK) {
  10367. if (this.options.to === 'string') {
  10368. this.result = this.chunks.join('');
  10369. } else {
  10370. this.result = utils.flattenChunks(this.chunks);
  10371. }
  10372. }
  10373. this.chunks = [];
  10374. this.err = status;
  10375. this.msg = this.strm.msg;
  10376. };
  10377. /**
  10378. * deflate(data[, options]) -> Uint8Array|Array|String
  10379. * - data (Uint8Array|Array|String): input data to compress.
  10380. * - options (Object): zlib deflate options.
  10381. *
  10382. * Compress `data` with deflate alrorythm and `options`.
  10383. *
  10384. * Supported options are:
  10385. *
  10386. * - level
  10387. * - windowBits
  10388. * - memLevel
  10389. * - strategy
  10390. *
  10391. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10392. * for more information on these.
  10393. *
  10394. * Sugar (options):
  10395. *
  10396. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10397. * negative windowBits implicitly.
  10398. * - `to` (String) - if equal to 'string', then result will be "binary string"
  10399. * (each char code [0..255])
  10400. *
  10401. * ##### Example:
  10402. *
  10403. * ```javascript
  10404. * var pako = require('pako')
  10405. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  10406. *
  10407. * console.log(pako.deflate(data));
  10408. * ```
  10409. **/
  10410. function deflate(input, options) {
  10411. var deflator = new Deflate(options);
  10412. deflator.push(input, true);
  10413. // That will never happens, if you don't cheat with options :)
  10414. if (deflator.err) { throw deflator.msg; }
  10415. return deflator.result;
  10416. }
  10417. /**
  10418. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  10419. * - data (Uint8Array|Array|String): input data to compress.
  10420. * - options (Object): zlib deflate options.
  10421. *
  10422. * The same as [[deflate]], but creates raw data, without wrapper
  10423. * (header and adler32 crc).
  10424. **/
  10425. function deflateRaw(input, options) {
  10426. options = options || {};
  10427. options.raw = true;
  10428. return deflate(input, options);
  10429. }
  10430. /**
  10431. * gzip(data[, options]) -> Uint8Array|Array|String
  10432. * - data (Uint8Array|Array|String): input data to compress.
  10433. * - options (Object): zlib deflate options.
  10434. *
  10435. * The same as [[deflate]], but create gzip wrapper instead of
  10436. * deflate one.
  10437. **/
  10438. function gzip(input, options) {
  10439. options = options || {};
  10440. options.gzip = true;
  10441. return deflate(input, options);
  10442. }
  10443. exports.Deflate = Deflate;
  10444. exports.deflate = deflate;
  10445. exports.deflateRaw = deflateRaw;
  10446. exports.gzip = gzip;
  10447. },{"./utils/common":39,"./utils/strings":40,"./zlib/deflate.js":44,"./zlib/messages":49,"./zlib/zstream":51}],38:[function(require,module,exports){
  10448. 'use strict';
  10449. var zlib_inflate = require('./zlib/inflate.js');
  10450. var utils = require('./utils/common');
  10451. var strings = require('./utils/strings');
  10452. var c = require('./zlib/constants');
  10453. var msg = require('./zlib/messages');
  10454. var zstream = require('./zlib/zstream');
  10455. var gzheader = require('./zlib/gzheader');
  10456. var toString = Object.prototype.toString;
  10457. /**
  10458. * class Inflate
  10459. *
  10460. * Generic JS-style wrapper for zlib calls. If you don't need
  10461. * streaming behaviour - use more simple functions: [[inflate]]
  10462. * and [[inflateRaw]].
  10463. **/
  10464. /* internal
  10465. * inflate.chunks -> Array
  10466. *
  10467. * Chunks of output data, if [[Inflate#onData]] not overriden.
  10468. **/
  10469. /**
  10470. * Inflate.result -> Uint8Array|Array|String
  10471. *
  10472. * Uncompressed result, generated by default [[Inflate#onData]]
  10473. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  10474. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  10475. * push a chunk with explicit flush (call [[Inflate#push]] with
  10476. * `Z_SYNC_FLUSH` param).
  10477. **/
  10478. /**
  10479. * Inflate.err -> Number
  10480. *
  10481. * Error code after inflate finished. 0 (Z_OK) on success.
  10482. * Should be checked if broken data possible.
  10483. **/
  10484. /**
  10485. * Inflate.msg -> String
  10486. *
  10487. * Error message, if [[Inflate.err]] != 0
  10488. **/
  10489. /**
  10490. * new Inflate(options)
  10491. * - options (Object): zlib inflate options.
  10492. *
  10493. * Creates new inflator instance with specified params. Throws exception
  10494. * on bad params. Supported options:
  10495. *
  10496. * - `windowBits`
  10497. *
  10498. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10499. * for more information on these.
  10500. *
  10501. * Additional options, for internal needs:
  10502. *
  10503. * - `chunkSize` - size of generated data chunks (16K by default)
  10504. * - `raw` (Boolean) - do raw inflate
  10505. * - `to` (String) - if equal to 'string', then result will be converted
  10506. * from utf8 to utf16 (javascript) string. When string output requested,
  10507. * chunk length can differ from `chunkSize`, depending on content.
  10508. *
  10509. * By default, when no options set, autodetect deflate/gzip data format via
  10510. * wrapper header.
  10511. *
  10512. * ##### Example:
  10513. *
  10514. * ```javascript
  10515. * var pako = require('pako')
  10516. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  10517. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  10518. *
  10519. * var inflate = new pako.Inflate({ level: 3});
  10520. *
  10521. * inflate.push(chunk1, false);
  10522. * inflate.push(chunk2, true); // true -> last chunk
  10523. *
  10524. * if (inflate.err) { throw new Error(inflate.err); }
  10525. *
  10526. * console.log(inflate.result);
  10527. * ```
  10528. **/
  10529. var Inflate = function(options) {
  10530. this.options = utils.assign({
  10531. chunkSize: 16384,
  10532. windowBits: 0,
  10533. to: ''
  10534. }, options || {});
  10535. var opt = this.options;
  10536. // Force window size for `raw` data, if not set directly,
  10537. // because we have no header for autodetect.
  10538. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  10539. opt.windowBits = -opt.windowBits;
  10540. if (opt.windowBits === 0) { opt.windowBits = -15; }
  10541. }
  10542. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  10543. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  10544. !(options && options.windowBits)) {
  10545. opt.windowBits += 32;
  10546. }
  10547. // Gzip header has no info about windows size, we can do autodetect only
  10548. // for deflate. So, if window size not set, force it to max when gzip possible
  10549. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  10550. // bit 3 (16) -> gzipped data
  10551. // bit 4 (32) -> autodetect gzip/deflate
  10552. if ((opt.windowBits & 15) === 0) {
  10553. opt.windowBits |= 15;
  10554. }
  10555. }
  10556. this.err = 0; // error code, if happens (0 = Z_OK)
  10557. this.msg = ''; // error message
  10558. this.ended = false; // used to avoid multiple onEnd() calls
  10559. this.chunks = []; // chunks of compressed data
  10560. this.strm = new zstream();
  10561. this.strm.avail_out = 0;
  10562. var status = zlib_inflate.inflateInit2(
  10563. this.strm,
  10564. opt.windowBits
  10565. );
  10566. if (status !== c.Z_OK) {
  10567. throw new Error(msg[status]);
  10568. }
  10569. this.header = new gzheader();
  10570. zlib_inflate.inflateGetHeader(this.strm, this.header);
  10571. };
  10572. /**
  10573. * Inflate#push(data[, mode]) -> Boolean
  10574. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  10575. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  10576. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  10577. *
  10578. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  10579. * new output chunks. Returns `true` on success. The last data block must have
  10580. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  10581. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  10582. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  10583. *
  10584. * On fail call [[Inflate#onEnd]] with error code and return false.
  10585. *
  10586. * We strongly recommend to use `Uint8Array` on input for best speed (output
  10587. * format is detected automatically). Also, don't skip last param and always
  10588. * use the same type in your code (boolean or number). That will improve JS speed.
  10589. *
  10590. * For regular `Array`-s make sure all elements are [0..255].
  10591. *
  10592. * ##### Example
  10593. *
  10594. * ```javascript
  10595. * push(chunk, false); // push one of data chunks
  10596. * ...
  10597. * push(chunk, true); // push last chunk
  10598. * ```
  10599. **/
  10600. Inflate.prototype.push = function(data, mode) {
  10601. var strm = this.strm;
  10602. var chunkSize = this.options.chunkSize;
  10603. var status, _mode;
  10604. var next_out_utf8, tail, utf8str;
  10605. if (this.ended) { return false; }
  10606. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  10607. // Convert data if needed
  10608. if (typeof data === 'string') {
  10609. // Only binary strings can be decompressed on practice
  10610. strm.input = strings.binstring2buf(data);
  10611. } else if (toString.call(data) === '[object ArrayBuffer]') {
  10612. strm.input = new Uint8Array(data);
  10613. } else {
  10614. strm.input = data;
  10615. }
  10616. strm.next_in = 0;
  10617. strm.avail_in = strm.input.length;
  10618. do {
  10619. if (strm.avail_out === 0) {
  10620. strm.output = new utils.Buf8(chunkSize);
  10621. strm.next_out = 0;
  10622. strm.avail_out = chunkSize;
  10623. }
  10624. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  10625. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  10626. this.onEnd(status);
  10627. this.ended = true;
  10628. return false;
  10629. }
  10630. if (strm.next_out) {
  10631. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  10632. if (this.options.to === 'string') {
  10633. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  10634. tail = strm.next_out - next_out_utf8;
  10635. utf8str = strings.buf2string(strm.output, next_out_utf8);
  10636. // move tail
  10637. strm.next_out = tail;
  10638. strm.avail_out = chunkSize - tail;
  10639. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  10640. this.onData(utf8str);
  10641. } else {
  10642. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  10643. }
  10644. }
  10645. }
  10646. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  10647. if (status === c.Z_STREAM_END) {
  10648. _mode = c.Z_FINISH;
  10649. }
  10650. // Finalize on the last chunk.
  10651. if (_mode === c.Z_FINISH) {
  10652. status = zlib_inflate.inflateEnd(this.strm);
  10653. this.onEnd(status);
  10654. this.ended = true;
  10655. return status === c.Z_OK;
  10656. }
  10657. // callback interim results if Z_SYNC_FLUSH.
  10658. if (_mode === c.Z_SYNC_FLUSH) {
  10659. this.onEnd(c.Z_OK);
  10660. strm.avail_out = 0;
  10661. return true;
  10662. }
  10663. return true;
  10664. };
  10665. /**
  10666. * Inflate#onData(chunk) -> Void
  10667. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  10668. * on js engine support. When string output requested, each chunk
  10669. * will be string.
  10670. *
  10671. * By default, stores data blocks in `chunks[]` property and glue
  10672. * those in `onEnd`. Override this handler, if you need another behaviour.
  10673. **/
  10674. Inflate.prototype.onData = function(chunk) {
  10675. this.chunks.push(chunk);
  10676. };
  10677. /**
  10678. * Inflate#onEnd(status) -> Void
  10679. * - status (Number): inflate status. 0 (Z_OK) on success,
  10680. * other if not.
  10681. *
  10682. * Called either after you tell inflate that the input stream is
  10683. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  10684. * or if an error happened. By default - join collected chunks,
  10685. * free memory and fill `results` / `err` properties.
  10686. **/
  10687. Inflate.prototype.onEnd = function(status) {
  10688. // On success - join
  10689. if (status === c.Z_OK) {
  10690. if (this.options.to === 'string') {
  10691. // Glue & convert here, until we teach pako to send
  10692. // utf8 alligned strings to onData
  10693. this.result = this.chunks.join('');
  10694. } else {
  10695. this.result = utils.flattenChunks(this.chunks);
  10696. }
  10697. }
  10698. this.chunks = [];
  10699. this.err = status;
  10700. this.msg = this.strm.msg;
  10701. };
  10702. /**
  10703. * inflate(data[, options]) -> Uint8Array|Array|String
  10704. * - data (Uint8Array|Array|String): input data to decompress.
  10705. * - options (Object): zlib inflate options.
  10706. *
  10707. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  10708. * format via wrapper header by default. That's why we don't provide
  10709. * separate `ungzip` method.
  10710. *
  10711. * Supported options are:
  10712. *
  10713. * - windowBits
  10714. *
  10715. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10716. * for more information.
  10717. *
  10718. * Sugar (options):
  10719. *
  10720. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10721. * negative windowBits implicitly.
  10722. * - `to` (String) - if equal to 'string', then result will be converted
  10723. * from utf8 to utf16 (javascript) string. When string output requested,
  10724. * chunk length can differ from `chunkSize`, depending on content.
  10725. *
  10726. *
  10727. * ##### Example:
  10728. *
  10729. * ```javascript
  10730. * var pako = require('pako')
  10731. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  10732. * , output;
  10733. *
  10734. * try {
  10735. * output = pako.inflate(input);
  10736. * } catch (err)
  10737. * console.log(err);
  10738. * }
  10739. * ```
  10740. **/
  10741. function inflate(input, options) {
  10742. var inflator = new Inflate(options);
  10743. inflator.push(input, true);
  10744. // That will never happens, if you don't cheat with options :)
  10745. if (inflator.err) { throw inflator.msg; }
  10746. return inflator.result;
  10747. }
  10748. /**
  10749. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  10750. * - data (Uint8Array|Array|String): input data to decompress.
  10751. * - options (Object): zlib inflate options.
  10752. *
  10753. * The same as [[inflate]], but creates raw data, without wrapper
  10754. * (header and adler32 crc).
  10755. **/
  10756. function inflateRaw(input, options) {
  10757. options = options || {};
  10758. options.raw = true;
  10759. return inflate(input, options);
  10760. }
  10761. /**
  10762. * ungzip(data[, options]) -> Uint8Array|Array|String
  10763. * - data (Uint8Array|Array|String): input data to decompress.
  10764. * - options (Object): zlib inflate options.
  10765. *
  10766. * Just shortcut to [[inflate]], because it autodetects format
  10767. * by header.content. Done for convenience.
  10768. **/
  10769. exports.Inflate = Inflate;
  10770. exports.inflate = inflate;
  10771. exports.inflateRaw = inflateRaw;
  10772. exports.ungzip = inflate;
  10773. },{"./utils/common":39,"./utils/strings":40,"./zlib/constants":42,"./zlib/gzheader":45,"./zlib/inflate.js":47,"./zlib/messages":49,"./zlib/zstream":51}],39:[function(require,module,exports){
  10774. 'use strict';
  10775. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  10776. (typeof Uint16Array !== 'undefined') &&
  10777. (typeof Int32Array !== 'undefined');
  10778. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  10779. var sources = Array.prototype.slice.call(arguments, 1);
  10780. while (sources.length) {
  10781. var source = sources.shift();
  10782. if (!source) { continue; }
  10783. if (typeof source !== 'object') {
  10784. throw new TypeError(source + 'must be non-object');
  10785. }
  10786. for (var p in source) {
  10787. if (source.hasOwnProperty(p)) {
  10788. obj[p] = source[p];
  10789. }
  10790. }
  10791. }
  10792. return obj;
  10793. };
  10794. // reduce buffer size, avoiding mem copy
  10795. exports.shrinkBuf = function (buf, size) {
  10796. if (buf.length === size) { return buf; }
  10797. if (buf.subarray) { return buf.subarray(0, size); }
  10798. buf.length = size;
  10799. return buf;
  10800. };
  10801. var fnTyped = {
  10802. arraySet: function (dest, src, src_offs, len, dest_offs) {
  10803. if (src.subarray && dest.subarray) {
  10804. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  10805. return;
  10806. }
  10807. // Fallback to ordinary array
  10808. for (var i=0; i<len; i++) {
  10809. dest[dest_offs + i] = src[src_offs + i];
  10810. }
  10811. },
  10812. // Join array of chunks to single array.
  10813. flattenChunks: function(chunks) {
  10814. var i, l, len, pos, chunk, result;
  10815. // calculate data length
  10816. len = 0;
  10817. for (i=0, l=chunks.length; i<l; i++) {
  10818. len += chunks[i].length;
  10819. }
  10820. // join chunks
  10821. result = new Uint8Array(len);
  10822. pos = 0;
  10823. for (i=0, l=chunks.length; i<l; i++) {
  10824. chunk = chunks[i];
  10825. result.set(chunk, pos);
  10826. pos += chunk.length;
  10827. }
  10828. return result;
  10829. }
  10830. };
  10831. var fnUntyped = {
  10832. arraySet: function (dest, src, src_offs, len, dest_offs) {
  10833. for (var i=0; i<len; i++) {
  10834. dest[dest_offs + i] = src[src_offs + i];
  10835. }
  10836. },
  10837. // Join array of chunks to single array.
  10838. flattenChunks: function(chunks) {
  10839. return [].concat.apply([], chunks);
  10840. }
  10841. };
  10842. // Enable/Disable typed arrays use, for testing
  10843. //
  10844. exports.setTyped = function (on) {
  10845. if (on) {
  10846. exports.Buf8 = Uint8Array;
  10847. exports.Buf16 = Uint16Array;
  10848. exports.Buf32 = Int32Array;
  10849. exports.assign(exports, fnTyped);
  10850. } else {
  10851. exports.Buf8 = Array;
  10852. exports.Buf16 = Array;
  10853. exports.Buf32 = Array;
  10854. exports.assign(exports, fnUntyped);
  10855. }
  10856. };
  10857. exports.setTyped(TYPED_OK);
  10858. },{}],40:[function(require,module,exports){
  10859. // String encode/decode helpers
  10860. 'use strict';
  10861. var utils = require('./common');
  10862. // Quick check if we can use fast array to bin string conversion
  10863. //
  10864. // - apply(Array) can fail on Android 2.2
  10865. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  10866. //
  10867. var STR_APPLY_OK = true;
  10868. var STR_APPLY_UIA_OK = true;
  10869. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  10870. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  10871. // Table with utf8 lengths (calculated by first byte of sequence)
  10872. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  10873. // because max possible codepoint is 0x10ffff
  10874. var _utf8len = new utils.Buf8(256);
  10875. for (var q=0; q<256; q++) {
  10876. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  10877. }
  10878. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  10879. // convert string to array (typed, when possible)
  10880. exports.string2buf = function (str) {
  10881. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  10882. // count binary size
  10883. for (m_pos = 0; m_pos < str_len; m_pos++) {
  10884. c = str.charCodeAt(m_pos);
  10885. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  10886. c2 = str.charCodeAt(m_pos+1);
  10887. if ((c2 & 0xfc00) === 0xdc00) {
  10888. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  10889. m_pos++;
  10890. }
  10891. }
  10892. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  10893. }
  10894. // allocate buffer
  10895. buf = new utils.Buf8(buf_len);
  10896. // convert
  10897. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  10898. c = str.charCodeAt(m_pos);
  10899. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  10900. c2 = str.charCodeAt(m_pos+1);
  10901. if ((c2 & 0xfc00) === 0xdc00) {
  10902. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  10903. m_pos++;
  10904. }
  10905. }
  10906. if (c < 0x80) {
  10907. /* one byte */
  10908. buf[i++] = c;
  10909. } else if (c < 0x800) {
  10910. /* two bytes */
  10911. buf[i++] = 0xC0 | (c >>> 6);
  10912. buf[i++] = 0x80 | (c & 0x3f);
  10913. } else if (c < 0x10000) {
  10914. /* three bytes */
  10915. buf[i++] = 0xE0 | (c >>> 12);
  10916. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  10917. buf[i++] = 0x80 | (c & 0x3f);
  10918. } else {
  10919. /* four bytes */
  10920. buf[i++] = 0xf0 | (c >>> 18);
  10921. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  10922. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  10923. buf[i++] = 0x80 | (c & 0x3f);
  10924. }
  10925. }
  10926. return buf;
  10927. };
  10928. // Helper (used in 2 places)
  10929. function buf2binstring(buf, len) {
  10930. // use fallback for big arrays to avoid stack overflow
  10931. if (len < 65537) {
  10932. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  10933. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  10934. }
  10935. }
  10936. var result = '';
  10937. for (var i=0; i < len; i++) {
  10938. result += String.fromCharCode(buf[i]);
  10939. }
  10940. return result;
  10941. }
  10942. // Convert byte array to binary string
  10943. exports.buf2binstring = function(buf) {
  10944. return buf2binstring(buf, buf.length);
  10945. };
  10946. // Convert binary string (typed, when possible)
  10947. exports.binstring2buf = function(str) {
  10948. var buf = new utils.Buf8(str.length);
  10949. for (var i=0, len=buf.length; i < len; i++) {
  10950. buf[i] = str.charCodeAt(i);
  10951. }
  10952. return buf;
  10953. };
  10954. // convert array to string
  10955. exports.buf2string = function (buf, max) {
  10956. var i, out, c, c_len;
  10957. var len = max || buf.length;
  10958. // Reserve max possible length (2 words per char)
  10959. // NB: by unknown reasons, Array is significantly faster for
  10960. // String.fromCharCode.apply than Uint16Array.
  10961. var utf16buf = new Array(len*2);
  10962. for (out=0, i=0; i<len;) {
  10963. c = buf[i++];
  10964. // quick process ascii
  10965. if (c < 0x80) { utf16buf[out++] = c; continue; }
  10966. c_len = _utf8len[c];
  10967. // skip 5 & 6 byte codes
  10968. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  10969. // apply mask on first byte
  10970. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  10971. // join the rest
  10972. while (c_len > 1 && i < len) {
  10973. c = (c << 6) | (buf[i++] & 0x3f);
  10974. c_len--;
  10975. }
  10976. // terminated by end of string?
  10977. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  10978. if (c < 0x10000) {
  10979. utf16buf[out++] = c;
  10980. } else {
  10981. c -= 0x10000;
  10982. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  10983. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  10984. }
  10985. }
  10986. return buf2binstring(utf16buf, out);
  10987. };
  10988. // Calculate max possible position in utf8 buffer,
  10989. // that will not break sequence. If that's not possible
  10990. // - (very small limits) return max size as is.
  10991. //
  10992. // buf[] - utf8 bytes array
  10993. // max - length limit (mandatory);
  10994. exports.utf8border = function(buf, max) {
  10995. var pos;
  10996. max = max || buf.length;
  10997. if (max > buf.length) { max = buf.length; }
  10998. // go back from last position, until start of sequence found
  10999. pos = max-1;
  11000. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  11001. // Fuckup - very small and broken sequence,
  11002. // return max, because we should return something anyway.
  11003. if (pos < 0) { return max; }
  11004. // If we came to start of buffer - that means vuffer is too small,
  11005. // return max too.
  11006. if (pos === 0) { return max; }
  11007. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  11008. };
  11009. },{"./common":39}],41:[function(require,module,exports){
  11010. 'use strict';
  11011. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  11012. // It doesn't worth to make additional optimizationa as in original.
  11013. // Small size is preferable.
  11014. function adler32(adler, buf, len, pos) {
  11015. var s1 = (adler & 0xffff) |0,
  11016. s2 = ((adler >>> 16) & 0xffff) |0,
  11017. n = 0;
  11018. while (len !== 0) {
  11019. // Set limit ~ twice less than 5552, to keep
  11020. // s2 in 31-bits, because we force signed ints.
  11021. // in other case %= will fail.
  11022. n = len > 2000 ? 2000 : len;
  11023. len -= n;
  11024. do {
  11025. s1 = (s1 + buf[pos++]) |0;
  11026. s2 = (s2 + s1) |0;
  11027. } while (--n);
  11028. s1 %= 65521;
  11029. s2 %= 65521;
  11030. }
  11031. return (s1 | (s2 << 16)) |0;
  11032. }
  11033. module.exports = adler32;
  11034. },{}],42:[function(require,module,exports){
  11035. module.exports = {
  11036. /* Allowed flush values; see deflate() and inflate() below for details */
  11037. Z_NO_FLUSH: 0,
  11038. Z_PARTIAL_FLUSH: 1,
  11039. Z_SYNC_FLUSH: 2,
  11040. Z_FULL_FLUSH: 3,
  11041. Z_FINISH: 4,
  11042. Z_BLOCK: 5,
  11043. Z_TREES: 6,
  11044. /* Return codes for the compression/decompression functions. Negative values
  11045. * are errors, positive values are used for special but normal events.
  11046. */
  11047. Z_OK: 0,
  11048. Z_STREAM_END: 1,
  11049. Z_NEED_DICT: 2,
  11050. Z_ERRNO: -1,
  11051. Z_STREAM_ERROR: -2,
  11052. Z_DATA_ERROR: -3,
  11053. //Z_MEM_ERROR: -4,
  11054. Z_BUF_ERROR: -5,
  11055. //Z_VERSION_ERROR: -6,
  11056. /* compression levels */
  11057. Z_NO_COMPRESSION: 0,
  11058. Z_BEST_SPEED: 1,
  11059. Z_BEST_COMPRESSION: 9,
  11060. Z_DEFAULT_COMPRESSION: -1,
  11061. Z_FILTERED: 1,
  11062. Z_HUFFMAN_ONLY: 2,
  11063. Z_RLE: 3,
  11064. Z_FIXED: 4,
  11065. Z_DEFAULT_STRATEGY: 0,
  11066. /* Possible values of the data_type field (though see inflate()) */
  11067. Z_BINARY: 0,
  11068. Z_TEXT: 1,
  11069. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  11070. Z_UNKNOWN: 2,
  11071. /* The deflate compression method */
  11072. Z_DEFLATED: 8
  11073. //Z_NULL: null // Use -1 or null inline, depending on var type
  11074. };
  11075. },{}],43:[function(require,module,exports){
  11076. 'use strict';
  11077. // Note: we can't get significant speed boost here.
  11078. // So write code to minimize size - no pregenerated tables
  11079. // and array tools dependencies.
  11080. // Use ordinary array, since untyped makes no boost here
  11081. function makeTable() {
  11082. var c, table = [];
  11083. for (var n =0; n < 256; n++) {
  11084. c = n;
  11085. for (var k =0; k < 8; k++) {
  11086. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  11087. }
  11088. table[n] = c;
  11089. }
  11090. return table;
  11091. }
  11092. // Create table on load. Just 255 signed longs. Not a problem.
  11093. var crcTable = makeTable();
  11094. function crc32(crc, buf, len, pos) {
  11095. var t = crcTable,
  11096. end = pos + len;
  11097. crc = crc ^ (-1);
  11098. for (var i = pos; i < end; i++) {
  11099. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  11100. }
  11101. return (crc ^ (-1)); // >>> 0;
  11102. }
  11103. module.exports = crc32;
  11104. },{}],44:[function(require,module,exports){
  11105. 'use strict';
  11106. var utils = require('../utils/common');
  11107. var trees = require('./trees');
  11108. var adler32 = require('./adler32');
  11109. var crc32 = require('./crc32');
  11110. var msg = require('./messages');
  11111. /* Public constants ==========================================================*/
  11112. /* ===========================================================================*/
  11113. /* Allowed flush values; see deflate() and inflate() below for details */
  11114. var Z_NO_FLUSH = 0;
  11115. var Z_PARTIAL_FLUSH = 1;
  11116. //var Z_SYNC_FLUSH = 2;
  11117. var Z_FULL_FLUSH = 3;
  11118. var Z_FINISH = 4;
  11119. var Z_BLOCK = 5;
  11120. //var Z_TREES = 6;
  11121. /* Return codes for the compression/decompression functions. Negative values
  11122. * are errors, positive values are used for special but normal events.
  11123. */
  11124. var Z_OK = 0;
  11125. var Z_STREAM_END = 1;
  11126. //var Z_NEED_DICT = 2;
  11127. //var Z_ERRNO = -1;
  11128. var Z_STREAM_ERROR = -2;
  11129. var Z_DATA_ERROR = -3;
  11130. //var Z_MEM_ERROR = -4;
  11131. var Z_BUF_ERROR = -5;
  11132. //var Z_VERSION_ERROR = -6;
  11133. /* compression levels */
  11134. //var Z_NO_COMPRESSION = 0;
  11135. //var Z_BEST_SPEED = 1;
  11136. //var Z_BEST_COMPRESSION = 9;
  11137. var Z_DEFAULT_COMPRESSION = -1;
  11138. var Z_FILTERED = 1;
  11139. var Z_HUFFMAN_ONLY = 2;
  11140. var Z_RLE = 3;
  11141. var Z_FIXED = 4;
  11142. var Z_DEFAULT_STRATEGY = 0;
  11143. /* Possible values of the data_type field (though see inflate()) */
  11144. //var Z_BINARY = 0;
  11145. //var Z_TEXT = 1;
  11146. //var Z_ASCII = 1; // = Z_TEXT
  11147. var Z_UNKNOWN = 2;
  11148. /* The deflate compression method */
  11149. var Z_DEFLATED = 8;
  11150. /*============================================================================*/
  11151. var MAX_MEM_LEVEL = 9;
  11152. /* Maximum value for memLevel in deflateInit2 */
  11153. var MAX_WBITS = 15;
  11154. /* 32K LZ77 window */
  11155. var DEF_MEM_LEVEL = 8;
  11156. var LENGTH_CODES = 29;
  11157. /* number of length codes, not counting the special END_BLOCK code */
  11158. var LITERALS = 256;
  11159. /* number of literal bytes 0..255 */
  11160. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  11161. /* number of Literal or Length codes, including the END_BLOCK code */
  11162. var D_CODES = 30;
  11163. /* number of distance codes */
  11164. var BL_CODES = 19;
  11165. /* number of codes used to transfer the bit lengths */
  11166. var HEAP_SIZE = 2*L_CODES + 1;
  11167. /* maximum heap size */
  11168. var MAX_BITS = 15;
  11169. /* All codes must not exceed MAX_BITS bits */
  11170. var MIN_MATCH = 3;
  11171. var MAX_MATCH = 258;
  11172. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  11173. var PRESET_DICT = 0x20;
  11174. var INIT_STATE = 42;
  11175. var EXTRA_STATE = 69;
  11176. var NAME_STATE = 73;
  11177. var COMMENT_STATE = 91;
  11178. var HCRC_STATE = 103;
  11179. var BUSY_STATE = 113;
  11180. var FINISH_STATE = 666;
  11181. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  11182. var BS_BLOCK_DONE = 2; /* block flush performed */
  11183. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  11184. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  11185. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  11186. function err(strm, errorCode) {
  11187. strm.msg = msg[errorCode];
  11188. return errorCode;
  11189. }
  11190. function rank(f) {
  11191. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  11192. }
  11193. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  11194. /* =========================================================================
  11195. * Flush as much pending output as possible. All deflate() output goes
  11196. * through this function so some applications may wish to modify it
  11197. * to avoid allocating a large strm->output buffer and copying into it.
  11198. * (See also read_buf()).
  11199. */
  11200. function flush_pending(strm) {
  11201. var s = strm.state;
  11202. //_tr_flush_bits(s);
  11203. var len = s.pending;
  11204. if (len > strm.avail_out) {
  11205. len = strm.avail_out;
  11206. }
  11207. if (len === 0) { return; }
  11208. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  11209. strm.next_out += len;
  11210. s.pending_out += len;
  11211. strm.total_out += len;
  11212. strm.avail_out -= len;
  11213. s.pending -= len;
  11214. if (s.pending === 0) {
  11215. s.pending_out = 0;
  11216. }
  11217. }
  11218. function flush_block_only (s, last) {
  11219. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  11220. s.block_start = s.strstart;
  11221. flush_pending(s.strm);
  11222. }
  11223. function put_byte(s, b) {
  11224. s.pending_buf[s.pending++] = b;
  11225. }
  11226. /* =========================================================================
  11227. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  11228. * IN assertion: the stream state is correct and there is enough room in
  11229. * pending_buf.
  11230. */
  11231. function putShortMSB(s, b) {
  11232. // put_byte(s, (Byte)(b >> 8));
  11233. // put_byte(s, (Byte)(b & 0xff));
  11234. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  11235. s.pending_buf[s.pending++] = b & 0xff;
  11236. }
  11237. /* ===========================================================================
  11238. * Read a new buffer from the current input stream, update the adler32
  11239. * and total number of bytes read. All deflate() input goes through
  11240. * this function so some applications may wish to modify it to avoid
  11241. * allocating a large strm->input buffer and copying from it.
  11242. * (See also flush_pending()).
  11243. */
  11244. function read_buf(strm, buf, start, size) {
  11245. var len = strm.avail_in;
  11246. if (len > size) { len = size; }
  11247. if (len === 0) { return 0; }
  11248. strm.avail_in -= len;
  11249. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  11250. if (strm.state.wrap === 1) {
  11251. strm.adler = adler32(strm.adler, buf, len, start);
  11252. }
  11253. else if (strm.state.wrap === 2) {
  11254. strm.adler = crc32(strm.adler, buf, len, start);
  11255. }
  11256. strm.next_in += len;
  11257. strm.total_in += len;
  11258. return len;
  11259. }
  11260. /* ===========================================================================
  11261. * Set match_start to the longest match starting at the given string and
  11262. * return its length. Matches shorter or equal to prev_length are discarded,
  11263. * in which case the result is equal to prev_length and match_start is
  11264. * garbage.
  11265. * IN assertions: cur_match is the head of the hash chain for the current
  11266. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  11267. * OUT assertion: the match length is not greater than s->lookahead.
  11268. */
  11269. function longest_match(s, cur_match) {
  11270. var chain_length = s.max_chain_length; /* max hash chain length */
  11271. var scan = s.strstart; /* current string */
  11272. var match; /* matched string */
  11273. var len; /* length of current match */
  11274. var best_len = s.prev_length; /* best match length so far */
  11275. var nice_match = s.nice_match; /* stop if match long enough */
  11276. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  11277. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  11278. var _win = s.window; // shortcut
  11279. var wmask = s.w_mask;
  11280. var prev = s.prev;
  11281. /* Stop when cur_match becomes <= limit. To simplify the code,
  11282. * we prevent matches with the string of window index 0.
  11283. */
  11284. var strend = s.strstart + MAX_MATCH;
  11285. var scan_end1 = _win[scan + best_len - 1];
  11286. var scan_end = _win[scan + best_len];
  11287. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  11288. * It is easy to get rid of this optimization if necessary.
  11289. */
  11290. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  11291. /* Do not waste too much time if we already have a good match: */
  11292. if (s.prev_length >= s.good_match) {
  11293. chain_length >>= 2;
  11294. }
  11295. /* Do not look for matches beyond the end of the input. This is necessary
  11296. * to make deflate deterministic.
  11297. */
  11298. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  11299. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  11300. do {
  11301. // Assert(cur_match < s->strstart, "no future");
  11302. match = cur_match;
  11303. /* Skip to next match if the match length cannot increase
  11304. * or if the match length is less than 2. Note that the checks below
  11305. * for insufficient lookahead only occur occasionally for performance
  11306. * reasons. Therefore uninitialized memory will be accessed, and
  11307. * conditional jumps will be made that depend on those values.
  11308. * However the length of the match is limited to the lookahead, so
  11309. * the output of deflate is not affected by the uninitialized values.
  11310. */
  11311. if (_win[match + best_len] !== scan_end ||
  11312. _win[match + best_len - 1] !== scan_end1 ||
  11313. _win[match] !== _win[scan] ||
  11314. _win[++match] !== _win[scan + 1]) {
  11315. continue;
  11316. }
  11317. /* The check at best_len-1 can be removed because it will be made
  11318. * again later. (This heuristic is not always a win.)
  11319. * It is not necessary to compare scan[2] and match[2] since they
  11320. * are always equal when the other bytes match, given that
  11321. * the hash keys are equal and that HASH_BITS >= 8.
  11322. */
  11323. scan += 2;
  11324. match++;
  11325. // Assert(*scan == *match, "match[2]?");
  11326. /* We check for insufficient lookahead only every 8th comparison;
  11327. * the 256th check will be made at strstart+258.
  11328. */
  11329. do {
  11330. /*jshint noempty:false*/
  11331. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11332. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11333. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11334. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11335. scan < strend);
  11336. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  11337. len = MAX_MATCH - (strend - scan);
  11338. scan = strend - MAX_MATCH;
  11339. if (len > best_len) {
  11340. s.match_start = cur_match;
  11341. best_len = len;
  11342. if (len >= nice_match) {
  11343. break;
  11344. }
  11345. scan_end1 = _win[scan + best_len - 1];
  11346. scan_end = _win[scan + best_len];
  11347. }
  11348. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  11349. if (best_len <= s.lookahead) {
  11350. return best_len;
  11351. }
  11352. return s.lookahead;
  11353. }
  11354. /* ===========================================================================
  11355. * Fill the window when the lookahead becomes insufficient.
  11356. * Updates strstart and lookahead.
  11357. *
  11358. * IN assertion: lookahead < MIN_LOOKAHEAD
  11359. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  11360. * At least one byte has been read, or avail_in == 0; reads are
  11361. * performed for at least two bytes (required for the zip translate_eol
  11362. * option -- not supported here).
  11363. */
  11364. function fill_window(s) {
  11365. var _w_size = s.w_size;
  11366. var p, n, m, more, str;
  11367. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  11368. do {
  11369. more = s.window_size - s.lookahead - s.strstart;
  11370. // JS ints have 32 bit, block below not needed
  11371. /* Deal with !@#$% 64K limit: */
  11372. //if (sizeof(int) <= 2) {
  11373. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  11374. // more = wsize;
  11375. //
  11376. // } else if (more == (unsigned)(-1)) {
  11377. // /* Very unlikely, but possible on 16 bit machine if
  11378. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  11379. // */
  11380. // more--;
  11381. // }
  11382. //}
  11383. /* If the window is almost full and there is insufficient lookahead,
  11384. * move the upper half to the lower one to make room in the upper half.
  11385. */
  11386. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  11387. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  11388. s.match_start -= _w_size;
  11389. s.strstart -= _w_size;
  11390. /* we now have strstart >= MAX_DIST */
  11391. s.block_start -= _w_size;
  11392. /* Slide the hash table (could be avoided with 32 bit values
  11393. at the expense of memory usage). We slide even when level == 0
  11394. to keep the hash table consistent if we switch back to level > 0
  11395. later. (Using level 0 permanently is not an optimal usage of
  11396. zlib, so we don't care about this pathological case.)
  11397. */
  11398. n = s.hash_size;
  11399. p = n;
  11400. do {
  11401. m = s.head[--p];
  11402. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  11403. } while (--n);
  11404. n = _w_size;
  11405. p = n;
  11406. do {
  11407. m = s.prev[--p];
  11408. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  11409. /* If n is not on any hash chain, prev[n] is garbage but
  11410. * its value will never be used.
  11411. */
  11412. } while (--n);
  11413. more += _w_size;
  11414. }
  11415. if (s.strm.avail_in === 0) {
  11416. break;
  11417. }
  11418. /* If there was no sliding:
  11419. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  11420. * more == window_size - lookahead - strstart
  11421. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  11422. * => more >= window_size - 2*WSIZE + 2
  11423. * In the BIG_MEM or MMAP case (not yet supported),
  11424. * window_size == input_size + MIN_LOOKAHEAD &&
  11425. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  11426. * Otherwise, window_size == 2*WSIZE so more >= 2.
  11427. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  11428. */
  11429. //Assert(more >= 2, "more < 2");
  11430. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  11431. s.lookahead += n;
  11432. /* Initialize the hash value now that we have some input: */
  11433. if (s.lookahead + s.insert >= MIN_MATCH) {
  11434. str = s.strstart - s.insert;
  11435. s.ins_h = s.window[str];
  11436. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  11437. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  11438. //#if MIN_MATCH != 3
  11439. // Call update_hash() MIN_MATCH-3 more times
  11440. //#endif
  11441. while (s.insert) {
  11442. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  11443. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  11444. s.prev[str & s.w_mask] = s.head[s.ins_h];
  11445. s.head[s.ins_h] = str;
  11446. str++;
  11447. s.insert--;
  11448. if (s.lookahead + s.insert < MIN_MATCH) {
  11449. break;
  11450. }
  11451. }
  11452. }
  11453. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  11454. * but this is not important since only literal bytes will be emitted.
  11455. */
  11456. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  11457. /* If the WIN_INIT bytes after the end of the current data have never been
  11458. * written, then zero those bytes in order to avoid memory check reports of
  11459. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  11460. * the longest match routines. Update the high water mark for the next
  11461. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  11462. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  11463. */
  11464. // if (s.high_water < s.window_size) {
  11465. // var curr = s.strstart + s.lookahead;
  11466. // var init = 0;
  11467. //
  11468. // if (s.high_water < curr) {
  11469. // /* Previous high water mark below current data -- zero WIN_INIT
  11470. // * bytes or up to end of window, whichever is less.
  11471. // */
  11472. // init = s.window_size - curr;
  11473. // if (init > WIN_INIT)
  11474. // init = WIN_INIT;
  11475. // zmemzero(s->window + curr, (unsigned)init);
  11476. // s->high_water = curr + init;
  11477. // }
  11478. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  11479. // /* High water mark at or above current data, but below current data
  11480. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  11481. // * to end of window, whichever is less.
  11482. // */
  11483. // init = (ulg)curr + WIN_INIT - s->high_water;
  11484. // if (init > s->window_size - s->high_water)
  11485. // init = s->window_size - s->high_water;
  11486. // zmemzero(s->window + s->high_water, (unsigned)init);
  11487. // s->high_water += init;
  11488. // }
  11489. // }
  11490. //
  11491. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  11492. // "not enough room for search");
  11493. }
  11494. /* ===========================================================================
  11495. * Copy without compression as much as possible from the input stream, return
  11496. * the current block state.
  11497. * This function does not insert new strings in the dictionary since
  11498. * uncompressible data is probably not useful. This function is used
  11499. * only for the level=0 compression option.
  11500. * NOTE: this function should be optimized to avoid extra copying from
  11501. * window to pending_buf.
  11502. */
  11503. function deflate_stored(s, flush) {
  11504. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  11505. * to pending_buf_size, and each stored block has a 5 byte header:
  11506. */
  11507. var max_block_size = 0xffff;
  11508. if (max_block_size > s.pending_buf_size - 5) {
  11509. max_block_size = s.pending_buf_size - 5;
  11510. }
  11511. /* Copy as much as possible from input to output: */
  11512. for (;;) {
  11513. /* Fill the window as much as possible: */
  11514. if (s.lookahead <= 1) {
  11515. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  11516. // s->block_start >= (long)s->w_size, "slide too late");
  11517. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  11518. // s.block_start >= s.w_size)) {
  11519. // throw new Error("slide too late");
  11520. // }
  11521. fill_window(s);
  11522. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  11523. return BS_NEED_MORE;
  11524. }
  11525. if (s.lookahead === 0) {
  11526. break;
  11527. }
  11528. /* flush the current block */
  11529. }
  11530. //Assert(s->block_start >= 0L, "block gone");
  11531. // if (s.block_start < 0) throw new Error("block gone");
  11532. s.strstart += s.lookahead;
  11533. s.lookahead = 0;
  11534. /* Emit a stored block if pending_buf will be full: */
  11535. var max_start = s.block_start + max_block_size;
  11536. if (s.strstart === 0 || s.strstart >= max_start) {
  11537. /* strstart == 0 is possible when wraparound on 16-bit machine */
  11538. s.lookahead = s.strstart - max_start;
  11539. s.strstart = max_start;
  11540. /*** FLUSH_BLOCK(s, 0); ***/
  11541. flush_block_only(s, false);
  11542. if (s.strm.avail_out === 0) {
  11543. return BS_NEED_MORE;
  11544. }
  11545. /***/
  11546. }
  11547. /* Flush if we may have to slide, otherwise block_start may become
  11548. * negative and the data will be gone:
  11549. */
  11550. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  11551. /*** FLUSH_BLOCK(s, 0); ***/
  11552. flush_block_only(s, false);
  11553. if (s.strm.avail_out === 0) {
  11554. return BS_NEED_MORE;
  11555. }
  11556. /***/
  11557. }
  11558. }
  11559. s.insert = 0;
  11560. if (flush === Z_FINISH) {
  11561. /*** FLUSH_BLOCK(s, 1); ***/
  11562. flush_block_only(s, true);
  11563. if (s.strm.avail_out === 0) {
  11564. return BS_FINISH_STARTED;
  11565. }
  11566. /***/
  11567. return BS_FINISH_DONE;
  11568. }
  11569. if (s.strstart > s.block_start) {
  11570. /*** FLUSH_BLOCK(s, 0); ***/
  11571. flush_block_only(s, false);
  11572. if (s.strm.avail_out === 0) {
  11573. return BS_NEED_MORE;
  11574. }
  11575. /***/
  11576. }
  11577. return BS_NEED_MORE;
  11578. }
  11579. /* ===========================================================================
  11580. * Compress as much as possible from the input stream, return the current
  11581. * block state.
  11582. * This function does not perform lazy evaluation of matches and inserts
  11583. * new strings in the dictionary only for unmatched strings or for short
  11584. * matches. It is used only for the fast compression options.
  11585. */
  11586. function deflate_fast(s, flush) {
  11587. var hash_head; /* head of the hash chain */
  11588. var bflush; /* set if current block must be flushed */
  11589. for (;;) {
  11590. /* Make sure that we always have enough lookahead, except
  11591. * at the end of the input file. We need MAX_MATCH bytes
  11592. * for the next match, plus MIN_MATCH bytes to insert the
  11593. * string following the next match.
  11594. */
  11595. if (s.lookahead < MIN_LOOKAHEAD) {
  11596. fill_window(s);
  11597. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11598. return BS_NEED_MORE;
  11599. }
  11600. if (s.lookahead === 0) {
  11601. break; /* flush the current block */
  11602. }
  11603. }
  11604. /* Insert the string window[strstart .. strstart+2] in the
  11605. * dictionary, and set hash_head to the head of the hash chain:
  11606. */
  11607. hash_head = 0/*NIL*/;
  11608. if (s.lookahead >= MIN_MATCH) {
  11609. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11610. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11611. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11612. s.head[s.ins_h] = s.strstart;
  11613. /***/
  11614. }
  11615. /* Find the longest match, discarding those <= prev_length.
  11616. * At this point we have always match_length < MIN_MATCH
  11617. */
  11618. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  11619. /* To simplify the code, we prevent matches with the string
  11620. * of window index 0 (in particular we have to avoid a match
  11621. * of the string with itself at the start of the input file).
  11622. */
  11623. s.match_length = longest_match(s, hash_head);
  11624. /* longest_match() sets match_start */
  11625. }
  11626. if (s.match_length >= MIN_MATCH) {
  11627. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  11628. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  11629. s.match_length - MIN_MATCH, bflush); ***/
  11630. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  11631. s.lookahead -= s.match_length;
  11632. /* Insert new strings in the hash table only if the match length
  11633. * is not too large. This saves time but degrades compression.
  11634. */
  11635. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  11636. s.match_length--; /* string at strstart already in table */
  11637. do {
  11638. s.strstart++;
  11639. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11640. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11641. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11642. s.head[s.ins_h] = s.strstart;
  11643. /***/
  11644. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  11645. * always MIN_MATCH bytes ahead.
  11646. */
  11647. } while (--s.match_length !== 0);
  11648. s.strstart++;
  11649. } else
  11650. {
  11651. s.strstart += s.match_length;
  11652. s.match_length = 0;
  11653. s.ins_h = s.window[s.strstart];
  11654. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  11655. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  11656. //#if MIN_MATCH != 3
  11657. // Call UPDATE_HASH() MIN_MATCH-3 more times
  11658. //#endif
  11659. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  11660. * matter since it will be recomputed at next deflate call.
  11661. */
  11662. }
  11663. } else {
  11664. /* No match, output a literal byte */
  11665. //Tracevv((stderr,"%c", s.window[s.strstart]));
  11666. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11667. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11668. s.lookahead--;
  11669. s.strstart++;
  11670. }
  11671. if (bflush) {
  11672. /*** FLUSH_BLOCK(s, 0); ***/
  11673. flush_block_only(s, false);
  11674. if (s.strm.avail_out === 0) {
  11675. return BS_NEED_MORE;
  11676. }
  11677. /***/
  11678. }
  11679. }
  11680. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  11681. if (flush === Z_FINISH) {
  11682. /*** FLUSH_BLOCK(s, 1); ***/
  11683. flush_block_only(s, true);
  11684. if (s.strm.avail_out === 0) {
  11685. return BS_FINISH_STARTED;
  11686. }
  11687. /***/
  11688. return BS_FINISH_DONE;
  11689. }
  11690. if (s.last_lit) {
  11691. /*** FLUSH_BLOCK(s, 0); ***/
  11692. flush_block_only(s, false);
  11693. if (s.strm.avail_out === 0) {
  11694. return BS_NEED_MORE;
  11695. }
  11696. /***/
  11697. }
  11698. return BS_BLOCK_DONE;
  11699. }
  11700. /* ===========================================================================
  11701. * Same as above, but achieves better compression. We use a lazy
  11702. * evaluation for matches: a match is finally adopted only if there is
  11703. * no better match at the next window position.
  11704. */
  11705. function deflate_slow(s, flush) {
  11706. var hash_head; /* head of hash chain */
  11707. var bflush; /* set if current block must be flushed */
  11708. var max_insert;
  11709. /* Process the input block. */
  11710. for (;;) {
  11711. /* Make sure that we always have enough lookahead, except
  11712. * at the end of the input file. We need MAX_MATCH bytes
  11713. * for the next match, plus MIN_MATCH bytes to insert the
  11714. * string following the next match.
  11715. */
  11716. if (s.lookahead < MIN_LOOKAHEAD) {
  11717. fill_window(s);
  11718. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11719. return BS_NEED_MORE;
  11720. }
  11721. if (s.lookahead === 0) { break; } /* flush the current block */
  11722. }
  11723. /* Insert the string window[strstart .. strstart+2] in the
  11724. * dictionary, and set hash_head to the head of the hash chain:
  11725. */
  11726. hash_head = 0/*NIL*/;
  11727. if (s.lookahead >= MIN_MATCH) {
  11728. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11729. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11730. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11731. s.head[s.ins_h] = s.strstart;
  11732. /***/
  11733. }
  11734. /* Find the longest match, discarding those <= prev_length.
  11735. */
  11736. s.prev_length = s.match_length;
  11737. s.prev_match = s.match_start;
  11738. s.match_length = MIN_MATCH-1;
  11739. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  11740. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  11741. /* To simplify the code, we prevent matches with the string
  11742. * of window index 0 (in particular we have to avoid a match
  11743. * of the string with itself at the start of the input file).
  11744. */
  11745. s.match_length = longest_match(s, hash_head);
  11746. /* longest_match() sets match_start */
  11747. if (s.match_length <= 5 &&
  11748. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  11749. /* If prev_match is also MIN_MATCH, match_start is garbage
  11750. * but we will ignore the current match anyway.
  11751. */
  11752. s.match_length = MIN_MATCH-1;
  11753. }
  11754. }
  11755. /* If there was a match at the previous step and the current
  11756. * match is not better, output the previous match:
  11757. */
  11758. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  11759. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  11760. /* Do not insert strings in hash table beyond this. */
  11761. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  11762. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  11763. s.prev_length - MIN_MATCH, bflush);***/
  11764. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  11765. /* Insert in hash table all strings up to the end of the match.
  11766. * strstart-1 and strstart are already inserted. If there is not
  11767. * enough lookahead, the last two strings are not inserted in
  11768. * the hash table.
  11769. */
  11770. s.lookahead -= s.prev_length-1;
  11771. s.prev_length -= 2;
  11772. do {
  11773. if (++s.strstart <= max_insert) {
  11774. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11775. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11776. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11777. s.head[s.ins_h] = s.strstart;
  11778. /***/
  11779. }
  11780. } while (--s.prev_length !== 0);
  11781. s.match_available = 0;
  11782. s.match_length = MIN_MATCH-1;
  11783. s.strstart++;
  11784. if (bflush) {
  11785. /*** FLUSH_BLOCK(s, 0); ***/
  11786. flush_block_only(s, false);
  11787. if (s.strm.avail_out === 0) {
  11788. return BS_NEED_MORE;
  11789. }
  11790. /***/
  11791. }
  11792. } else if (s.match_available) {
  11793. /* If there was no match at the previous position, output a
  11794. * single literal. If there was a match but the current match
  11795. * is longer, truncate the previous match to a single literal.
  11796. */
  11797. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  11798. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  11799. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  11800. if (bflush) {
  11801. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  11802. flush_block_only(s, false);
  11803. /***/
  11804. }
  11805. s.strstart++;
  11806. s.lookahead--;
  11807. if (s.strm.avail_out === 0) {
  11808. return BS_NEED_MORE;
  11809. }
  11810. } else {
  11811. /* There is no previous match to compare with, wait for
  11812. * the next step to decide.
  11813. */
  11814. s.match_available = 1;
  11815. s.strstart++;
  11816. s.lookahead--;
  11817. }
  11818. }
  11819. //Assert (flush != Z_NO_FLUSH, "no flush?");
  11820. if (s.match_available) {
  11821. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  11822. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  11823. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  11824. s.match_available = 0;
  11825. }
  11826. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  11827. if (flush === Z_FINISH) {
  11828. /*** FLUSH_BLOCK(s, 1); ***/
  11829. flush_block_only(s, true);
  11830. if (s.strm.avail_out === 0) {
  11831. return BS_FINISH_STARTED;
  11832. }
  11833. /***/
  11834. return BS_FINISH_DONE;
  11835. }
  11836. if (s.last_lit) {
  11837. /*** FLUSH_BLOCK(s, 0); ***/
  11838. flush_block_only(s, false);
  11839. if (s.strm.avail_out === 0) {
  11840. return BS_NEED_MORE;
  11841. }
  11842. /***/
  11843. }
  11844. return BS_BLOCK_DONE;
  11845. }
  11846. /* ===========================================================================
  11847. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  11848. * one. Do not maintain a hash table. (It will be regenerated if this run of
  11849. * deflate switches away from Z_RLE.)
  11850. */
  11851. function deflate_rle(s, flush) {
  11852. var bflush; /* set if current block must be flushed */
  11853. var prev; /* byte at distance one to match */
  11854. var scan, strend; /* scan goes up to strend for length of run */
  11855. var _win = s.window;
  11856. for (;;) {
  11857. /* Make sure that we always have enough lookahead, except
  11858. * at the end of the input file. We need MAX_MATCH bytes
  11859. * for the longest run, plus one for the unrolled loop.
  11860. */
  11861. if (s.lookahead <= MAX_MATCH) {
  11862. fill_window(s);
  11863. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  11864. return BS_NEED_MORE;
  11865. }
  11866. if (s.lookahead === 0) { break; } /* flush the current block */
  11867. }
  11868. /* See how many times the previous byte repeats */
  11869. s.match_length = 0;
  11870. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  11871. scan = s.strstart - 1;
  11872. prev = _win[scan];
  11873. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  11874. strend = s.strstart + MAX_MATCH;
  11875. do {
  11876. /*jshint noempty:false*/
  11877. } while (prev === _win[++scan] && prev === _win[++scan] &&
  11878. prev === _win[++scan] && prev === _win[++scan] &&
  11879. prev === _win[++scan] && prev === _win[++scan] &&
  11880. prev === _win[++scan] && prev === _win[++scan] &&
  11881. scan < strend);
  11882. s.match_length = MAX_MATCH - (strend - scan);
  11883. if (s.match_length > s.lookahead) {
  11884. s.match_length = s.lookahead;
  11885. }
  11886. }
  11887. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  11888. }
  11889. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  11890. if (s.match_length >= MIN_MATCH) {
  11891. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  11892. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  11893. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  11894. s.lookahead -= s.match_length;
  11895. s.strstart += s.match_length;
  11896. s.match_length = 0;
  11897. } else {
  11898. /* No match, output a literal byte */
  11899. //Tracevv((stderr,"%c", s->window[s->strstart]));
  11900. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11901. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11902. s.lookahead--;
  11903. s.strstart++;
  11904. }
  11905. if (bflush) {
  11906. /*** FLUSH_BLOCK(s, 0); ***/
  11907. flush_block_only(s, false);
  11908. if (s.strm.avail_out === 0) {
  11909. return BS_NEED_MORE;
  11910. }
  11911. /***/
  11912. }
  11913. }
  11914. s.insert = 0;
  11915. if (flush === Z_FINISH) {
  11916. /*** FLUSH_BLOCK(s, 1); ***/
  11917. flush_block_only(s, true);
  11918. if (s.strm.avail_out === 0) {
  11919. return BS_FINISH_STARTED;
  11920. }
  11921. /***/
  11922. return BS_FINISH_DONE;
  11923. }
  11924. if (s.last_lit) {
  11925. /*** FLUSH_BLOCK(s, 0); ***/
  11926. flush_block_only(s, false);
  11927. if (s.strm.avail_out === 0) {
  11928. return BS_NEED_MORE;
  11929. }
  11930. /***/
  11931. }
  11932. return BS_BLOCK_DONE;
  11933. }
  11934. /* ===========================================================================
  11935. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  11936. * (It will be regenerated if this run of deflate switches away from Huffman.)
  11937. */
  11938. function deflate_huff(s, flush) {
  11939. var bflush; /* set if current block must be flushed */
  11940. for (;;) {
  11941. /* Make sure that we have a literal to write. */
  11942. if (s.lookahead === 0) {
  11943. fill_window(s);
  11944. if (s.lookahead === 0) {
  11945. if (flush === Z_NO_FLUSH) {
  11946. return BS_NEED_MORE;
  11947. }
  11948. break; /* flush the current block */
  11949. }
  11950. }
  11951. /* Output a literal byte */
  11952. s.match_length = 0;
  11953. //Tracevv((stderr,"%c", s->window[s->strstart]));
  11954. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11955. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11956. s.lookahead--;
  11957. s.strstart++;
  11958. if (bflush) {
  11959. /*** FLUSH_BLOCK(s, 0); ***/
  11960. flush_block_only(s, false);
  11961. if (s.strm.avail_out === 0) {
  11962. return BS_NEED_MORE;
  11963. }
  11964. /***/
  11965. }
  11966. }
  11967. s.insert = 0;
  11968. if (flush === Z_FINISH) {
  11969. /*** FLUSH_BLOCK(s, 1); ***/
  11970. flush_block_only(s, true);
  11971. if (s.strm.avail_out === 0) {
  11972. return BS_FINISH_STARTED;
  11973. }
  11974. /***/
  11975. return BS_FINISH_DONE;
  11976. }
  11977. if (s.last_lit) {
  11978. /*** FLUSH_BLOCK(s, 0); ***/
  11979. flush_block_only(s, false);
  11980. if (s.strm.avail_out === 0) {
  11981. return BS_NEED_MORE;
  11982. }
  11983. /***/
  11984. }
  11985. return BS_BLOCK_DONE;
  11986. }
  11987. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  11988. * the desired pack level (0..9). The values given below have been tuned to
  11989. * exclude worst case performance for pathological files. Better values may be
  11990. * found for specific files.
  11991. */
  11992. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  11993. this.good_length = good_length;
  11994. this.max_lazy = max_lazy;
  11995. this.nice_length = nice_length;
  11996. this.max_chain = max_chain;
  11997. this.func = func;
  11998. };
  11999. var configuration_table;
  12000. configuration_table = [
  12001. /* good lazy nice chain */
  12002. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  12003. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  12004. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  12005. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  12006. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  12007. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  12008. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  12009. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  12010. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  12011. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  12012. ];
  12013. /* ===========================================================================
  12014. * Initialize the "longest match" routines for a new zlib stream
  12015. */
  12016. function lm_init(s) {
  12017. s.window_size = 2 * s.w_size;
  12018. /*** CLEAR_HASH(s); ***/
  12019. zero(s.head); // Fill with NIL (= 0);
  12020. /* Set the default configuration parameters:
  12021. */
  12022. s.max_lazy_match = configuration_table[s.level].max_lazy;
  12023. s.good_match = configuration_table[s.level].good_length;
  12024. s.nice_match = configuration_table[s.level].nice_length;
  12025. s.max_chain_length = configuration_table[s.level].max_chain;
  12026. s.strstart = 0;
  12027. s.block_start = 0;
  12028. s.lookahead = 0;
  12029. s.insert = 0;
  12030. s.match_length = s.prev_length = MIN_MATCH - 1;
  12031. s.match_available = 0;
  12032. s.ins_h = 0;
  12033. }
  12034. function DeflateState() {
  12035. this.strm = null; /* pointer back to this zlib stream */
  12036. this.status = 0; /* as the name implies */
  12037. this.pending_buf = null; /* output still pending */
  12038. this.pending_buf_size = 0; /* size of pending_buf */
  12039. this.pending_out = 0; /* next pending byte to output to the stream */
  12040. this.pending = 0; /* nb of bytes in the pending buffer */
  12041. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  12042. this.gzhead = null; /* gzip header information to write */
  12043. this.gzindex = 0; /* where in extra, name, or comment */
  12044. this.method = Z_DEFLATED; /* can only be DEFLATED */
  12045. this.last_flush = -1; /* value of flush param for previous deflate call */
  12046. this.w_size = 0; /* LZ77 window size (32K by default) */
  12047. this.w_bits = 0; /* log2(w_size) (8..16) */
  12048. this.w_mask = 0; /* w_size - 1 */
  12049. this.window = null;
  12050. /* Sliding window. Input bytes are read into the second half of the window,
  12051. * and move to the first half later to keep a dictionary of at least wSize
  12052. * bytes. With this organization, matches are limited to a distance of
  12053. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  12054. * performed with a length multiple of the block size.
  12055. */
  12056. this.window_size = 0;
  12057. /* Actual size of window: 2*wSize, except when the user input buffer
  12058. * is directly used as sliding window.
  12059. */
  12060. this.prev = null;
  12061. /* Link to older string with same hash index. To limit the size of this
  12062. * array to 64K, this link is maintained only for the last 32K strings.
  12063. * An index in this array is thus a window index modulo 32K.
  12064. */
  12065. this.head = null; /* Heads of the hash chains or NIL. */
  12066. this.ins_h = 0; /* hash index of string to be inserted */
  12067. this.hash_size = 0; /* number of elements in hash table */
  12068. this.hash_bits = 0; /* log2(hash_size) */
  12069. this.hash_mask = 0; /* hash_size-1 */
  12070. this.hash_shift = 0;
  12071. /* Number of bits by which ins_h must be shifted at each input
  12072. * step. It must be such that after MIN_MATCH steps, the oldest
  12073. * byte no longer takes part in the hash key, that is:
  12074. * hash_shift * MIN_MATCH >= hash_bits
  12075. */
  12076. this.block_start = 0;
  12077. /* Window position at the beginning of the current output block. Gets
  12078. * negative when the window is moved backwards.
  12079. */
  12080. this.match_length = 0; /* length of best match */
  12081. this.prev_match = 0; /* previous match */
  12082. this.match_available = 0; /* set if previous match exists */
  12083. this.strstart = 0; /* start of string to insert */
  12084. this.match_start = 0; /* start of matching string */
  12085. this.lookahead = 0; /* number of valid bytes ahead in window */
  12086. this.prev_length = 0;
  12087. /* Length of the best match at previous step. Matches not greater than this
  12088. * are discarded. This is used in the lazy match evaluation.
  12089. */
  12090. this.max_chain_length = 0;
  12091. /* To speed up deflation, hash chains are never searched beyond this
  12092. * length. A higher limit improves compression ratio but degrades the
  12093. * speed.
  12094. */
  12095. this.max_lazy_match = 0;
  12096. /* Attempt to find a better match only when the current match is strictly
  12097. * smaller than this value. This mechanism is used only for compression
  12098. * levels >= 4.
  12099. */
  12100. // That's alias to max_lazy_match, don't use directly
  12101. //this.max_insert_length = 0;
  12102. /* Insert new strings in the hash table only if the match length is not
  12103. * greater than this length. This saves time but degrades compression.
  12104. * max_insert_length is used only for compression levels <= 3.
  12105. */
  12106. this.level = 0; /* compression level (1..9) */
  12107. this.strategy = 0; /* favor or force Huffman coding*/
  12108. this.good_match = 0;
  12109. /* Use a faster search when the previous match is longer than this */
  12110. this.nice_match = 0; /* Stop searching when current match exceeds this */
  12111. /* used by trees.c: */
  12112. /* Didn't use ct_data typedef below to suppress compiler warning */
  12113. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  12114. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  12115. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  12116. // Use flat array of DOUBLE size, with interleaved fata,
  12117. // because JS does not support effective
  12118. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  12119. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  12120. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  12121. zero(this.dyn_ltree);
  12122. zero(this.dyn_dtree);
  12123. zero(this.bl_tree);
  12124. this.l_desc = null; /* desc. for literal tree */
  12125. this.d_desc = null; /* desc. for distance tree */
  12126. this.bl_desc = null; /* desc. for bit length tree */
  12127. //ush bl_count[MAX_BITS+1];
  12128. this.bl_count = new utils.Buf16(MAX_BITS+1);
  12129. /* number of codes at each bit length for an optimal tree */
  12130. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  12131. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  12132. zero(this.heap);
  12133. this.heap_len = 0; /* number of elements in the heap */
  12134. this.heap_max = 0; /* element of largest frequency */
  12135. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  12136. * The same heap array is used to build all trees.
  12137. */
  12138. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  12139. zero(this.depth);
  12140. /* Depth of each subtree used as tie breaker for trees of equal frequency
  12141. */
  12142. this.l_buf = 0; /* buffer index for literals or lengths */
  12143. this.lit_bufsize = 0;
  12144. /* Size of match buffer for literals/lengths. There are 4 reasons for
  12145. * limiting lit_bufsize to 64K:
  12146. * - frequencies can be kept in 16 bit counters
  12147. * - if compression is not successful for the first block, all input
  12148. * data is still in the window so we can still emit a stored block even
  12149. * when input comes from standard input. (This can also be done for
  12150. * all blocks if lit_bufsize is not greater than 32K.)
  12151. * - if compression is not successful for a file smaller than 64K, we can
  12152. * even emit a stored file instead of a stored block (saving 5 bytes).
  12153. * This is applicable only for zip (not gzip or zlib).
  12154. * - creating new Huffman trees less frequently may not provide fast
  12155. * adaptation to changes in the input data statistics. (Take for
  12156. * example a binary file with poorly compressible code followed by
  12157. * a highly compressible string table.) Smaller buffer sizes give
  12158. * fast adaptation but have of course the overhead of transmitting
  12159. * trees more frequently.
  12160. * - I can't count above 4
  12161. */
  12162. this.last_lit = 0; /* running index in l_buf */
  12163. this.d_buf = 0;
  12164. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  12165. * the same number of elements. To use different lengths, an extra flag
  12166. * array would be necessary.
  12167. */
  12168. this.opt_len = 0; /* bit length of current block with optimal trees */
  12169. this.static_len = 0; /* bit length of current block with static trees */
  12170. this.matches = 0; /* number of string matches in current block */
  12171. this.insert = 0; /* bytes at end of window left to insert */
  12172. this.bi_buf = 0;
  12173. /* Output buffer. bits are inserted starting at the bottom (least
  12174. * significant bits).
  12175. */
  12176. this.bi_valid = 0;
  12177. /* Number of valid bits in bi_buf. All bits above the last valid bit
  12178. * are always zero.
  12179. */
  12180. // Used for window memory init. We safely ignore it for JS. That makes
  12181. // sense only for pointers and memory check tools.
  12182. //this.high_water = 0;
  12183. /* High water mark offset in window for initialized bytes -- bytes above
  12184. * this are set to zero in order to avoid memory check warnings when
  12185. * longest match routines access bytes past the input. This is then
  12186. * updated to the new high water mark.
  12187. */
  12188. }
  12189. function deflateResetKeep(strm) {
  12190. var s;
  12191. if (!strm || !strm.state) {
  12192. return err(strm, Z_STREAM_ERROR);
  12193. }
  12194. strm.total_in = strm.total_out = 0;
  12195. strm.data_type = Z_UNKNOWN;
  12196. s = strm.state;
  12197. s.pending = 0;
  12198. s.pending_out = 0;
  12199. if (s.wrap < 0) {
  12200. s.wrap = -s.wrap;
  12201. /* was made negative by deflate(..., Z_FINISH); */
  12202. }
  12203. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  12204. strm.adler = (s.wrap === 2) ?
  12205. 0 // crc32(0, Z_NULL, 0)
  12206. :
  12207. 1; // adler32(0, Z_NULL, 0)
  12208. s.last_flush = Z_NO_FLUSH;
  12209. trees._tr_init(s);
  12210. return Z_OK;
  12211. }
  12212. function deflateReset(strm) {
  12213. var ret = deflateResetKeep(strm);
  12214. if (ret === Z_OK) {
  12215. lm_init(strm.state);
  12216. }
  12217. return ret;
  12218. }
  12219. function deflateSetHeader(strm, head) {
  12220. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12221. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  12222. strm.state.gzhead = head;
  12223. return Z_OK;
  12224. }
  12225. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  12226. if (!strm) { // === Z_NULL
  12227. return Z_STREAM_ERROR;
  12228. }
  12229. var wrap = 1;
  12230. if (level === Z_DEFAULT_COMPRESSION) {
  12231. level = 6;
  12232. }
  12233. if (windowBits < 0) { /* suppress zlib wrapper */
  12234. wrap = 0;
  12235. windowBits = -windowBits;
  12236. }
  12237. else if (windowBits > 15) {
  12238. wrap = 2; /* write gzip wrapper instead */
  12239. windowBits -= 16;
  12240. }
  12241. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  12242. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  12243. strategy < 0 || strategy > Z_FIXED) {
  12244. return err(strm, Z_STREAM_ERROR);
  12245. }
  12246. if (windowBits === 8) {
  12247. windowBits = 9;
  12248. }
  12249. /* until 256-byte window bug fixed */
  12250. var s = new DeflateState();
  12251. strm.state = s;
  12252. s.strm = strm;
  12253. s.wrap = wrap;
  12254. s.gzhead = null;
  12255. s.w_bits = windowBits;
  12256. s.w_size = 1 << s.w_bits;
  12257. s.w_mask = s.w_size - 1;
  12258. s.hash_bits = memLevel + 7;
  12259. s.hash_size = 1 << s.hash_bits;
  12260. s.hash_mask = s.hash_size - 1;
  12261. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  12262. s.window = new utils.Buf8(s.w_size * 2);
  12263. s.head = new utils.Buf16(s.hash_size);
  12264. s.prev = new utils.Buf16(s.w_size);
  12265. // Don't need mem init magic for JS.
  12266. //s.high_water = 0; /* nothing written to s->window yet */
  12267. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  12268. s.pending_buf_size = s.lit_bufsize * 4;
  12269. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  12270. s.d_buf = s.lit_bufsize >> 1;
  12271. s.l_buf = (1 + 2) * s.lit_bufsize;
  12272. s.level = level;
  12273. s.strategy = strategy;
  12274. s.method = method;
  12275. return deflateReset(strm);
  12276. }
  12277. function deflateInit(strm, level) {
  12278. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  12279. }
  12280. function deflate(strm, flush) {
  12281. var old_flush, s;
  12282. var beg, val; // for gzip header write only
  12283. if (!strm || !strm.state ||
  12284. flush > Z_BLOCK || flush < 0) {
  12285. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  12286. }
  12287. s = strm.state;
  12288. if (!strm.output ||
  12289. (!strm.input && strm.avail_in !== 0) ||
  12290. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  12291. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  12292. }
  12293. s.strm = strm; /* just in case */
  12294. old_flush = s.last_flush;
  12295. s.last_flush = flush;
  12296. /* Write the header */
  12297. if (s.status === INIT_STATE) {
  12298. if (s.wrap === 2) { // GZIP header
  12299. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  12300. put_byte(s, 31);
  12301. put_byte(s, 139);
  12302. put_byte(s, 8);
  12303. if (!s.gzhead) { // s->gzhead == Z_NULL
  12304. put_byte(s, 0);
  12305. put_byte(s, 0);
  12306. put_byte(s, 0);
  12307. put_byte(s, 0);
  12308. put_byte(s, 0);
  12309. put_byte(s, s.level === 9 ? 2 :
  12310. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  12311. 4 : 0));
  12312. put_byte(s, OS_CODE);
  12313. s.status = BUSY_STATE;
  12314. }
  12315. else {
  12316. put_byte(s, (s.gzhead.text ? 1 : 0) +
  12317. (s.gzhead.hcrc ? 2 : 0) +
  12318. (!s.gzhead.extra ? 0 : 4) +
  12319. (!s.gzhead.name ? 0 : 8) +
  12320. (!s.gzhead.comment ? 0 : 16)
  12321. );
  12322. put_byte(s, s.gzhead.time & 0xff);
  12323. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  12324. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  12325. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  12326. put_byte(s, s.level === 9 ? 2 :
  12327. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  12328. 4 : 0));
  12329. put_byte(s, s.gzhead.os & 0xff);
  12330. if (s.gzhead.extra && s.gzhead.extra.length) {
  12331. put_byte(s, s.gzhead.extra.length & 0xff);
  12332. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  12333. }
  12334. if (s.gzhead.hcrc) {
  12335. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  12336. }
  12337. s.gzindex = 0;
  12338. s.status = EXTRA_STATE;
  12339. }
  12340. }
  12341. else // DEFLATE header
  12342. {
  12343. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  12344. var level_flags = -1;
  12345. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  12346. level_flags = 0;
  12347. } else if (s.level < 6) {
  12348. level_flags = 1;
  12349. } else if (s.level === 6) {
  12350. level_flags = 2;
  12351. } else {
  12352. level_flags = 3;
  12353. }
  12354. header |= (level_flags << 6);
  12355. if (s.strstart !== 0) { header |= PRESET_DICT; }
  12356. header += 31 - (header % 31);
  12357. s.status = BUSY_STATE;
  12358. putShortMSB(s, header);
  12359. /* Save the adler32 of the preset dictionary: */
  12360. if (s.strstart !== 0) {
  12361. putShortMSB(s, strm.adler >>> 16);
  12362. putShortMSB(s, strm.adler & 0xffff);
  12363. }
  12364. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  12365. }
  12366. }
  12367. //#ifdef GZIP
  12368. if (s.status === EXTRA_STATE) {
  12369. if (s.gzhead.extra/* != Z_NULL*/) {
  12370. beg = s.pending; /* start of bytes to update crc */
  12371. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  12372. if (s.pending === s.pending_buf_size) {
  12373. if (s.gzhead.hcrc && s.pending > beg) {
  12374. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12375. }
  12376. flush_pending(strm);
  12377. beg = s.pending;
  12378. if (s.pending === s.pending_buf_size) {
  12379. break;
  12380. }
  12381. }
  12382. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  12383. s.gzindex++;
  12384. }
  12385. if (s.gzhead.hcrc && s.pending > beg) {
  12386. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12387. }
  12388. if (s.gzindex === s.gzhead.extra.length) {
  12389. s.gzindex = 0;
  12390. s.status = NAME_STATE;
  12391. }
  12392. }
  12393. else {
  12394. s.status = NAME_STATE;
  12395. }
  12396. }
  12397. if (s.status === NAME_STATE) {
  12398. if (s.gzhead.name/* != Z_NULL*/) {
  12399. beg = s.pending; /* start of bytes to update crc */
  12400. //int val;
  12401. do {
  12402. if (s.pending === s.pending_buf_size) {
  12403. if (s.gzhead.hcrc && s.pending > beg) {
  12404. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12405. }
  12406. flush_pending(strm);
  12407. beg = s.pending;
  12408. if (s.pending === s.pending_buf_size) {
  12409. val = 1;
  12410. break;
  12411. }
  12412. }
  12413. // JS specific: little magic to add zero terminator to end of string
  12414. if (s.gzindex < s.gzhead.name.length) {
  12415. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  12416. } else {
  12417. val = 0;
  12418. }
  12419. put_byte(s, val);
  12420. } while (val !== 0);
  12421. if (s.gzhead.hcrc && s.pending > beg) {
  12422. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12423. }
  12424. if (val === 0) {
  12425. s.gzindex = 0;
  12426. s.status = COMMENT_STATE;
  12427. }
  12428. }
  12429. else {
  12430. s.status = COMMENT_STATE;
  12431. }
  12432. }
  12433. if (s.status === COMMENT_STATE) {
  12434. if (s.gzhead.comment/* != Z_NULL*/) {
  12435. beg = s.pending; /* start of bytes to update crc */
  12436. //int val;
  12437. do {
  12438. if (s.pending === s.pending_buf_size) {
  12439. if (s.gzhead.hcrc && s.pending > beg) {
  12440. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12441. }
  12442. flush_pending(strm);
  12443. beg = s.pending;
  12444. if (s.pending === s.pending_buf_size) {
  12445. val = 1;
  12446. break;
  12447. }
  12448. }
  12449. // JS specific: little magic to add zero terminator to end of string
  12450. if (s.gzindex < s.gzhead.comment.length) {
  12451. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  12452. } else {
  12453. val = 0;
  12454. }
  12455. put_byte(s, val);
  12456. } while (val !== 0);
  12457. if (s.gzhead.hcrc && s.pending > beg) {
  12458. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12459. }
  12460. if (val === 0) {
  12461. s.status = HCRC_STATE;
  12462. }
  12463. }
  12464. else {
  12465. s.status = HCRC_STATE;
  12466. }
  12467. }
  12468. if (s.status === HCRC_STATE) {
  12469. if (s.gzhead.hcrc) {
  12470. if (s.pending + 2 > s.pending_buf_size) {
  12471. flush_pending(strm);
  12472. }
  12473. if (s.pending + 2 <= s.pending_buf_size) {
  12474. put_byte(s, strm.adler & 0xff);
  12475. put_byte(s, (strm.adler >> 8) & 0xff);
  12476. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  12477. s.status = BUSY_STATE;
  12478. }
  12479. }
  12480. else {
  12481. s.status = BUSY_STATE;
  12482. }
  12483. }
  12484. //#endif
  12485. /* Flush as much pending output as possible */
  12486. if (s.pending !== 0) {
  12487. flush_pending(strm);
  12488. if (strm.avail_out === 0) {
  12489. /* Since avail_out is 0, deflate will be called again with
  12490. * more output space, but possibly with both pending and
  12491. * avail_in equal to zero. There won't be anything to do,
  12492. * but this is not an error situation so make sure we
  12493. * return OK instead of BUF_ERROR at next call of deflate:
  12494. */
  12495. s.last_flush = -1;
  12496. return Z_OK;
  12497. }
  12498. /* Make sure there is something to do and avoid duplicate consecutive
  12499. * flushes. For repeated and useless calls with Z_FINISH, we keep
  12500. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  12501. */
  12502. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  12503. flush !== Z_FINISH) {
  12504. return err(strm, Z_BUF_ERROR);
  12505. }
  12506. /* User must not provide more input after the first FINISH: */
  12507. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  12508. return err(strm, Z_BUF_ERROR);
  12509. }
  12510. /* Start a new block or continue the current one.
  12511. */
  12512. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  12513. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  12514. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  12515. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  12516. configuration_table[s.level].func(s, flush));
  12517. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  12518. s.status = FINISH_STATE;
  12519. }
  12520. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  12521. if (strm.avail_out === 0) {
  12522. s.last_flush = -1;
  12523. /* avoid BUF_ERROR next call, see above */
  12524. }
  12525. return Z_OK;
  12526. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  12527. * of deflate should use the same flush parameter to make sure
  12528. * that the flush is complete. So we don't have to output an
  12529. * empty block here, this will be done at next call. This also
  12530. * ensures that for a very small output buffer, we emit at most
  12531. * one empty block.
  12532. */
  12533. }
  12534. if (bstate === BS_BLOCK_DONE) {
  12535. if (flush === Z_PARTIAL_FLUSH) {
  12536. trees._tr_align(s);
  12537. }
  12538. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  12539. trees._tr_stored_block(s, 0, 0, false);
  12540. /* For a full flush, this empty block will be recognized
  12541. * as a special marker by inflate_sync().
  12542. */
  12543. if (flush === Z_FULL_FLUSH) {
  12544. /*** CLEAR_HASH(s); ***/ /* forget history */
  12545. zero(s.head); // Fill with NIL (= 0);
  12546. if (s.lookahead === 0) {
  12547. s.strstart = 0;
  12548. s.block_start = 0;
  12549. s.insert = 0;
  12550. }
  12551. }
  12552. }
  12553. flush_pending(strm);
  12554. if (strm.avail_out === 0) {
  12555. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  12556. return Z_OK;
  12557. }
  12558. }
  12559. }
  12560. //Assert(strm->avail_out > 0, "bug2");
  12561. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  12562. if (flush !== Z_FINISH) { return Z_OK; }
  12563. if (s.wrap <= 0) { return Z_STREAM_END; }
  12564. /* Write the trailer */
  12565. if (s.wrap === 2) {
  12566. put_byte(s, strm.adler & 0xff);
  12567. put_byte(s, (strm.adler >> 8) & 0xff);
  12568. put_byte(s, (strm.adler >> 16) & 0xff);
  12569. put_byte(s, (strm.adler >> 24) & 0xff);
  12570. put_byte(s, strm.total_in & 0xff);
  12571. put_byte(s, (strm.total_in >> 8) & 0xff);
  12572. put_byte(s, (strm.total_in >> 16) & 0xff);
  12573. put_byte(s, (strm.total_in >> 24) & 0xff);
  12574. }
  12575. else
  12576. {
  12577. putShortMSB(s, strm.adler >>> 16);
  12578. putShortMSB(s, strm.adler & 0xffff);
  12579. }
  12580. flush_pending(strm);
  12581. /* If avail_out is zero, the application will call deflate again
  12582. * to flush the rest.
  12583. */
  12584. if (s.wrap > 0) { s.wrap = -s.wrap; }
  12585. /* write the trailer only once! */
  12586. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  12587. }
  12588. function deflateEnd(strm) {
  12589. var status;
  12590. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  12591. return Z_STREAM_ERROR;
  12592. }
  12593. status = strm.state.status;
  12594. if (status !== INIT_STATE &&
  12595. status !== EXTRA_STATE &&
  12596. status !== NAME_STATE &&
  12597. status !== COMMENT_STATE &&
  12598. status !== HCRC_STATE &&
  12599. status !== BUSY_STATE &&
  12600. status !== FINISH_STATE
  12601. ) {
  12602. return err(strm, Z_STREAM_ERROR);
  12603. }
  12604. strm.state = null;
  12605. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  12606. }
  12607. /* =========================================================================
  12608. * Copy the source state to the destination state
  12609. */
  12610. //function deflateCopy(dest, source) {
  12611. //
  12612. //}
  12613. exports.deflateInit = deflateInit;
  12614. exports.deflateInit2 = deflateInit2;
  12615. exports.deflateReset = deflateReset;
  12616. exports.deflateResetKeep = deflateResetKeep;
  12617. exports.deflateSetHeader = deflateSetHeader;
  12618. exports.deflate = deflate;
  12619. exports.deflateEnd = deflateEnd;
  12620. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  12621. /* Not implemented
  12622. exports.deflateBound = deflateBound;
  12623. exports.deflateCopy = deflateCopy;
  12624. exports.deflateSetDictionary = deflateSetDictionary;
  12625. exports.deflateParams = deflateParams;
  12626. exports.deflatePending = deflatePending;
  12627. exports.deflatePrime = deflatePrime;
  12628. exports.deflateTune = deflateTune;
  12629. */
  12630. },{"../utils/common":39,"./adler32":41,"./crc32":43,"./messages":49,"./trees":50}],45:[function(require,module,exports){
  12631. 'use strict';
  12632. function GZheader() {
  12633. /* true if compressed data believed to be text */
  12634. this.text = 0;
  12635. /* modification time */
  12636. this.time = 0;
  12637. /* extra flags (not used when writing a gzip file) */
  12638. this.xflags = 0;
  12639. /* operating system */
  12640. this.os = 0;
  12641. /* pointer to extra field or Z_NULL if none */
  12642. this.extra = null;
  12643. /* extra field length (valid if extra != Z_NULL) */
  12644. this.extra_len = 0; // Actually, we don't need it in JS,
  12645. // but leave for few code modifications
  12646. //
  12647. // Setup limits is not necessary because in js we should not preallocate memory
  12648. // for inflate use constant limit in 65536 bytes
  12649. //
  12650. /* space at extra (only when reading header) */
  12651. // this.extra_max = 0;
  12652. /* pointer to zero-terminated file name or Z_NULL */
  12653. this.name = '';
  12654. /* space at name (only when reading header) */
  12655. // this.name_max = 0;
  12656. /* pointer to zero-terminated comment or Z_NULL */
  12657. this.comment = '';
  12658. /* space at comment (only when reading header) */
  12659. // this.comm_max = 0;
  12660. /* true if there was or will be a header crc */
  12661. this.hcrc = 0;
  12662. /* true when done reading gzip header (not used when writing a gzip file) */
  12663. this.done = false;
  12664. }
  12665. module.exports = GZheader;
  12666. },{}],46:[function(require,module,exports){
  12667. 'use strict';
  12668. // See state defs from inflate.js
  12669. var BAD = 30; /* got a data error -- remain here until reset */
  12670. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  12671. /*
  12672. Decode literal, length, and distance codes and write out the resulting
  12673. literal and match bytes until either not enough input or output is
  12674. available, an end-of-block is encountered, or a data error is encountered.
  12675. When large enough input and output buffers are supplied to inflate(), for
  12676. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  12677. inflate execution time is spent in this routine.
  12678. Entry assumptions:
  12679. state.mode === LEN
  12680. strm.avail_in >= 6
  12681. strm.avail_out >= 258
  12682. start >= strm.avail_out
  12683. state.bits < 8
  12684. On return, state.mode is one of:
  12685. LEN -- ran out of enough output space or enough available input
  12686. TYPE -- reached end of block code, inflate() to interpret next block
  12687. BAD -- error in block data
  12688. Notes:
  12689. - The maximum input bits used by a length/distance pair is 15 bits for the
  12690. length code, 5 bits for the length extra, 15 bits for the distance code,
  12691. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  12692. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  12693. checking for available input while decoding.
  12694. - The maximum bytes that a single length/distance pair can output is 258
  12695. bytes, which is the maximum length that can be coded. inflate_fast()
  12696. requires strm.avail_out >= 258 for each loop to avoid checking for
  12697. output space.
  12698. */
  12699. module.exports = function inflate_fast(strm, start) {
  12700. var state;
  12701. var _in; /* local strm.input */
  12702. var last; /* have enough input while in < last */
  12703. var _out; /* local strm.output */
  12704. var beg; /* inflate()'s initial strm.output */
  12705. var end; /* while out < end, enough space available */
  12706. //#ifdef INFLATE_STRICT
  12707. var dmax; /* maximum distance from zlib header */
  12708. //#endif
  12709. var wsize; /* window size or zero if not using window */
  12710. var whave; /* valid bytes in the window */
  12711. var wnext; /* window write index */
  12712. var window; /* allocated sliding window, if wsize != 0 */
  12713. var hold; /* local strm.hold */
  12714. var bits; /* local strm.bits */
  12715. var lcode; /* local strm.lencode */
  12716. var dcode; /* local strm.distcode */
  12717. var lmask; /* mask for first level of length codes */
  12718. var dmask; /* mask for first level of distance codes */
  12719. var here; /* retrieved table entry */
  12720. var op; /* code bits, operation, extra bits, or */
  12721. /* window position, window bytes to copy */
  12722. var len; /* match length, unused bytes */
  12723. var dist; /* match distance */
  12724. var from; /* where to copy match from */
  12725. var from_source;
  12726. var input, output; // JS specific, because we have no pointers
  12727. /* copy state to local variables */
  12728. state = strm.state;
  12729. //here = state.here;
  12730. _in = strm.next_in;
  12731. input = strm.input;
  12732. last = _in + (strm.avail_in - 5);
  12733. _out = strm.next_out;
  12734. output = strm.output;
  12735. beg = _out - (start - strm.avail_out);
  12736. end = _out + (strm.avail_out - 257);
  12737. //#ifdef INFLATE_STRICT
  12738. dmax = state.dmax;
  12739. //#endif
  12740. wsize = state.wsize;
  12741. whave = state.whave;
  12742. wnext = state.wnext;
  12743. window = state.window;
  12744. hold = state.hold;
  12745. bits = state.bits;
  12746. lcode = state.lencode;
  12747. dcode = state.distcode;
  12748. lmask = (1 << state.lenbits) - 1;
  12749. dmask = (1 << state.distbits) - 1;
  12750. /* decode literals and length/distances until end-of-block or not enough
  12751. input data or output space */
  12752. top:
  12753. do {
  12754. if (bits < 15) {
  12755. hold += input[_in++] << bits;
  12756. bits += 8;
  12757. hold += input[_in++] << bits;
  12758. bits += 8;
  12759. }
  12760. here = lcode[hold & lmask];
  12761. dolen:
  12762. for (;;) { // Goto emulation
  12763. op = here >>> 24/*here.bits*/;
  12764. hold >>>= op;
  12765. bits -= op;
  12766. op = (here >>> 16) & 0xff/*here.op*/;
  12767. if (op === 0) { /* literal */
  12768. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  12769. // "inflate: literal '%c'\n" :
  12770. // "inflate: literal 0x%02x\n", here.val));
  12771. output[_out++] = here & 0xffff/*here.val*/;
  12772. }
  12773. else if (op & 16) { /* length base */
  12774. len = here & 0xffff/*here.val*/;
  12775. op &= 15; /* number of extra bits */
  12776. if (op) {
  12777. if (bits < op) {
  12778. hold += input[_in++] << bits;
  12779. bits += 8;
  12780. }
  12781. len += hold & ((1 << op) - 1);
  12782. hold >>>= op;
  12783. bits -= op;
  12784. }
  12785. //Tracevv((stderr, "inflate: length %u\n", len));
  12786. if (bits < 15) {
  12787. hold += input[_in++] << bits;
  12788. bits += 8;
  12789. hold += input[_in++] << bits;
  12790. bits += 8;
  12791. }
  12792. here = dcode[hold & dmask];
  12793. dodist:
  12794. for (;;) { // goto emulation
  12795. op = here >>> 24/*here.bits*/;
  12796. hold >>>= op;
  12797. bits -= op;
  12798. op = (here >>> 16) & 0xff/*here.op*/;
  12799. if (op & 16) { /* distance base */
  12800. dist = here & 0xffff/*here.val*/;
  12801. op &= 15; /* number of extra bits */
  12802. if (bits < op) {
  12803. hold += input[_in++] << bits;
  12804. bits += 8;
  12805. if (bits < op) {
  12806. hold += input[_in++] << bits;
  12807. bits += 8;
  12808. }
  12809. }
  12810. dist += hold & ((1 << op) - 1);
  12811. //#ifdef INFLATE_STRICT
  12812. if (dist > dmax) {
  12813. strm.msg = 'invalid distance too far back';
  12814. state.mode = BAD;
  12815. break top;
  12816. }
  12817. //#endif
  12818. hold >>>= op;
  12819. bits -= op;
  12820. //Tracevv((stderr, "inflate: distance %u\n", dist));
  12821. op = _out - beg; /* max distance in output */
  12822. if (dist > op) { /* see if copy from window */
  12823. op = dist - op; /* distance back in window */
  12824. if (op > whave) {
  12825. if (state.sane) {
  12826. strm.msg = 'invalid distance too far back';
  12827. state.mode = BAD;
  12828. break top;
  12829. }
  12830. // (!) This block is disabled in zlib defailts,
  12831. // don't enable it for binary compatibility
  12832. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  12833. // if (len <= op - whave) {
  12834. // do {
  12835. // output[_out++] = 0;
  12836. // } while (--len);
  12837. // continue top;
  12838. // }
  12839. // len -= op - whave;
  12840. // do {
  12841. // output[_out++] = 0;
  12842. // } while (--op > whave);
  12843. // if (op === 0) {
  12844. // from = _out - dist;
  12845. // do {
  12846. // output[_out++] = output[from++];
  12847. // } while (--len);
  12848. // continue top;
  12849. // }
  12850. //#endif
  12851. }
  12852. from = 0; // window index
  12853. from_source = window;
  12854. if (wnext === 0) { /* very common case */
  12855. from += wsize - op;
  12856. if (op < len) { /* some from window */
  12857. len -= op;
  12858. do {
  12859. output[_out++] = window[from++];
  12860. } while (--op);
  12861. from = _out - dist; /* rest from output */
  12862. from_source = output;
  12863. }
  12864. }
  12865. else if (wnext < op) { /* wrap around window */
  12866. from += wsize + wnext - op;
  12867. op -= wnext;
  12868. if (op < len) { /* some from end of window */
  12869. len -= op;
  12870. do {
  12871. output[_out++] = window[from++];
  12872. } while (--op);
  12873. from = 0;
  12874. if (wnext < len) { /* some from start of window */
  12875. op = wnext;
  12876. len -= op;
  12877. do {
  12878. output[_out++] = window[from++];
  12879. } while (--op);
  12880. from = _out - dist; /* rest from output */
  12881. from_source = output;
  12882. }
  12883. }
  12884. }
  12885. else { /* contiguous in window */
  12886. from += wnext - op;
  12887. if (op < len) { /* some from window */
  12888. len -= op;
  12889. do {
  12890. output[_out++] = window[from++];
  12891. } while (--op);
  12892. from = _out - dist; /* rest from output */
  12893. from_source = output;
  12894. }
  12895. }
  12896. while (len > 2) {
  12897. output[_out++] = from_source[from++];
  12898. output[_out++] = from_source[from++];
  12899. output[_out++] = from_source[from++];
  12900. len -= 3;
  12901. }
  12902. if (len) {
  12903. output[_out++] = from_source[from++];
  12904. if (len > 1) {
  12905. output[_out++] = from_source[from++];
  12906. }
  12907. }
  12908. }
  12909. else {
  12910. from = _out - dist; /* copy direct from output */
  12911. do { /* minimum length is three */
  12912. output[_out++] = output[from++];
  12913. output[_out++] = output[from++];
  12914. output[_out++] = output[from++];
  12915. len -= 3;
  12916. } while (len > 2);
  12917. if (len) {
  12918. output[_out++] = output[from++];
  12919. if (len > 1) {
  12920. output[_out++] = output[from++];
  12921. }
  12922. }
  12923. }
  12924. }
  12925. else if ((op & 64) === 0) { /* 2nd level distance code */
  12926. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  12927. continue dodist;
  12928. }
  12929. else {
  12930. strm.msg = 'invalid distance code';
  12931. state.mode = BAD;
  12932. break top;
  12933. }
  12934. break; // need to emulate goto via "continue"
  12935. }
  12936. }
  12937. else if ((op & 64) === 0) { /* 2nd level length code */
  12938. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  12939. continue dolen;
  12940. }
  12941. else if (op & 32) { /* end-of-block */
  12942. //Tracevv((stderr, "inflate: end of block\n"));
  12943. state.mode = TYPE;
  12944. break top;
  12945. }
  12946. else {
  12947. strm.msg = 'invalid literal/length code';
  12948. state.mode = BAD;
  12949. break top;
  12950. }
  12951. break; // need to emulate goto via "continue"
  12952. }
  12953. } while (_in < last && _out < end);
  12954. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  12955. len = bits >> 3;
  12956. _in -= len;
  12957. bits -= len << 3;
  12958. hold &= (1 << bits) - 1;
  12959. /* update state and return */
  12960. strm.next_in = _in;
  12961. strm.next_out = _out;
  12962. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  12963. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  12964. state.hold = hold;
  12965. state.bits = bits;
  12966. return;
  12967. };
  12968. },{}],47:[function(require,module,exports){
  12969. 'use strict';
  12970. var utils = require('../utils/common');
  12971. var adler32 = require('./adler32');
  12972. var crc32 = require('./crc32');
  12973. var inflate_fast = require('./inffast');
  12974. var inflate_table = require('./inftrees');
  12975. var CODES = 0;
  12976. var LENS = 1;
  12977. var DISTS = 2;
  12978. /* Public constants ==========================================================*/
  12979. /* ===========================================================================*/
  12980. /* Allowed flush values; see deflate() and inflate() below for details */
  12981. //var Z_NO_FLUSH = 0;
  12982. //var Z_PARTIAL_FLUSH = 1;
  12983. //var Z_SYNC_FLUSH = 2;
  12984. //var Z_FULL_FLUSH = 3;
  12985. var Z_FINISH = 4;
  12986. var Z_BLOCK = 5;
  12987. var Z_TREES = 6;
  12988. /* Return codes for the compression/decompression functions. Negative values
  12989. * are errors, positive values are used for special but normal events.
  12990. */
  12991. var Z_OK = 0;
  12992. var Z_STREAM_END = 1;
  12993. var Z_NEED_DICT = 2;
  12994. //var Z_ERRNO = -1;
  12995. var Z_STREAM_ERROR = -2;
  12996. var Z_DATA_ERROR = -3;
  12997. var Z_MEM_ERROR = -4;
  12998. var Z_BUF_ERROR = -5;
  12999. //var Z_VERSION_ERROR = -6;
  13000. /* The deflate compression method */
  13001. var Z_DEFLATED = 8;
  13002. /* STATES ====================================================================*/
  13003. /* ===========================================================================*/
  13004. var HEAD = 1; /* i: waiting for magic header */
  13005. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  13006. var TIME = 3; /* i: waiting for modification time (gzip) */
  13007. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  13008. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  13009. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  13010. var NAME = 7; /* i: waiting for end of file name (gzip) */
  13011. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  13012. var HCRC = 9; /* i: waiting for header crc (gzip) */
  13013. var DICTID = 10; /* i: waiting for dictionary check value */
  13014. var DICT = 11; /* waiting for inflateSetDictionary() call */
  13015. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  13016. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  13017. var STORED = 14; /* i: waiting for stored size (length and complement) */
  13018. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  13019. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  13020. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  13021. var LENLENS = 18; /* i: waiting for code length code lengths */
  13022. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  13023. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  13024. var LEN = 21; /* i: waiting for length/lit/eob code */
  13025. var LENEXT = 22; /* i: waiting for length extra bits */
  13026. var DIST = 23; /* i: waiting for distance code */
  13027. var DISTEXT = 24; /* i: waiting for distance extra bits */
  13028. var MATCH = 25; /* o: waiting for output space to copy string */
  13029. var LIT = 26; /* o: waiting for output space to write literal */
  13030. var CHECK = 27; /* i: waiting for 32-bit check value */
  13031. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  13032. var DONE = 29; /* finished check, done -- remain here until reset */
  13033. var BAD = 30; /* got a data error -- remain here until reset */
  13034. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  13035. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  13036. /* ===========================================================================*/
  13037. var ENOUGH_LENS = 852;
  13038. var ENOUGH_DISTS = 592;
  13039. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  13040. var MAX_WBITS = 15;
  13041. /* 32K LZ77 window */
  13042. var DEF_WBITS = MAX_WBITS;
  13043. function ZSWAP32(q) {
  13044. return (((q >>> 24) & 0xff) +
  13045. ((q >>> 8) & 0xff00) +
  13046. ((q & 0xff00) << 8) +
  13047. ((q & 0xff) << 24));
  13048. }
  13049. function InflateState() {
  13050. this.mode = 0; /* current inflate mode */
  13051. this.last = false; /* true if processing last block */
  13052. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  13053. this.havedict = false; /* true if dictionary provided */
  13054. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  13055. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  13056. this.check = 0; /* protected copy of check value */
  13057. this.total = 0; /* protected copy of output count */
  13058. // TODO: may be {}
  13059. this.head = null; /* where to save gzip header information */
  13060. /* sliding window */
  13061. this.wbits = 0; /* log base 2 of requested window size */
  13062. this.wsize = 0; /* window size or zero if not using window */
  13063. this.whave = 0; /* valid bytes in the window */
  13064. this.wnext = 0; /* window write index */
  13065. this.window = null; /* allocated sliding window, if needed */
  13066. /* bit accumulator */
  13067. this.hold = 0; /* input bit accumulator */
  13068. this.bits = 0; /* number of bits in "in" */
  13069. /* for string and stored block copying */
  13070. this.length = 0; /* literal or length of data to copy */
  13071. this.offset = 0; /* distance back to copy string from */
  13072. /* for table and code decoding */
  13073. this.extra = 0; /* extra bits needed */
  13074. /* fixed and dynamic code tables */
  13075. this.lencode = null; /* starting table for length/literal codes */
  13076. this.distcode = null; /* starting table for distance codes */
  13077. this.lenbits = 0; /* index bits for lencode */
  13078. this.distbits = 0; /* index bits for distcode */
  13079. /* dynamic table building */
  13080. this.ncode = 0; /* number of code length code lengths */
  13081. this.nlen = 0; /* number of length code lengths */
  13082. this.ndist = 0; /* number of distance code lengths */
  13083. this.have = 0; /* number of code lengths in lens[] */
  13084. this.next = null; /* next available space in codes[] */
  13085. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  13086. this.work = new utils.Buf16(288); /* work area for code table building */
  13087. /*
  13088. because we don't have pointers in js, we use lencode and distcode directly
  13089. as buffers so we don't need codes
  13090. */
  13091. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  13092. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  13093. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  13094. this.sane = 0; /* if false, allow invalid distance too far */
  13095. this.back = 0; /* bits back of last unprocessed length/lit */
  13096. this.was = 0; /* initial length of match */
  13097. }
  13098. function inflateResetKeep(strm) {
  13099. var state;
  13100. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13101. state = strm.state;
  13102. strm.total_in = strm.total_out = state.total = 0;
  13103. strm.msg = ''; /*Z_NULL*/
  13104. if (state.wrap) { /* to support ill-conceived Java test suite */
  13105. strm.adler = state.wrap & 1;
  13106. }
  13107. state.mode = HEAD;
  13108. state.last = 0;
  13109. state.havedict = 0;
  13110. state.dmax = 32768;
  13111. state.head = null/*Z_NULL*/;
  13112. state.hold = 0;
  13113. state.bits = 0;
  13114. //state.lencode = state.distcode = state.next = state.codes;
  13115. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  13116. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  13117. state.sane = 1;
  13118. state.back = -1;
  13119. //Tracev((stderr, "inflate: reset\n"));
  13120. return Z_OK;
  13121. }
  13122. function inflateReset(strm) {
  13123. var state;
  13124. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13125. state = strm.state;
  13126. state.wsize = 0;
  13127. state.whave = 0;
  13128. state.wnext = 0;
  13129. return inflateResetKeep(strm);
  13130. }
  13131. function inflateReset2(strm, windowBits) {
  13132. var wrap;
  13133. var state;
  13134. /* get the state */
  13135. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13136. state = strm.state;
  13137. /* extract wrap request from windowBits parameter */
  13138. if (windowBits < 0) {
  13139. wrap = 0;
  13140. windowBits = -windowBits;
  13141. }
  13142. else {
  13143. wrap = (windowBits >> 4) + 1;
  13144. if (windowBits < 48) {
  13145. windowBits &= 15;
  13146. }
  13147. }
  13148. /* set number of window bits, free window if different */
  13149. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  13150. return Z_STREAM_ERROR;
  13151. }
  13152. if (state.window !== null && state.wbits !== windowBits) {
  13153. state.window = null;
  13154. }
  13155. /* update state and reset the rest of it */
  13156. state.wrap = wrap;
  13157. state.wbits = windowBits;
  13158. return inflateReset(strm);
  13159. }
  13160. function inflateInit2(strm, windowBits) {
  13161. var ret;
  13162. var state;
  13163. if (!strm) { return Z_STREAM_ERROR; }
  13164. //strm.msg = Z_NULL; /* in case we return an error */
  13165. state = new InflateState();
  13166. //if (state === Z_NULL) return Z_MEM_ERROR;
  13167. //Tracev((stderr, "inflate: allocated\n"));
  13168. strm.state = state;
  13169. state.window = null/*Z_NULL*/;
  13170. ret = inflateReset2(strm, windowBits);
  13171. if (ret !== Z_OK) {
  13172. strm.state = null/*Z_NULL*/;
  13173. }
  13174. return ret;
  13175. }
  13176. function inflateInit(strm) {
  13177. return inflateInit2(strm, DEF_WBITS);
  13178. }
  13179. /*
  13180. Return state with length and distance decoding tables and index sizes set to
  13181. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  13182. If BUILDFIXED is defined, then instead this routine builds the tables the
  13183. first time it's called, and returns those tables the first time and
  13184. thereafter. This reduces the size of the code by about 2K bytes, in
  13185. exchange for a little execution time. However, BUILDFIXED should not be
  13186. used for threaded applications, since the rewriting of the tables and virgin
  13187. may not be thread-safe.
  13188. */
  13189. var virgin = true;
  13190. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  13191. function fixedtables(state) {
  13192. /* build fixed huffman tables if first call (may not be thread safe) */
  13193. if (virgin) {
  13194. var sym;
  13195. lenfix = new utils.Buf32(512);
  13196. distfix = new utils.Buf32(32);
  13197. /* literal/length table */
  13198. sym = 0;
  13199. while (sym < 144) { state.lens[sym++] = 8; }
  13200. while (sym < 256) { state.lens[sym++] = 9; }
  13201. while (sym < 280) { state.lens[sym++] = 7; }
  13202. while (sym < 288) { state.lens[sym++] = 8; }
  13203. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  13204. /* distance table */
  13205. sym = 0;
  13206. while (sym < 32) { state.lens[sym++] = 5; }
  13207. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  13208. /* do this just once */
  13209. virgin = false;
  13210. }
  13211. state.lencode = lenfix;
  13212. state.lenbits = 9;
  13213. state.distcode = distfix;
  13214. state.distbits = 5;
  13215. }
  13216. /*
  13217. Update the window with the last wsize (normally 32K) bytes written before
  13218. returning. If window does not exist yet, create it. This is only called
  13219. when a window is already in use, or when output has been written during this
  13220. inflate call, but the end of the deflate stream has not been reached yet.
  13221. It is also called to create a window for dictionary data when a dictionary
  13222. is loaded.
  13223. Providing output buffers larger than 32K to inflate() should provide a speed
  13224. advantage, since only the last 32K of output is copied to the sliding window
  13225. upon return from inflate(), and since all distances after the first 32K of
  13226. output will fall in the output data, making match copies simpler and faster.
  13227. The advantage may be dependent on the size of the processor's data caches.
  13228. */
  13229. function updatewindow(strm, src, end, copy) {
  13230. var dist;
  13231. var state = strm.state;
  13232. /* if it hasn't been done already, allocate space for the window */
  13233. if (state.window === null) {
  13234. state.wsize = 1 << state.wbits;
  13235. state.wnext = 0;
  13236. state.whave = 0;
  13237. state.window = new utils.Buf8(state.wsize);
  13238. }
  13239. /* copy state->wsize or less output bytes into the circular window */
  13240. if (copy >= state.wsize) {
  13241. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  13242. state.wnext = 0;
  13243. state.whave = state.wsize;
  13244. }
  13245. else {
  13246. dist = state.wsize - state.wnext;
  13247. if (dist > copy) {
  13248. dist = copy;
  13249. }
  13250. //zmemcpy(state->window + state->wnext, end - copy, dist);
  13251. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  13252. copy -= dist;
  13253. if (copy) {
  13254. //zmemcpy(state->window, end - copy, copy);
  13255. utils.arraySet(state.window,src, end - copy, copy, 0);
  13256. state.wnext = copy;
  13257. state.whave = state.wsize;
  13258. }
  13259. else {
  13260. state.wnext += dist;
  13261. if (state.wnext === state.wsize) { state.wnext = 0; }
  13262. if (state.whave < state.wsize) { state.whave += dist; }
  13263. }
  13264. }
  13265. return 0;
  13266. }
  13267. function inflate(strm, flush) {
  13268. var state;
  13269. var input, output; // input/output buffers
  13270. var next; /* next input INDEX */
  13271. var put; /* next output INDEX */
  13272. var have, left; /* available input and output */
  13273. var hold; /* bit buffer */
  13274. var bits; /* bits in bit buffer */
  13275. var _in, _out; /* save starting available input and output */
  13276. var copy; /* number of stored or match bytes to copy */
  13277. var from; /* where to copy match bytes from */
  13278. var from_source;
  13279. var here = 0; /* current decoding table entry */
  13280. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  13281. //var last; /* parent table entry */
  13282. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  13283. var len; /* length to copy for repeats, bits to drop */
  13284. var ret; /* return code */
  13285. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  13286. var opts;
  13287. var n; // temporary var for NEED_BITS
  13288. var order = /* permutation of code lengths */
  13289. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  13290. if (!strm || !strm.state || !strm.output ||
  13291. (!strm.input && strm.avail_in !== 0)) {
  13292. return Z_STREAM_ERROR;
  13293. }
  13294. state = strm.state;
  13295. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  13296. //--- LOAD() ---
  13297. put = strm.next_out;
  13298. output = strm.output;
  13299. left = strm.avail_out;
  13300. next = strm.next_in;
  13301. input = strm.input;
  13302. have = strm.avail_in;
  13303. hold = state.hold;
  13304. bits = state.bits;
  13305. //---
  13306. _in = have;
  13307. _out = left;
  13308. ret = Z_OK;
  13309. inf_leave: // goto emulation
  13310. for (;;) {
  13311. switch (state.mode) {
  13312. case HEAD:
  13313. if (state.wrap === 0) {
  13314. state.mode = TYPEDO;
  13315. break;
  13316. }
  13317. //=== NEEDBITS(16);
  13318. while (bits < 16) {
  13319. if (have === 0) { break inf_leave; }
  13320. have--;
  13321. hold += input[next++] << bits;
  13322. bits += 8;
  13323. }
  13324. //===//
  13325. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  13326. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  13327. //=== CRC2(state.check, hold);
  13328. hbuf[0] = hold & 0xff;
  13329. hbuf[1] = (hold >>> 8) & 0xff;
  13330. state.check = crc32(state.check, hbuf, 2, 0);
  13331. //===//
  13332. //=== INITBITS();
  13333. hold = 0;
  13334. bits = 0;
  13335. //===//
  13336. state.mode = FLAGS;
  13337. break;
  13338. }
  13339. state.flags = 0; /* expect zlib header */
  13340. if (state.head) {
  13341. state.head.done = false;
  13342. }
  13343. if (!(state.wrap & 1) || /* check if zlib header allowed */
  13344. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  13345. strm.msg = 'incorrect header check';
  13346. state.mode = BAD;
  13347. break;
  13348. }
  13349. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  13350. strm.msg = 'unknown compression method';
  13351. state.mode = BAD;
  13352. break;
  13353. }
  13354. //--- DROPBITS(4) ---//
  13355. hold >>>= 4;
  13356. bits -= 4;
  13357. //---//
  13358. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  13359. if (state.wbits === 0) {
  13360. state.wbits = len;
  13361. }
  13362. else if (len > state.wbits) {
  13363. strm.msg = 'invalid window size';
  13364. state.mode = BAD;
  13365. break;
  13366. }
  13367. state.dmax = 1 << len;
  13368. //Tracev((stderr, "inflate: zlib header ok\n"));
  13369. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  13370. state.mode = hold & 0x200 ? DICTID : TYPE;
  13371. //=== INITBITS();
  13372. hold = 0;
  13373. bits = 0;
  13374. //===//
  13375. break;
  13376. case FLAGS:
  13377. //=== NEEDBITS(16); */
  13378. while (bits < 16) {
  13379. if (have === 0) { break inf_leave; }
  13380. have--;
  13381. hold += input[next++] << bits;
  13382. bits += 8;
  13383. }
  13384. //===//
  13385. state.flags = hold;
  13386. if ((state.flags & 0xff) !== Z_DEFLATED) {
  13387. strm.msg = 'unknown compression method';
  13388. state.mode = BAD;
  13389. break;
  13390. }
  13391. if (state.flags & 0xe000) {
  13392. strm.msg = 'unknown header flags set';
  13393. state.mode = BAD;
  13394. break;
  13395. }
  13396. if (state.head) {
  13397. state.head.text = ((hold >> 8) & 1);
  13398. }
  13399. if (state.flags & 0x0200) {
  13400. //=== CRC2(state.check, hold);
  13401. hbuf[0] = hold & 0xff;
  13402. hbuf[1] = (hold >>> 8) & 0xff;
  13403. state.check = crc32(state.check, hbuf, 2, 0);
  13404. //===//
  13405. }
  13406. //=== INITBITS();
  13407. hold = 0;
  13408. bits = 0;
  13409. //===//
  13410. state.mode = TIME;
  13411. /* falls through */
  13412. case TIME:
  13413. //=== NEEDBITS(32); */
  13414. while (bits < 32) {
  13415. if (have === 0) { break inf_leave; }
  13416. have--;
  13417. hold += input[next++] << bits;
  13418. bits += 8;
  13419. }
  13420. //===//
  13421. if (state.head) {
  13422. state.head.time = hold;
  13423. }
  13424. if (state.flags & 0x0200) {
  13425. //=== CRC4(state.check, hold)
  13426. hbuf[0] = hold & 0xff;
  13427. hbuf[1] = (hold >>> 8) & 0xff;
  13428. hbuf[2] = (hold >>> 16) & 0xff;
  13429. hbuf[3] = (hold >>> 24) & 0xff;
  13430. state.check = crc32(state.check, hbuf, 4, 0);
  13431. //===
  13432. }
  13433. //=== INITBITS();
  13434. hold = 0;
  13435. bits = 0;
  13436. //===//
  13437. state.mode = OS;
  13438. /* falls through */
  13439. case OS:
  13440. //=== NEEDBITS(16); */
  13441. while (bits < 16) {
  13442. if (have === 0) { break inf_leave; }
  13443. have--;
  13444. hold += input[next++] << bits;
  13445. bits += 8;
  13446. }
  13447. //===//
  13448. if (state.head) {
  13449. state.head.xflags = (hold & 0xff);
  13450. state.head.os = (hold >> 8);
  13451. }
  13452. if (state.flags & 0x0200) {
  13453. //=== CRC2(state.check, hold);
  13454. hbuf[0] = hold & 0xff;
  13455. hbuf[1] = (hold >>> 8) & 0xff;
  13456. state.check = crc32(state.check, hbuf, 2, 0);
  13457. //===//
  13458. }
  13459. //=== INITBITS();
  13460. hold = 0;
  13461. bits = 0;
  13462. //===//
  13463. state.mode = EXLEN;
  13464. /* falls through */
  13465. case EXLEN:
  13466. if (state.flags & 0x0400) {
  13467. //=== NEEDBITS(16); */
  13468. while (bits < 16) {
  13469. if (have === 0) { break inf_leave; }
  13470. have--;
  13471. hold += input[next++] << bits;
  13472. bits += 8;
  13473. }
  13474. //===//
  13475. state.length = hold;
  13476. if (state.head) {
  13477. state.head.extra_len = hold;
  13478. }
  13479. if (state.flags & 0x0200) {
  13480. //=== CRC2(state.check, hold);
  13481. hbuf[0] = hold & 0xff;
  13482. hbuf[1] = (hold >>> 8) & 0xff;
  13483. state.check = crc32(state.check, hbuf, 2, 0);
  13484. //===//
  13485. }
  13486. //=== INITBITS();
  13487. hold = 0;
  13488. bits = 0;
  13489. //===//
  13490. }
  13491. else if (state.head) {
  13492. state.head.extra = null/*Z_NULL*/;
  13493. }
  13494. state.mode = EXTRA;
  13495. /* falls through */
  13496. case EXTRA:
  13497. if (state.flags & 0x0400) {
  13498. copy = state.length;
  13499. if (copy > have) { copy = have; }
  13500. if (copy) {
  13501. if (state.head) {
  13502. len = state.head.extra_len - state.length;
  13503. if (!state.head.extra) {
  13504. // Use untyped array for more conveniend processing later
  13505. state.head.extra = new Array(state.head.extra_len);
  13506. }
  13507. utils.arraySet(
  13508. state.head.extra,
  13509. input,
  13510. next,
  13511. // extra field is limited to 65536 bytes
  13512. // - no need for additional size check
  13513. copy,
  13514. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  13515. len
  13516. );
  13517. //zmemcpy(state.head.extra + len, next,
  13518. // len + copy > state.head.extra_max ?
  13519. // state.head.extra_max - len : copy);
  13520. }
  13521. if (state.flags & 0x0200) {
  13522. state.check = crc32(state.check, input, copy, next);
  13523. }
  13524. have -= copy;
  13525. next += copy;
  13526. state.length -= copy;
  13527. }
  13528. if (state.length) { break inf_leave; }
  13529. }
  13530. state.length = 0;
  13531. state.mode = NAME;
  13532. /* falls through */
  13533. case NAME:
  13534. if (state.flags & 0x0800) {
  13535. if (have === 0) { break inf_leave; }
  13536. copy = 0;
  13537. do {
  13538. // TODO: 2 or 1 bytes?
  13539. len = input[next + copy++];
  13540. /* use constant limit because in js we should not preallocate memory */
  13541. if (state.head && len &&
  13542. (state.length < 65536 /*state.head.name_max*/)) {
  13543. state.head.name += String.fromCharCode(len);
  13544. }
  13545. } while (len && copy < have);
  13546. if (state.flags & 0x0200) {
  13547. state.check = crc32(state.check, input, copy, next);
  13548. }
  13549. have -= copy;
  13550. next += copy;
  13551. if (len) { break inf_leave; }
  13552. }
  13553. else if (state.head) {
  13554. state.head.name = null;
  13555. }
  13556. state.length = 0;
  13557. state.mode = COMMENT;
  13558. /* falls through */
  13559. case COMMENT:
  13560. if (state.flags & 0x1000) {
  13561. if (have === 0) { break inf_leave; }
  13562. copy = 0;
  13563. do {
  13564. len = input[next + copy++];
  13565. /* use constant limit because in js we should not preallocate memory */
  13566. if (state.head && len &&
  13567. (state.length < 65536 /*state.head.comm_max*/)) {
  13568. state.head.comment += String.fromCharCode(len);
  13569. }
  13570. } while (len && copy < have);
  13571. if (state.flags & 0x0200) {
  13572. state.check = crc32(state.check, input, copy, next);
  13573. }
  13574. have -= copy;
  13575. next += copy;
  13576. if (len) { break inf_leave; }
  13577. }
  13578. else if (state.head) {
  13579. state.head.comment = null;
  13580. }
  13581. state.mode = HCRC;
  13582. /* falls through */
  13583. case HCRC:
  13584. if (state.flags & 0x0200) {
  13585. //=== NEEDBITS(16); */
  13586. while (bits < 16) {
  13587. if (have === 0) { break inf_leave; }
  13588. have--;
  13589. hold += input[next++] << bits;
  13590. bits += 8;
  13591. }
  13592. //===//
  13593. if (hold !== (state.check & 0xffff)) {
  13594. strm.msg = 'header crc mismatch';
  13595. state.mode = BAD;
  13596. break;
  13597. }
  13598. //=== INITBITS();
  13599. hold = 0;
  13600. bits = 0;
  13601. //===//
  13602. }
  13603. if (state.head) {
  13604. state.head.hcrc = ((state.flags >> 9) & 1);
  13605. state.head.done = true;
  13606. }
  13607. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  13608. state.mode = TYPE;
  13609. break;
  13610. case DICTID:
  13611. //=== NEEDBITS(32); */
  13612. while (bits < 32) {
  13613. if (have === 0) { break inf_leave; }
  13614. have--;
  13615. hold += input[next++] << bits;
  13616. bits += 8;
  13617. }
  13618. //===//
  13619. strm.adler = state.check = ZSWAP32(hold);
  13620. //=== INITBITS();
  13621. hold = 0;
  13622. bits = 0;
  13623. //===//
  13624. state.mode = DICT;
  13625. /* falls through */
  13626. case DICT:
  13627. if (state.havedict === 0) {
  13628. //--- RESTORE() ---
  13629. strm.next_out = put;
  13630. strm.avail_out = left;
  13631. strm.next_in = next;
  13632. strm.avail_in = have;
  13633. state.hold = hold;
  13634. state.bits = bits;
  13635. //---
  13636. return Z_NEED_DICT;
  13637. }
  13638. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  13639. state.mode = TYPE;
  13640. /* falls through */
  13641. case TYPE:
  13642. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  13643. /* falls through */
  13644. case TYPEDO:
  13645. if (state.last) {
  13646. //--- BYTEBITS() ---//
  13647. hold >>>= bits & 7;
  13648. bits -= bits & 7;
  13649. //---//
  13650. state.mode = CHECK;
  13651. break;
  13652. }
  13653. //=== NEEDBITS(3); */
  13654. while (bits < 3) {
  13655. if (have === 0) { break inf_leave; }
  13656. have--;
  13657. hold += input[next++] << bits;
  13658. bits += 8;
  13659. }
  13660. //===//
  13661. state.last = (hold & 0x01)/*BITS(1)*/;
  13662. //--- DROPBITS(1) ---//
  13663. hold >>>= 1;
  13664. bits -= 1;
  13665. //---//
  13666. switch ((hold & 0x03)/*BITS(2)*/) {
  13667. case 0: /* stored block */
  13668. //Tracev((stderr, "inflate: stored block%s\n",
  13669. // state.last ? " (last)" : ""));
  13670. state.mode = STORED;
  13671. break;
  13672. case 1: /* fixed block */
  13673. fixedtables(state);
  13674. //Tracev((stderr, "inflate: fixed codes block%s\n",
  13675. // state.last ? " (last)" : ""));
  13676. state.mode = LEN_; /* decode codes */
  13677. if (flush === Z_TREES) {
  13678. //--- DROPBITS(2) ---//
  13679. hold >>>= 2;
  13680. bits -= 2;
  13681. //---//
  13682. break inf_leave;
  13683. }
  13684. break;
  13685. case 2: /* dynamic block */
  13686. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  13687. // state.last ? " (last)" : ""));
  13688. state.mode = TABLE;
  13689. break;
  13690. case 3:
  13691. strm.msg = 'invalid block type';
  13692. state.mode = BAD;
  13693. }
  13694. //--- DROPBITS(2) ---//
  13695. hold >>>= 2;
  13696. bits -= 2;
  13697. //---//
  13698. break;
  13699. case STORED:
  13700. //--- BYTEBITS() ---// /* go to byte boundary */
  13701. hold >>>= bits & 7;
  13702. bits -= bits & 7;
  13703. //---//
  13704. //=== NEEDBITS(32); */
  13705. while (bits < 32) {
  13706. if (have === 0) { break inf_leave; }
  13707. have--;
  13708. hold += input[next++] << bits;
  13709. bits += 8;
  13710. }
  13711. //===//
  13712. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  13713. strm.msg = 'invalid stored block lengths';
  13714. state.mode = BAD;
  13715. break;
  13716. }
  13717. state.length = hold & 0xffff;
  13718. //Tracev((stderr, "inflate: stored length %u\n",
  13719. // state.length));
  13720. //=== INITBITS();
  13721. hold = 0;
  13722. bits = 0;
  13723. //===//
  13724. state.mode = COPY_;
  13725. if (flush === Z_TREES) { break inf_leave; }
  13726. /* falls through */
  13727. case COPY_:
  13728. state.mode = COPY;
  13729. /* falls through */
  13730. case COPY:
  13731. copy = state.length;
  13732. if (copy) {
  13733. if (copy > have) { copy = have; }
  13734. if (copy > left) { copy = left; }
  13735. if (copy === 0) { break inf_leave; }
  13736. //--- zmemcpy(put, next, copy); ---
  13737. utils.arraySet(output, input, next, copy, put);
  13738. //---//
  13739. have -= copy;
  13740. next += copy;
  13741. left -= copy;
  13742. put += copy;
  13743. state.length -= copy;
  13744. break;
  13745. }
  13746. //Tracev((stderr, "inflate: stored end\n"));
  13747. state.mode = TYPE;
  13748. break;
  13749. case TABLE:
  13750. //=== NEEDBITS(14); */
  13751. while (bits < 14) {
  13752. if (have === 0) { break inf_leave; }
  13753. have--;
  13754. hold += input[next++] << bits;
  13755. bits += 8;
  13756. }
  13757. //===//
  13758. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  13759. //--- DROPBITS(5) ---//
  13760. hold >>>= 5;
  13761. bits -= 5;
  13762. //---//
  13763. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  13764. //--- DROPBITS(5) ---//
  13765. hold >>>= 5;
  13766. bits -= 5;
  13767. //---//
  13768. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  13769. //--- DROPBITS(4) ---//
  13770. hold >>>= 4;
  13771. bits -= 4;
  13772. //---//
  13773. //#ifndef PKZIP_BUG_WORKAROUND
  13774. if (state.nlen > 286 || state.ndist > 30) {
  13775. strm.msg = 'too many length or distance symbols';
  13776. state.mode = BAD;
  13777. break;
  13778. }
  13779. //#endif
  13780. //Tracev((stderr, "inflate: table sizes ok\n"));
  13781. state.have = 0;
  13782. state.mode = LENLENS;
  13783. /* falls through */
  13784. case LENLENS:
  13785. while (state.have < state.ncode) {
  13786. //=== NEEDBITS(3);
  13787. while (bits < 3) {
  13788. if (have === 0) { break inf_leave; }
  13789. have--;
  13790. hold += input[next++] << bits;
  13791. bits += 8;
  13792. }
  13793. //===//
  13794. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  13795. //--- DROPBITS(3) ---//
  13796. hold >>>= 3;
  13797. bits -= 3;
  13798. //---//
  13799. }
  13800. while (state.have < 19) {
  13801. state.lens[order[state.have++]] = 0;
  13802. }
  13803. // We have separate tables & no pointers. 2 commented lines below not needed.
  13804. //state.next = state.codes;
  13805. //state.lencode = state.next;
  13806. // Switch to use dynamic table
  13807. state.lencode = state.lendyn;
  13808. state.lenbits = 7;
  13809. opts = {bits: state.lenbits};
  13810. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  13811. state.lenbits = opts.bits;
  13812. if (ret) {
  13813. strm.msg = 'invalid code lengths set';
  13814. state.mode = BAD;
  13815. break;
  13816. }
  13817. //Tracev((stderr, "inflate: code lengths ok\n"));
  13818. state.have = 0;
  13819. state.mode = CODELENS;
  13820. /* falls through */
  13821. case CODELENS:
  13822. while (state.have < state.nlen + state.ndist) {
  13823. for (;;) {
  13824. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  13825. here_bits = here >>> 24;
  13826. here_op = (here >>> 16) & 0xff;
  13827. here_val = here & 0xffff;
  13828. if ((here_bits) <= bits) { break; }
  13829. //--- PULLBYTE() ---//
  13830. if (have === 0) { break inf_leave; }
  13831. have--;
  13832. hold += input[next++] << bits;
  13833. bits += 8;
  13834. //---//
  13835. }
  13836. if (here_val < 16) {
  13837. //--- DROPBITS(here.bits) ---//
  13838. hold >>>= here_bits;
  13839. bits -= here_bits;
  13840. //---//
  13841. state.lens[state.have++] = here_val;
  13842. }
  13843. else {
  13844. if (here_val === 16) {
  13845. //=== NEEDBITS(here.bits + 2);
  13846. n = here_bits + 2;
  13847. while (bits < n) {
  13848. if (have === 0) { break inf_leave; }
  13849. have--;
  13850. hold += input[next++] << bits;
  13851. bits += 8;
  13852. }
  13853. //===//
  13854. //--- DROPBITS(here.bits) ---//
  13855. hold >>>= here_bits;
  13856. bits -= here_bits;
  13857. //---//
  13858. if (state.have === 0) {
  13859. strm.msg = 'invalid bit length repeat';
  13860. state.mode = BAD;
  13861. break;
  13862. }
  13863. len = state.lens[state.have - 1];
  13864. copy = 3 + (hold & 0x03);//BITS(2);
  13865. //--- DROPBITS(2) ---//
  13866. hold >>>= 2;
  13867. bits -= 2;
  13868. //---//
  13869. }
  13870. else if (here_val === 17) {
  13871. //=== NEEDBITS(here.bits + 3);
  13872. n = here_bits + 3;
  13873. while (bits < n) {
  13874. if (have === 0) { break inf_leave; }
  13875. have--;
  13876. hold += input[next++] << bits;
  13877. bits += 8;
  13878. }
  13879. //===//
  13880. //--- DROPBITS(here.bits) ---//
  13881. hold >>>= here_bits;
  13882. bits -= here_bits;
  13883. //---//
  13884. len = 0;
  13885. copy = 3 + (hold & 0x07);//BITS(3);
  13886. //--- DROPBITS(3) ---//
  13887. hold >>>= 3;
  13888. bits -= 3;
  13889. //---//
  13890. }
  13891. else {
  13892. //=== NEEDBITS(here.bits + 7);
  13893. n = here_bits + 7;
  13894. while (bits < n) {
  13895. if (have === 0) { break inf_leave; }
  13896. have--;
  13897. hold += input[next++] << bits;
  13898. bits += 8;
  13899. }
  13900. //===//
  13901. //--- DROPBITS(here.bits) ---//
  13902. hold >>>= here_bits;
  13903. bits -= here_bits;
  13904. //---//
  13905. len = 0;
  13906. copy = 11 + (hold & 0x7f);//BITS(7);
  13907. //--- DROPBITS(7) ---//
  13908. hold >>>= 7;
  13909. bits -= 7;
  13910. //---//
  13911. }
  13912. if (state.have + copy > state.nlen + state.ndist) {
  13913. strm.msg = 'invalid bit length repeat';
  13914. state.mode = BAD;
  13915. break;
  13916. }
  13917. while (copy--) {
  13918. state.lens[state.have++] = len;
  13919. }
  13920. }
  13921. }
  13922. /* handle error breaks in while */
  13923. if (state.mode === BAD) { break; }
  13924. /* check for end-of-block code (better have one) */
  13925. if (state.lens[256] === 0) {
  13926. strm.msg = 'invalid code -- missing end-of-block';
  13927. state.mode = BAD;
  13928. break;
  13929. }
  13930. /* build code tables -- note: do not change the lenbits or distbits
  13931. values here (9 and 6) without reading the comments in inftrees.h
  13932. concerning the ENOUGH constants, which depend on those values */
  13933. state.lenbits = 9;
  13934. opts = {bits: state.lenbits};
  13935. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  13936. // We have separate tables & no pointers. 2 commented lines below not needed.
  13937. // state.next_index = opts.table_index;
  13938. state.lenbits = opts.bits;
  13939. // state.lencode = state.next;
  13940. if (ret) {
  13941. strm.msg = 'invalid literal/lengths set';
  13942. state.mode = BAD;
  13943. break;
  13944. }
  13945. state.distbits = 6;
  13946. //state.distcode.copy(state.codes);
  13947. // Switch to use dynamic table
  13948. state.distcode = state.distdyn;
  13949. opts = {bits: state.distbits};
  13950. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  13951. // We have separate tables & no pointers. 2 commented lines below not needed.
  13952. // state.next_index = opts.table_index;
  13953. state.distbits = opts.bits;
  13954. // state.distcode = state.next;
  13955. if (ret) {
  13956. strm.msg = 'invalid distances set';
  13957. state.mode = BAD;
  13958. break;
  13959. }
  13960. //Tracev((stderr, 'inflate: codes ok\n'));
  13961. state.mode = LEN_;
  13962. if (flush === Z_TREES) { break inf_leave; }
  13963. /* falls through */
  13964. case LEN_:
  13965. state.mode = LEN;
  13966. /* falls through */
  13967. case LEN:
  13968. if (have >= 6 && left >= 258) {
  13969. //--- RESTORE() ---
  13970. strm.next_out = put;
  13971. strm.avail_out = left;
  13972. strm.next_in = next;
  13973. strm.avail_in = have;
  13974. state.hold = hold;
  13975. state.bits = bits;
  13976. //---
  13977. inflate_fast(strm, _out);
  13978. //--- LOAD() ---
  13979. put = strm.next_out;
  13980. output = strm.output;
  13981. left = strm.avail_out;
  13982. next = strm.next_in;
  13983. input = strm.input;
  13984. have = strm.avail_in;
  13985. hold = state.hold;
  13986. bits = state.bits;
  13987. //---
  13988. if (state.mode === TYPE) {
  13989. state.back = -1;
  13990. }
  13991. break;
  13992. }
  13993. state.back = 0;
  13994. for (;;) {
  13995. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  13996. here_bits = here >>> 24;
  13997. here_op = (here >>> 16) & 0xff;
  13998. here_val = here & 0xffff;
  13999. if (here_bits <= bits) { break; }
  14000. //--- PULLBYTE() ---//
  14001. if (have === 0) { break inf_leave; }
  14002. have--;
  14003. hold += input[next++] << bits;
  14004. bits += 8;
  14005. //---//
  14006. }
  14007. if (here_op && (here_op & 0xf0) === 0) {
  14008. last_bits = here_bits;
  14009. last_op = here_op;
  14010. last_val = here_val;
  14011. for (;;) {
  14012. here = state.lencode[last_val +
  14013. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  14014. here_bits = here >>> 24;
  14015. here_op = (here >>> 16) & 0xff;
  14016. here_val = here & 0xffff;
  14017. if ((last_bits + here_bits) <= bits) { break; }
  14018. //--- PULLBYTE() ---//
  14019. if (have === 0) { break inf_leave; }
  14020. have--;
  14021. hold += input[next++] << bits;
  14022. bits += 8;
  14023. //---//
  14024. }
  14025. //--- DROPBITS(last.bits) ---//
  14026. hold >>>= last_bits;
  14027. bits -= last_bits;
  14028. //---//
  14029. state.back += last_bits;
  14030. }
  14031. //--- DROPBITS(here.bits) ---//
  14032. hold >>>= here_bits;
  14033. bits -= here_bits;
  14034. //---//
  14035. state.back += here_bits;
  14036. state.length = here_val;
  14037. if (here_op === 0) {
  14038. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  14039. // "inflate: literal '%c'\n" :
  14040. // "inflate: literal 0x%02x\n", here.val));
  14041. state.mode = LIT;
  14042. break;
  14043. }
  14044. if (here_op & 32) {
  14045. //Tracevv((stderr, "inflate: end of block\n"));
  14046. state.back = -1;
  14047. state.mode = TYPE;
  14048. break;
  14049. }
  14050. if (here_op & 64) {
  14051. strm.msg = 'invalid literal/length code';
  14052. state.mode = BAD;
  14053. break;
  14054. }
  14055. state.extra = here_op & 15;
  14056. state.mode = LENEXT;
  14057. /* falls through */
  14058. case LENEXT:
  14059. if (state.extra) {
  14060. //=== NEEDBITS(state.extra);
  14061. n = state.extra;
  14062. while (bits < n) {
  14063. if (have === 0) { break inf_leave; }
  14064. have--;
  14065. hold += input[next++] << bits;
  14066. bits += 8;
  14067. }
  14068. //===//
  14069. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  14070. //--- DROPBITS(state.extra) ---//
  14071. hold >>>= state.extra;
  14072. bits -= state.extra;
  14073. //---//
  14074. state.back += state.extra;
  14075. }
  14076. //Tracevv((stderr, "inflate: length %u\n", state.length));
  14077. state.was = state.length;
  14078. state.mode = DIST;
  14079. /* falls through */
  14080. case DIST:
  14081. for (;;) {
  14082. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  14083. here_bits = here >>> 24;
  14084. here_op = (here >>> 16) & 0xff;
  14085. here_val = here & 0xffff;
  14086. if ((here_bits) <= bits) { break; }
  14087. //--- PULLBYTE() ---//
  14088. if (have === 0) { break inf_leave; }
  14089. have--;
  14090. hold += input[next++] << bits;
  14091. bits += 8;
  14092. //---//
  14093. }
  14094. if ((here_op & 0xf0) === 0) {
  14095. last_bits = here_bits;
  14096. last_op = here_op;
  14097. last_val = here_val;
  14098. for (;;) {
  14099. here = state.distcode[last_val +
  14100. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  14101. here_bits = here >>> 24;
  14102. here_op = (here >>> 16) & 0xff;
  14103. here_val = here & 0xffff;
  14104. if ((last_bits + here_bits) <= bits) { break; }
  14105. //--- PULLBYTE() ---//
  14106. if (have === 0) { break inf_leave; }
  14107. have--;
  14108. hold += input[next++] << bits;
  14109. bits += 8;
  14110. //---//
  14111. }
  14112. //--- DROPBITS(last.bits) ---//
  14113. hold >>>= last_bits;
  14114. bits -= last_bits;
  14115. //---//
  14116. state.back += last_bits;
  14117. }
  14118. //--- DROPBITS(here.bits) ---//
  14119. hold >>>= here_bits;
  14120. bits -= here_bits;
  14121. //---//
  14122. state.back += here_bits;
  14123. if (here_op & 64) {
  14124. strm.msg = 'invalid distance code';
  14125. state.mode = BAD;
  14126. break;
  14127. }
  14128. state.offset = here_val;
  14129. state.extra = (here_op) & 15;
  14130. state.mode = DISTEXT;
  14131. /* falls through */
  14132. case DISTEXT:
  14133. if (state.extra) {
  14134. //=== NEEDBITS(state.extra);
  14135. n = state.extra;
  14136. while (bits < n) {
  14137. if (have === 0) { break inf_leave; }
  14138. have--;
  14139. hold += input[next++] << bits;
  14140. bits += 8;
  14141. }
  14142. //===//
  14143. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  14144. //--- DROPBITS(state.extra) ---//
  14145. hold >>>= state.extra;
  14146. bits -= state.extra;
  14147. //---//
  14148. state.back += state.extra;
  14149. }
  14150. //#ifdef INFLATE_STRICT
  14151. if (state.offset > state.dmax) {
  14152. strm.msg = 'invalid distance too far back';
  14153. state.mode = BAD;
  14154. break;
  14155. }
  14156. //#endif
  14157. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  14158. state.mode = MATCH;
  14159. /* falls through */
  14160. case MATCH:
  14161. if (left === 0) { break inf_leave; }
  14162. copy = _out - left;
  14163. if (state.offset > copy) { /* copy from window */
  14164. copy = state.offset - copy;
  14165. if (copy > state.whave) {
  14166. if (state.sane) {
  14167. strm.msg = 'invalid distance too far back';
  14168. state.mode = BAD;
  14169. break;
  14170. }
  14171. // (!) This block is disabled in zlib defailts,
  14172. // don't enable it for binary compatibility
  14173. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  14174. // Trace((stderr, "inflate.c too far\n"));
  14175. // copy -= state.whave;
  14176. // if (copy > state.length) { copy = state.length; }
  14177. // if (copy > left) { copy = left; }
  14178. // left -= copy;
  14179. // state.length -= copy;
  14180. // do {
  14181. // output[put++] = 0;
  14182. // } while (--copy);
  14183. // if (state.length === 0) { state.mode = LEN; }
  14184. // break;
  14185. //#endif
  14186. }
  14187. if (copy > state.wnext) {
  14188. copy -= state.wnext;
  14189. from = state.wsize - copy;
  14190. }
  14191. else {
  14192. from = state.wnext - copy;
  14193. }
  14194. if (copy > state.length) { copy = state.length; }
  14195. from_source = state.window;
  14196. }
  14197. else { /* copy from output */
  14198. from_source = output;
  14199. from = put - state.offset;
  14200. copy = state.length;
  14201. }
  14202. if (copy > left) { copy = left; }
  14203. left -= copy;
  14204. state.length -= copy;
  14205. do {
  14206. output[put++] = from_source[from++];
  14207. } while (--copy);
  14208. if (state.length === 0) { state.mode = LEN; }
  14209. break;
  14210. case LIT:
  14211. if (left === 0) { break inf_leave; }
  14212. output[put++] = state.length;
  14213. left--;
  14214. state.mode = LEN;
  14215. break;
  14216. case CHECK:
  14217. if (state.wrap) {
  14218. //=== NEEDBITS(32);
  14219. while (bits < 32) {
  14220. if (have === 0) { break inf_leave; }
  14221. have--;
  14222. // Use '|' insdead of '+' to make sure that result is signed
  14223. hold |= input[next++] << bits;
  14224. bits += 8;
  14225. }
  14226. //===//
  14227. _out -= left;
  14228. strm.total_out += _out;
  14229. state.total += _out;
  14230. if (_out) {
  14231. strm.adler = state.check =
  14232. /*UPDATE(state.check, put - _out, _out);*/
  14233. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  14234. }
  14235. _out = left;
  14236. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  14237. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  14238. strm.msg = 'incorrect data check';
  14239. state.mode = BAD;
  14240. break;
  14241. }
  14242. //=== INITBITS();
  14243. hold = 0;
  14244. bits = 0;
  14245. //===//
  14246. //Tracev((stderr, "inflate: check matches trailer\n"));
  14247. }
  14248. state.mode = LENGTH;
  14249. /* falls through */
  14250. case LENGTH:
  14251. if (state.wrap && state.flags) {
  14252. //=== NEEDBITS(32);
  14253. while (bits < 32) {
  14254. if (have === 0) { break inf_leave; }
  14255. have--;
  14256. hold += input[next++] << bits;
  14257. bits += 8;
  14258. }
  14259. //===//
  14260. if (hold !== (state.total & 0xffffffff)) {
  14261. strm.msg = 'incorrect length check';
  14262. state.mode = BAD;
  14263. break;
  14264. }
  14265. //=== INITBITS();
  14266. hold = 0;
  14267. bits = 0;
  14268. //===//
  14269. //Tracev((stderr, "inflate: length matches trailer\n"));
  14270. }
  14271. state.mode = DONE;
  14272. /* falls through */
  14273. case DONE:
  14274. ret = Z_STREAM_END;
  14275. break inf_leave;
  14276. case BAD:
  14277. ret = Z_DATA_ERROR;
  14278. break inf_leave;
  14279. case MEM:
  14280. return Z_MEM_ERROR;
  14281. case SYNC:
  14282. /* falls through */
  14283. default:
  14284. return Z_STREAM_ERROR;
  14285. }
  14286. }
  14287. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  14288. /*
  14289. Return from inflate(), updating the total counts and the check value.
  14290. If there was no progress during the inflate() call, return a buffer
  14291. error. Call updatewindow() to create and/or update the window state.
  14292. Note: a memory error from inflate() is non-recoverable.
  14293. */
  14294. //--- RESTORE() ---
  14295. strm.next_out = put;
  14296. strm.avail_out = left;
  14297. strm.next_in = next;
  14298. strm.avail_in = have;
  14299. state.hold = hold;
  14300. state.bits = bits;
  14301. //---
  14302. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  14303. (state.mode < CHECK || flush !== Z_FINISH))) {
  14304. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  14305. state.mode = MEM;
  14306. return Z_MEM_ERROR;
  14307. }
  14308. }
  14309. _in -= strm.avail_in;
  14310. _out -= strm.avail_out;
  14311. strm.total_in += _in;
  14312. strm.total_out += _out;
  14313. state.total += _out;
  14314. if (state.wrap && _out) {
  14315. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  14316. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  14317. }
  14318. strm.data_type = state.bits + (state.last ? 64 : 0) +
  14319. (state.mode === TYPE ? 128 : 0) +
  14320. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  14321. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  14322. ret = Z_BUF_ERROR;
  14323. }
  14324. return ret;
  14325. }
  14326. function inflateEnd(strm) {
  14327. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  14328. return Z_STREAM_ERROR;
  14329. }
  14330. var state = strm.state;
  14331. if (state.window) {
  14332. state.window = null;
  14333. }
  14334. strm.state = null;
  14335. return Z_OK;
  14336. }
  14337. function inflateGetHeader(strm, head) {
  14338. var state;
  14339. /* check state */
  14340. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14341. state = strm.state;
  14342. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  14343. /* save header structure */
  14344. state.head = head;
  14345. head.done = false;
  14346. return Z_OK;
  14347. }
  14348. exports.inflateReset = inflateReset;
  14349. exports.inflateReset2 = inflateReset2;
  14350. exports.inflateResetKeep = inflateResetKeep;
  14351. exports.inflateInit = inflateInit;
  14352. exports.inflateInit2 = inflateInit2;
  14353. exports.inflate = inflate;
  14354. exports.inflateEnd = inflateEnd;
  14355. exports.inflateGetHeader = inflateGetHeader;
  14356. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  14357. /* Not implemented
  14358. exports.inflateCopy = inflateCopy;
  14359. exports.inflateGetDictionary = inflateGetDictionary;
  14360. exports.inflateMark = inflateMark;
  14361. exports.inflatePrime = inflatePrime;
  14362. exports.inflateSetDictionary = inflateSetDictionary;
  14363. exports.inflateSync = inflateSync;
  14364. exports.inflateSyncPoint = inflateSyncPoint;
  14365. exports.inflateUndermine = inflateUndermine;
  14366. */
  14367. },{"../utils/common":39,"./adler32":41,"./crc32":43,"./inffast":46,"./inftrees":48}],48:[function(require,module,exports){
  14368. 'use strict';
  14369. var utils = require('../utils/common');
  14370. var MAXBITS = 15;
  14371. var ENOUGH_LENS = 852;
  14372. var ENOUGH_DISTS = 592;
  14373. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  14374. var CODES = 0;
  14375. var LENS = 1;
  14376. var DISTS = 2;
  14377. var lbase = [ /* Length codes 257..285 base */
  14378. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  14379. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  14380. ];
  14381. var lext = [ /* Length codes 257..285 extra */
  14382. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  14383. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  14384. ];
  14385. var dbase = [ /* Distance codes 0..29 base */
  14386. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  14387. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  14388. 8193, 12289, 16385, 24577, 0, 0
  14389. ];
  14390. var dext = [ /* Distance codes 0..29 extra */
  14391. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  14392. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  14393. 28, 28, 29, 29, 64, 64
  14394. ];
  14395. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  14396. {
  14397. var bits = opts.bits;
  14398. //here = opts.here; /* table entry for duplication */
  14399. var len = 0; /* a code's length in bits */
  14400. var sym = 0; /* index of code symbols */
  14401. var min = 0, max = 0; /* minimum and maximum code lengths */
  14402. var root = 0; /* number of index bits for root table */
  14403. var curr = 0; /* number of index bits for current table */
  14404. var drop = 0; /* code bits to drop for sub-table */
  14405. var left = 0; /* number of prefix codes available */
  14406. var used = 0; /* code entries in table used */
  14407. var huff = 0; /* Huffman code */
  14408. var incr; /* for incrementing code, index */
  14409. var fill; /* index for replicating entries */
  14410. var low; /* low bits for current root entry */
  14411. var mask; /* mask for low root bits */
  14412. var next; /* next available space in table */
  14413. var base = null; /* base value table to use */
  14414. var base_index = 0;
  14415. // var shoextra; /* extra bits table to use */
  14416. var end; /* use base and extra for symbol > end */
  14417. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  14418. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  14419. var extra = null;
  14420. var extra_index = 0;
  14421. var here_bits, here_op, here_val;
  14422. /*
  14423. Process a set of code lengths to create a canonical Huffman code. The
  14424. code lengths are lens[0..codes-1]. Each length corresponds to the
  14425. symbols 0..codes-1. The Huffman code is generated by first sorting the
  14426. symbols by length from short to long, and retaining the symbol order
  14427. for codes with equal lengths. Then the code starts with all zero bits
  14428. for the first code of the shortest length, and the codes are integer
  14429. increments for the same length, and zeros are appended as the length
  14430. increases. For the deflate format, these bits are stored backwards
  14431. from their more natural integer increment ordering, and so when the
  14432. decoding tables are built in the large loop below, the integer codes
  14433. are incremented backwards.
  14434. This routine assumes, but does not check, that all of the entries in
  14435. lens[] are in the range 0..MAXBITS. The caller must assure this.
  14436. 1..MAXBITS is interpreted as that code length. zero means that that
  14437. symbol does not occur in this code.
  14438. The codes are sorted by computing a count of codes for each length,
  14439. creating from that a table of starting indices for each length in the
  14440. sorted table, and then entering the symbols in order in the sorted
  14441. table. The sorted table is work[], with that space being provided by
  14442. the caller.
  14443. The length counts are used for other purposes as well, i.e. finding
  14444. the minimum and maximum length codes, determining if there are any
  14445. codes at all, checking for a valid set of lengths, and looking ahead
  14446. at length counts to determine sub-table sizes when building the
  14447. decoding tables.
  14448. */
  14449. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  14450. for (len = 0; len <= MAXBITS; len++) {
  14451. count[len] = 0;
  14452. }
  14453. for (sym = 0; sym < codes; sym++) {
  14454. count[lens[lens_index + sym]]++;
  14455. }
  14456. /* bound code lengths, force root to be within code lengths */
  14457. root = bits;
  14458. for (max = MAXBITS; max >= 1; max--) {
  14459. if (count[max] !== 0) { break; }
  14460. }
  14461. if (root > max) {
  14462. root = max;
  14463. }
  14464. if (max === 0) { /* no symbols to code at all */
  14465. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  14466. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  14467. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  14468. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  14469. //table.op[opts.table_index] = 64;
  14470. //table.bits[opts.table_index] = 1;
  14471. //table.val[opts.table_index++] = 0;
  14472. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  14473. opts.bits = 1;
  14474. return 0; /* no symbols, but wait for decoding to report error */
  14475. }
  14476. for (min = 1; min < max; min++) {
  14477. if (count[min] !== 0) { break; }
  14478. }
  14479. if (root < min) {
  14480. root = min;
  14481. }
  14482. /* check for an over-subscribed or incomplete set of lengths */
  14483. left = 1;
  14484. for (len = 1; len <= MAXBITS; len++) {
  14485. left <<= 1;
  14486. left -= count[len];
  14487. if (left < 0) {
  14488. return -1;
  14489. } /* over-subscribed */
  14490. }
  14491. if (left > 0 && (type === CODES || max !== 1)) {
  14492. return -1; /* incomplete set */
  14493. }
  14494. /* generate offsets into symbol table for each length for sorting */
  14495. offs[1] = 0;
  14496. for (len = 1; len < MAXBITS; len++) {
  14497. offs[len + 1] = offs[len] + count[len];
  14498. }
  14499. /* sort symbols by length, by symbol order within each length */
  14500. for (sym = 0; sym < codes; sym++) {
  14501. if (lens[lens_index + sym] !== 0) {
  14502. work[offs[lens[lens_index + sym]]++] = sym;
  14503. }
  14504. }
  14505. /*
  14506. Create and fill in decoding tables. In this loop, the table being
  14507. filled is at next and has curr index bits. The code being used is huff
  14508. with length len. That code is converted to an index by dropping drop
  14509. bits off of the bottom. For codes where len is less than drop + curr,
  14510. those top drop + curr - len bits are incremented through all values to
  14511. fill the table with replicated entries.
  14512. root is the number of index bits for the root table. When len exceeds
  14513. root, sub-tables are created pointed to by the root entry with an index
  14514. of the low root bits of huff. This is saved in low to check for when a
  14515. new sub-table should be started. drop is zero when the root table is
  14516. being filled, and drop is root when sub-tables are being filled.
  14517. When a new sub-table is needed, it is necessary to look ahead in the
  14518. code lengths to determine what size sub-table is needed. The length
  14519. counts are used for this, and so count[] is decremented as codes are
  14520. entered in the tables.
  14521. used keeps track of how many table entries have been allocated from the
  14522. provided *table space. It is checked for LENS and DIST tables against
  14523. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  14524. the initial root table size constants. See the comments in inftrees.h
  14525. for more information.
  14526. sym increments through all symbols, and the loop terminates when
  14527. all codes of length max, i.e. all codes, have been processed. This
  14528. routine permits incomplete codes, so another loop after this one fills
  14529. in the rest of the decoding tables with invalid code markers.
  14530. */
  14531. /* set up for code type */
  14532. // poor man optimization - use if-else instead of switch,
  14533. // to avoid deopts in old v8
  14534. if (type === CODES) {
  14535. base = extra = work; /* dummy value--not used */
  14536. end = 19;
  14537. } else if (type === LENS) {
  14538. base = lbase;
  14539. base_index -= 257;
  14540. extra = lext;
  14541. extra_index -= 257;
  14542. end = 256;
  14543. } else { /* DISTS */
  14544. base = dbase;
  14545. extra = dext;
  14546. end = -1;
  14547. }
  14548. /* initialize opts for loop */
  14549. huff = 0; /* starting code */
  14550. sym = 0; /* starting code symbol */
  14551. len = min; /* starting code length */
  14552. next = table_index; /* current table to fill in */
  14553. curr = root; /* current table index bits */
  14554. drop = 0; /* current bits to drop from code for index */
  14555. low = -1; /* trigger new sub-table when len > root */
  14556. used = 1 << root; /* use root table entries */
  14557. mask = used - 1; /* mask for comparing low */
  14558. /* check available table space */
  14559. if ((type === LENS && used > ENOUGH_LENS) ||
  14560. (type === DISTS && used > ENOUGH_DISTS)) {
  14561. return 1;
  14562. }
  14563. var i=0;
  14564. /* process all codes and make table entries */
  14565. for (;;) {
  14566. i++;
  14567. /* create table entry */
  14568. here_bits = len - drop;
  14569. if (work[sym] < end) {
  14570. here_op = 0;
  14571. here_val = work[sym];
  14572. }
  14573. else if (work[sym] > end) {
  14574. here_op = extra[extra_index + work[sym]];
  14575. here_val = base[base_index + work[sym]];
  14576. }
  14577. else {
  14578. here_op = 32 + 64; /* end of block */
  14579. here_val = 0;
  14580. }
  14581. /* replicate for those indices with low len bits equal to huff */
  14582. incr = 1 << (len - drop);
  14583. fill = 1 << curr;
  14584. min = fill; /* save offset to next table */
  14585. do {
  14586. fill -= incr;
  14587. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  14588. } while (fill !== 0);
  14589. /* backwards increment the len-bit code huff */
  14590. incr = 1 << (len - 1);
  14591. while (huff & incr) {
  14592. incr >>= 1;
  14593. }
  14594. if (incr !== 0) {
  14595. huff &= incr - 1;
  14596. huff += incr;
  14597. } else {
  14598. huff = 0;
  14599. }
  14600. /* go to next symbol, update count, len */
  14601. sym++;
  14602. if (--count[len] === 0) {
  14603. if (len === max) { break; }
  14604. len = lens[lens_index + work[sym]];
  14605. }
  14606. /* create new sub-table if needed */
  14607. if (len > root && (huff & mask) !== low) {
  14608. /* if first time, transition to sub-tables */
  14609. if (drop === 0) {
  14610. drop = root;
  14611. }
  14612. /* increment past last table */
  14613. next += min; /* here min is 1 << curr */
  14614. /* determine length of next table */
  14615. curr = len - drop;
  14616. left = 1 << curr;
  14617. while (curr + drop < max) {
  14618. left -= count[curr + drop];
  14619. if (left <= 0) { break; }
  14620. curr++;
  14621. left <<= 1;
  14622. }
  14623. /* check for enough space */
  14624. used += 1 << curr;
  14625. if ((type === LENS && used > ENOUGH_LENS) ||
  14626. (type === DISTS && used > ENOUGH_DISTS)) {
  14627. return 1;
  14628. }
  14629. /* point entry in root table to sub-table */
  14630. low = huff & mask;
  14631. /*table.op[low] = curr;
  14632. table.bits[low] = root;
  14633. table.val[low] = next - opts.table_index;*/
  14634. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  14635. }
  14636. }
  14637. /* fill in remaining table entry if code is incomplete (guaranteed to have
  14638. at most one remaining entry, since if the code is incomplete, the
  14639. maximum code length that was allowed to get this far is one bit) */
  14640. if (huff !== 0) {
  14641. //table.op[next + huff] = 64; /* invalid code marker */
  14642. //table.bits[next + huff] = len - drop;
  14643. //table.val[next + huff] = 0;
  14644. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  14645. }
  14646. /* set return parameters */
  14647. //opts.table_index += used;
  14648. opts.bits = root;
  14649. return 0;
  14650. };
  14651. },{"../utils/common":39}],49:[function(require,module,exports){
  14652. 'use strict';
  14653. module.exports = {
  14654. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  14655. '1': 'stream end', /* Z_STREAM_END 1 */
  14656. '0': '', /* Z_OK 0 */
  14657. '-1': 'file error', /* Z_ERRNO (-1) */
  14658. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  14659. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  14660. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  14661. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  14662. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  14663. };
  14664. },{}],50:[function(require,module,exports){
  14665. 'use strict';
  14666. var utils = require('../utils/common');
  14667. /* Public constants ==========================================================*/
  14668. /* ===========================================================================*/
  14669. //var Z_FILTERED = 1;
  14670. //var Z_HUFFMAN_ONLY = 2;
  14671. //var Z_RLE = 3;
  14672. var Z_FIXED = 4;
  14673. //var Z_DEFAULT_STRATEGY = 0;
  14674. /* Possible values of the data_type field (though see inflate()) */
  14675. var Z_BINARY = 0;
  14676. var Z_TEXT = 1;
  14677. //var Z_ASCII = 1; // = Z_TEXT
  14678. var Z_UNKNOWN = 2;
  14679. /*============================================================================*/
  14680. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14681. // From zutil.h
  14682. var STORED_BLOCK = 0;
  14683. var STATIC_TREES = 1;
  14684. var DYN_TREES = 2;
  14685. /* The three kinds of block type */
  14686. var MIN_MATCH = 3;
  14687. var MAX_MATCH = 258;
  14688. /* The minimum and maximum match lengths */
  14689. // From deflate.h
  14690. /* ===========================================================================
  14691. * Internal compression state.
  14692. */
  14693. var LENGTH_CODES = 29;
  14694. /* number of length codes, not counting the special END_BLOCK code */
  14695. var LITERALS = 256;
  14696. /* number of literal bytes 0..255 */
  14697. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14698. /* number of Literal or Length codes, including the END_BLOCK code */
  14699. var D_CODES = 30;
  14700. /* number of distance codes */
  14701. var BL_CODES = 19;
  14702. /* number of codes used to transfer the bit lengths */
  14703. var HEAP_SIZE = 2*L_CODES + 1;
  14704. /* maximum heap size */
  14705. var MAX_BITS = 15;
  14706. /* All codes must not exceed MAX_BITS bits */
  14707. var Buf_size = 16;
  14708. /* size of bit buffer in bi_buf */
  14709. /* ===========================================================================
  14710. * Constants
  14711. */
  14712. var MAX_BL_BITS = 7;
  14713. /* Bit length codes must not exceed MAX_BL_BITS bits */
  14714. var END_BLOCK = 256;
  14715. /* end of block literal code */
  14716. var REP_3_6 = 16;
  14717. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  14718. var REPZ_3_10 = 17;
  14719. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  14720. var REPZ_11_138 = 18;
  14721. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  14722. var extra_lbits = /* extra bits for each length code */
  14723. [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];
  14724. var extra_dbits = /* extra bits for each distance code */
  14725. [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];
  14726. var extra_blbits = /* extra bits for each bit length code */
  14727. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  14728. var bl_order =
  14729. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  14730. /* The lengths of the bit length codes are sent in order of decreasing
  14731. * probability, to avoid transmitting the lengths for unused bit length codes.
  14732. */
  14733. /* ===========================================================================
  14734. * Local data. These are initialized only once.
  14735. */
  14736. // We pre-fill arrays with 0 to avoid uninitialized gaps
  14737. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  14738. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  14739. var static_ltree = new Array((L_CODES+2) * 2);
  14740. zero(static_ltree);
  14741. /* The static literal tree. Since the bit lengths are imposed, there is no
  14742. * need for the L_CODES extra codes used during heap construction. However
  14743. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  14744. * below).
  14745. */
  14746. var static_dtree = new Array(D_CODES * 2);
  14747. zero(static_dtree);
  14748. /* The static distance tree. (Actually a trivial tree since all codes use
  14749. * 5 bits.)
  14750. */
  14751. var _dist_code = new Array(DIST_CODE_LEN);
  14752. zero(_dist_code);
  14753. /* Distance codes. The first 256 values correspond to the distances
  14754. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  14755. * the 15 bit distances.
  14756. */
  14757. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  14758. zero(_length_code);
  14759. /* length code for each normalized match length (0 == MIN_MATCH) */
  14760. var base_length = new Array(LENGTH_CODES);
  14761. zero(base_length);
  14762. /* First normalized length for each code (0 = MIN_MATCH) */
  14763. var base_dist = new Array(D_CODES);
  14764. zero(base_dist);
  14765. /* First normalized distance for each code (0 = distance of 1) */
  14766. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  14767. this.static_tree = static_tree; /* static tree or NULL */
  14768. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  14769. this.extra_base = extra_base; /* base index for extra_bits */
  14770. this.elems = elems; /* max number of elements in the tree */
  14771. this.max_length = max_length; /* max bit length for the codes */
  14772. // show if `static_tree` has data or dummy - needed for monomorphic objects
  14773. this.has_stree = static_tree && static_tree.length;
  14774. };
  14775. var static_l_desc;
  14776. var static_d_desc;
  14777. var static_bl_desc;
  14778. var TreeDesc = function(dyn_tree, stat_desc) {
  14779. this.dyn_tree = dyn_tree; /* the dynamic tree */
  14780. this.max_code = 0; /* largest code with non zero frequency */
  14781. this.stat_desc = stat_desc; /* the corresponding static tree */
  14782. };
  14783. function d_code(dist) {
  14784. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  14785. }
  14786. /* ===========================================================================
  14787. * Output a short LSB first on the stream.
  14788. * IN assertion: there is enough room in pendingBuf.
  14789. */
  14790. function put_short (s, w) {
  14791. // put_byte(s, (uch)((w) & 0xff));
  14792. // put_byte(s, (uch)((ush)(w) >> 8));
  14793. s.pending_buf[s.pending++] = (w) & 0xff;
  14794. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  14795. }
  14796. /* ===========================================================================
  14797. * Send a value on a given number of bits.
  14798. * IN assertion: length <= 16 and value fits in length bits.
  14799. */
  14800. function send_bits(s, value, length) {
  14801. if (s.bi_valid > (Buf_size - length)) {
  14802. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  14803. put_short(s, s.bi_buf);
  14804. s.bi_buf = value >> (Buf_size - s.bi_valid);
  14805. s.bi_valid += length - Buf_size;
  14806. } else {
  14807. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  14808. s.bi_valid += length;
  14809. }
  14810. }
  14811. function send_code(s, c, tree) {
  14812. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  14813. }
  14814. /* ===========================================================================
  14815. * Reverse the first len bits of a code, using straightforward code (a faster
  14816. * method would use a table)
  14817. * IN assertion: 1 <= len <= 15
  14818. */
  14819. function bi_reverse(code, len) {
  14820. var res = 0;
  14821. do {
  14822. res |= code & 1;
  14823. code >>>= 1;
  14824. res <<= 1;
  14825. } while (--len > 0);
  14826. return res >>> 1;
  14827. }
  14828. /* ===========================================================================
  14829. * Flush the bit buffer, keeping at most 7 bits in it.
  14830. */
  14831. function bi_flush(s) {
  14832. if (s.bi_valid === 16) {
  14833. put_short(s, s.bi_buf);
  14834. s.bi_buf = 0;
  14835. s.bi_valid = 0;
  14836. } else if (s.bi_valid >= 8) {
  14837. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  14838. s.bi_buf >>= 8;
  14839. s.bi_valid -= 8;
  14840. }
  14841. }
  14842. /* ===========================================================================
  14843. * Compute the optimal bit lengths for a tree and update the total bit length
  14844. * for the current block.
  14845. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  14846. * above are the tree nodes sorted by increasing frequency.
  14847. * OUT assertions: the field len is set to the optimal bit length, the
  14848. * array bl_count contains the frequencies for each bit length.
  14849. * The length opt_len is updated; static_len is also updated if stree is
  14850. * not null.
  14851. */
  14852. function gen_bitlen(s, desc)
  14853. // deflate_state *s;
  14854. // tree_desc *desc; /* the tree descriptor */
  14855. {
  14856. var tree = desc.dyn_tree;
  14857. var max_code = desc.max_code;
  14858. var stree = desc.stat_desc.static_tree;
  14859. var has_stree = desc.stat_desc.has_stree;
  14860. var extra = desc.stat_desc.extra_bits;
  14861. var base = desc.stat_desc.extra_base;
  14862. var max_length = desc.stat_desc.max_length;
  14863. var h; /* heap index */
  14864. var n, m; /* iterate over the tree elements */
  14865. var bits; /* bit length */
  14866. var xbits; /* extra bits */
  14867. var f; /* frequency */
  14868. var overflow = 0; /* number of elements with bit length too large */
  14869. for (bits = 0; bits <= MAX_BITS; bits++) {
  14870. s.bl_count[bits] = 0;
  14871. }
  14872. /* In a first pass, compute the optimal bit lengths (which may
  14873. * overflow in the case of the bit length tree).
  14874. */
  14875. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  14876. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  14877. n = s.heap[h];
  14878. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  14879. if (bits > max_length) {
  14880. bits = max_length;
  14881. overflow++;
  14882. }
  14883. tree[n*2 + 1]/*.Len*/ = bits;
  14884. /* We overwrite tree[n].Dad which is no longer needed */
  14885. if (n > max_code) { continue; } /* not a leaf node */
  14886. s.bl_count[bits]++;
  14887. xbits = 0;
  14888. if (n >= base) {
  14889. xbits = extra[n-base];
  14890. }
  14891. f = tree[n * 2]/*.Freq*/;
  14892. s.opt_len += f * (bits + xbits);
  14893. if (has_stree) {
  14894. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  14895. }
  14896. }
  14897. if (overflow === 0) { return; }
  14898. // Trace((stderr,"\nbit length overflow\n"));
  14899. /* This happens for example on obj2 and pic of the Calgary corpus */
  14900. /* Find the first bit length which could increase: */
  14901. do {
  14902. bits = max_length-1;
  14903. while (s.bl_count[bits] === 0) { bits--; }
  14904. s.bl_count[bits]--; /* move one leaf down the tree */
  14905. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  14906. s.bl_count[max_length]--;
  14907. /* The brother of the overflow item also moves one step up,
  14908. * but this does not affect bl_count[max_length]
  14909. */
  14910. overflow -= 2;
  14911. } while (overflow > 0);
  14912. /* Now recompute all bit lengths, scanning in increasing frequency.
  14913. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  14914. * lengths instead of fixing only the wrong ones. This idea is taken
  14915. * from 'ar' written by Haruhiko Okumura.)
  14916. */
  14917. for (bits = max_length; bits !== 0; bits--) {
  14918. n = s.bl_count[bits];
  14919. while (n !== 0) {
  14920. m = s.heap[--h];
  14921. if (m > max_code) { continue; }
  14922. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  14923. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  14924. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  14925. tree[m*2 + 1]/*.Len*/ = bits;
  14926. }
  14927. n--;
  14928. }
  14929. }
  14930. }
  14931. /* ===========================================================================
  14932. * Generate the codes for a given tree and bit counts (which need not be
  14933. * optimal).
  14934. * IN assertion: the array bl_count contains the bit length statistics for
  14935. * the given tree and the field len is set for all tree elements.
  14936. * OUT assertion: the field code is set for all tree elements of non
  14937. * zero code length.
  14938. */
  14939. function gen_codes(tree, max_code, bl_count)
  14940. // ct_data *tree; /* the tree to decorate */
  14941. // int max_code; /* largest code with non zero frequency */
  14942. // ushf *bl_count; /* number of codes at each bit length */
  14943. {
  14944. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  14945. var code = 0; /* running code value */
  14946. var bits; /* bit index */
  14947. var n; /* code index */
  14948. /* The distribution counts are first used to generate the code values
  14949. * without bit reversal.
  14950. */
  14951. for (bits = 1; bits <= MAX_BITS; bits++) {
  14952. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  14953. }
  14954. /* Check that the bit counts in bl_count are consistent. The last code
  14955. * must be all ones.
  14956. */
  14957. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  14958. // "inconsistent bit counts");
  14959. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  14960. for (n = 0; n <= max_code; n++) {
  14961. var len = tree[n*2 + 1]/*.Len*/;
  14962. if (len === 0) { continue; }
  14963. /* Now reverse the bits */
  14964. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  14965. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  14966. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  14967. }
  14968. }
  14969. /* ===========================================================================
  14970. * Initialize the various 'constant' tables.
  14971. */
  14972. function tr_static_init() {
  14973. var n; /* iterates over tree elements */
  14974. var bits; /* bit counter */
  14975. var length; /* length value */
  14976. var code; /* code value */
  14977. var dist; /* distance index */
  14978. var bl_count = new Array(MAX_BITS+1);
  14979. /* number of codes at each bit length for an optimal tree */
  14980. // do check in _tr_init()
  14981. //if (static_init_done) return;
  14982. /* For some embedded targets, global variables are not initialized: */
  14983. /*#ifdef NO_INIT_GLOBAL_POINTERS
  14984. static_l_desc.static_tree = static_ltree;
  14985. static_l_desc.extra_bits = extra_lbits;
  14986. static_d_desc.static_tree = static_dtree;
  14987. static_d_desc.extra_bits = extra_dbits;
  14988. static_bl_desc.extra_bits = extra_blbits;
  14989. #endif*/
  14990. /* Initialize the mapping length (0..255) -> length code (0..28) */
  14991. length = 0;
  14992. for (code = 0; code < LENGTH_CODES-1; code++) {
  14993. base_length[code] = length;
  14994. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  14995. _length_code[length++] = code;
  14996. }
  14997. }
  14998. //Assert (length == 256, "tr_static_init: length != 256");
  14999. /* Note that the length 255 (match length 258) can be represented
  15000. * in two different ways: code 284 + 5 bits or code 285, so we
  15001. * overwrite length_code[255] to use the best encoding:
  15002. */
  15003. _length_code[length-1] = code;
  15004. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  15005. dist = 0;
  15006. for (code = 0 ; code < 16; code++) {
  15007. base_dist[code] = dist;
  15008. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  15009. _dist_code[dist++] = code;
  15010. }
  15011. }
  15012. //Assert (dist == 256, "tr_static_init: dist != 256");
  15013. dist >>= 7; /* from now on, all distances are divided by 128 */
  15014. for (; code < D_CODES; code++) {
  15015. base_dist[code] = dist << 7;
  15016. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  15017. _dist_code[256 + dist++] = code;
  15018. }
  15019. }
  15020. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  15021. /* Construct the codes of the static literal tree */
  15022. for (bits = 0; bits <= MAX_BITS; bits++) {
  15023. bl_count[bits] = 0;
  15024. }
  15025. n = 0;
  15026. while (n <= 143) {
  15027. static_ltree[n*2 + 1]/*.Len*/ = 8;
  15028. n++;
  15029. bl_count[8]++;
  15030. }
  15031. while (n <= 255) {
  15032. static_ltree[n*2 + 1]/*.Len*/ = 9;
  15033. n++;
  15034. bl_count[9]++;
  15035. }
  15036. while (n <= 279) {
  15037. static_ltree[n*2 + 1]/*.Len*/ = 7;
  15038. n++;
  15039. bl_count[7]++;
  15040. }
  15041. while (n <= 287) {
  15042. static_ltree[n*2 + 1]/*.Len*/ = 8;
  15043. n++;
  15044. bl_count[8]++;
  15045. }
  15046. /* Codes 286 and 287 do not exist, but we must include them in the
  15047. * tree construction to get a canonical Huffman tree (longest code
  15048. * all ones)
  15049. */
  15050. gen_codes(static_ltree, L_CODES+1, bl_count);
  15051. /* The static distance tree is trivial: */
  15052. for (n = 0; n < D_CODES; n++) {
  15053. static_dtree[n*2 + 1]/*.Len*/ = 5;
  15054. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  15055. }
  15056. // Now data ready and we can init static trees
  15057. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  15058. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  15059. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  15060. //static_init_done = true;
  15061. }
  15062. /* ===========================================================================
  15063. * Initialize a new block.
  15064. */
  15065. function init_block(s) {
  15066. var n; /* iterates over tree elements */
  15067. /* Initialize the trees. */
  15068. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  15069. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  15070. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  15071. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  15072. s.opt_len = s.static_len = 0;
  15073. s.last_lit = s.matches = 0;
  15074. }
  15075. /* ===========================================================================
  15076. * Flush the bit buffer and align the output on a byte boundary
  15077. */
  15078. function bi_windup(s)
  15079. {
  15080. if (s.bi_valid > 8) {
  15081. put_short(s, s.bi_buf);
  15082. } else if (s.bi_valid > 0) {
  15083. //put_byte(s, (Byte)s->bi_buf);
  15084. s.pending_buf[s.pending++] = s.bi_buf;
  15085. }
  15086. s.bi_buf = 0;
  15087. s.bi_valid = 0;
  15088. }
  15089. /* ===========================================================================
  15090. * Copy a stored block, storing first the length and its
  15091. * one's complement if requested.
  15092. */
  15093. function copy_block(s, buf, len, header)
  15094. //DeflateState *s;
  15095. //charf *buf; /* the input data */
  15096. //unsigned len; /* its length */
  15097. //int header; /* true if block header must be written */
  15098. {
  15099. bi_windup(s); /* align on byte boundary */
  15100. if (header) {
  15101. put_short(s, len);
  15102. put_short(s, ~len);
  15103. }
  15104. // while (len--) {
  15105. // put_byte(s, *buf++);
  15106. // }
  15107. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  15108. s.pending += len;
  15109. }
  15110. /* ===========================================================================
  15111. * Compares to subtrees, using the tree depth as tie breaker when
  15112. * the subtrees have equal frequency. This minimizes the worst case length.
  15113. */
  15114. function smaller(tree, n, m, depth) {
  15115. var _n2 = n*2;
  15116. var _m2 = m*2;
  15117. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  15118. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  15119. }
  15120. /* ===========================================================================
  15121. * Restore the heap property by moving down the tree starting at node k,
  15122. * exchanging a node with the smallest of its two sons if necessary, stopping
  15123. * when the heap property is re-established (each father smaller than its
  15124. * two sons).
  15125. */
  15126. function pqdownheap(s, tree, k)
  15127. // deflate_state *s;
  15128. // ct_data *tree; /* the tree to restore */
  15129. // int k; /* node to move down */
  15130. {
  15131. var v = s.heap[k];
  15132. var j = k << 1; /* left son of k */
  15133. while (j <= s.heap_len) {
  15134. /* Set j to the smallest of the two sons: */
  15135. if (j < s.heap_len &&
  15136. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  15137. j++;
  15138. }
  15139. /* Exit if v is smaller than both sons */
  15140. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  15141. /* Exchange v with the smallest son */
  15142. s.heap[k] = s.heap[j];
  15143. k = j;
  15144. /* And continue down the tree, setting j to the left son of k */
  15145. j <<= 1;
  15146. }
  15147. s.heap[k] = v;
  15148. }
  15149. // inlined manually
  15150. // var SMALLEST = 1;
  15151. /* ===========================================================================
  15152. * Send the block data compressed using the given Huffman trees
  15153. */
  15154. function compress_block(s, ltree, dtree)
  15155. // deflate_state *s;
  15156. // const ct_data *ltree; /* literal tree */
  15157. // const ct_data *dtree; /* distance tree */
  15158. {
  15159. var dist; /* distance of matched string */
  15160. var lc; /* match length or unmatched char (if dist == 0) */
  15161. var lx = 0; /* running index in l_buf */
  15162. var code; /* the code to send */
  15163. var extra; /* number of extra bits to send */
  15164. if (s.last_lit !== 0) {
  15165. do {
  15166. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  15167. lc = s.pending_buf[s.l_buf + lx];
  15168. lx++;
  15169. if (dist === 0) {
  15170. send_code(s, lc, ltree); /* send a literal byte */
  15171. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  15172. } else {
  15173. /* Here, lc is the match length - MIN_MATCH */
  15174. code = _length_code[lc];
  15175. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  15176. extra = extra_lbits[code];
  15177. if (extra !== 0) {
  15178. lc -= base_length[code];
  15179. send_bits(s, lc, extra); /* send the extra length bits */
  15180. }
  15181. dist--; /* dist is now the match distance - 1 */
  15182. code = d_code(dist);
  15183. //Assert (code < D_CODES, "bad d_code");
  15184. send_code(s, code, dtree); /* send the distance code */
  15185. extra = extra_dbits[code];
  15186. if (extra !== 0) {
  15187. dist -= base_dist[code];
  15188. send_bits(s, dist, extra); /* send the extra distance bits */
  15189. }
  15190. } /* literal or match pair ? */
  15191. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  15192. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  15193. // "pendingBuf overflow");
  15194. } while (lx < s.last_lit);
  15195. }
  15196. send_code(s, END_BLOCK, ltree);
  15197. }
  15198. /* ===========================================================================
  15199. * Construct one Huffman tree and assigns the code bit strings and lengths.
  15200. * Update the total bit length for the current block.
  15201. * IN assertion: the field freq is set for all tree elements.
  15202. * OUT assertions: the fields len and code are set to the optimal bit length
  15203. * and corresponding code. The length opt_len is updated; static_len is
  15204. * also updated if stree is not null. The field max_code is set.
  15205. */
  15206. function build_tree(s, desc)
  15207. // deflate_state *s;
  15208. // tree_desc *desc; /* the tree descriptor */
  15209. {
  15210. var tree = desc.dyn_tree;
  15211. var stree = desc.stat_desc.static_tree;
  15212. var has_stree = desc.stat_desc.has_stree;
  15213. var elems = desc.stat_desc.elems;
  15214. var n, m; /* iterate over heap elements */
  15215. var max_code = -1; /* largest code with non zero frequency */
  15216. var node; /* new node being created */
  15217. /* Construct the initial heap, with least frequent element in
  15218. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  15219. * heap[0] is not used.
  15220. */
  15221. s.heap_len = 0;
  15222. s.heap_max = HEAP_SIZE;
  15223. for (n = 0; n < elems; n++) {
  15224. if (tree[n * 2]/*.Freq*/ !== 0) {
  15225. s.heap[++s.heap_len] = max_code = n;
  15226. s.depth[n] = 0;
  15227. } else {
  15228. tree[n*2 + 1]/*.Len*/ = 0;
  15229. }
  15230. }
  15231. /* The pkzip format requires that at least one distance code exists,
  15232. * and that at least one bit should be sent even if there is only one
  15233. * possible code. So to avoid special checks later on we force at least
  15234. * two codes of non zero frequency.
  15235. */
  15236. while (s.heap_len < 2) {
  15237. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  15238. tree[node * 2]/*.Freq*/ = 1;
  15239. s.depth[node] = 0;
  15240. s.opt_len--;
  15241. if (has_stree) {
  15242. s.static_len -= stree[node*2 + 1]/*.Len*/;
  15243. }
  15244. /* node is 0 or 1 so it does not have extra bits */
  15245. }
  15246. desc.max_code = max_code;
  15247. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  15248. * establish sub-heaps of increasing lengths:
  15249. */
  15250. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  15251. /* Construct the Huffman tree by repeatedly combining the least two
  15252. * frequent nodes.
  15253. */
  15254. node = elems; /* next internal node of the tree */
  15255. do {
  15256. //pqremove(s, tree, n); /* n = node of least frequency */
  15257. /*** pqremove ***/
  15258. n = s.heap[1/*SMALLEST*/];
  15259. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  15260. pqdownheap(s, tree, 1/*SMALLEST*/);
  15261. /***/
  15262. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  15263. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  15264. s.heap[--s.heap_max] = m;
  15265. /* Create a new node father of n and m */
  15266. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  15267. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  15268. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  15269. /* and insert the new node in the heap */
  15270. s.heap[1/*SMALLEST*/] = node++;
  15271. pqdownheap(s, tree, 1/*SMALLEST*/);
  15272. } while (s.heap_len >= 2);
  15273. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  15274. /* At this point, the fields freq and dad are set. We can now
  15275. * generate the bit lengths.
  15276. */
  15277. gen_bitlen(s, desc);
  15278. /* The field len is now set, we can generate the bit codes */
  15279. gen_codes(tree, max_code, s.bl_count);
  15280. }
  15281. /* ===========================================================================
  15282. * Scan a literal or distance tree to determine the frequencies of the codes
  15283. * in the bit length tree.
  15284. */
  15285. function scan_tree(s, tree, max_code)
  15286. // deflate_state *s;
  15287. // ct_data *tree; /* the tree to be scanned */
  15288. // int max_code; /* and its largest code of non zero frequency */
  15289. {
  15290. var n; /* iterates over all tree elements */
  15291. var prevlen = -1; /* last emitted length */
  15292. var curlen; /* length of current code */
  15293. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  15294. var count = 0; /* repeat count of the current code */
  15295. var max_count = 7; /* max repeat count */
  15296. var min_count = 4; /* min repeat count */
  15297. if (nextlen === 0) {
  15298. max_count = 138;
  15299. min_count = 3;
  15300. }
  15301. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  15302. for (n = 0; n <= max_code; n++) {
  15303. curlen = nextlen;
  15304. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  15305. if (++count < max_count && curlen === nextlen) {
  15306. continue;
  15307. } else if (count < min_count) {
  15308. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  15309. } else if (curlen !== 0) {
  15310. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  15311. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  15312. } else if (count <= 10) {
  15313. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  15314. } else {
  15315. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  15316. }
  15317. count = 0;
  15318. prevlen = curlen;
  15319. if (nextlen === 0) {
  15320. max_count = 138;
  15321. min_count = 3;
  15322. } else if (curlen === nextlen) {
  15323. max_count = 6;
  15324. min_count = 3;
  15325. } else {
  15326. max_count = 7;
  15327. min_count = 4;
  15328. }
  15329. }
  15330. }
  15331. /* ===========================================================================
  15332. * Send a literal or distance tree in compressed form, using the codes in
  15333. * bl_tree.
  15334. */
  15335. function send_tree(s, tree, max_code)
  15336. // deflate_state *s;
  15337. // ct_data *tree; /* the tree to be scanned */
  15338. // int max_code; /* and its largest code of non zero frequency */
  15339. {
  15340. var n; /* iterates over all tree elements */
  15341. var prevlen = -1; /* last emitted length */
  15342. var curlen; /* length of current code */
  15343. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  15344. var count = 0; /* repeat count of the current code */
  15345. var max_count = 7; /* max repeat count */
  15346. var min_count = 4; /* min repeat count */
  15347. /* tree[max_code+1].Len = -1; */ /* guard already set */
  15348. if (nextlen === 0) {
  15349. max_count = 138;
  15350. min_count = 3;
  15351. }
  15352. for (n = 0; n <= max_code; n++) {
  15353. curlen = nextlen;
  15354. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  15355. if (++count < max_count && curlen === nextlen) {
  15356. continue;
  15357. } else if (count < min_count) {
  15358. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  15359. } else if (curlen !== 0) {
  15360. if (curlen !== prevlen) {
  15361. send_code(s, curlen, s.bl_tree);
  15362. count--;
  15363. }
  15364. //Assert(count >= 3 && count <= 6, " 3_6?");
  15365. send_code(s, REP_3_6, s.bl_tree);
  15366. send_bits(s, count-3, 2);
  15367. } else if (count <= 10) {
  15368. send_code(s, REPZ_3_10, s.bl_tree);
  15369. send_bits(s, count-3, 3);
  15370. } else {
  15371. send_code(s, REPZ_11_138, s.bl_tree);
  15372. send_bits(s, count-11, 7);
  15373. }
  15374. count = 0;
  15375. prevlen = curlen;
  15376. if (nextlen === 0) {
  15377. max_count = 138;
  15378. min_count = 3;
  15379. } else if (curlen === nextlen) {
  15380. max_count = 6;
  15381. min_count = 3;
  15382. } else {
  15383. max_count = 7;
  15384. min_count = 4;
  15385. }
  15386. }
  15387. }
  15388. /* ===========================================================================
  15389. * Construct the Huffman tree for the bit lengths and return the index in
  15390. * bl_order of the last bit length code to send.
  15391. */
  15392. function build_bl_tree(s) {
  15393. var max_blindex; /* index of last bit length code of non zero freq */
  15394. /* Determine the bit length frequencies for literal and distance trees */
  15395. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  15396. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  15397. /* Build the bit length tree: */
  15398. build_tree(s, s.bl_desc);
  15399. /* opt_len now includes the length of the tree representations, except
  15400. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  15401. */
  15402. /* Determine the number of bit length codes to send. The pkzip format
  15403. * requires that at least 4 bit length codes be sent. (appnote.txt says
  15404. * 3 but the actual value used is 4.)
  15405. */
  15406. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  15407. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  15408. break;
  15409. }
  15410. }
  15411. /* Update opt_len to include the bit length tree and counts */
  15412. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  15413. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  15414. // s->opt_len, s->static_len));
  15415. return max_blindex;
  15416. }
  15417. /* ===========================================================================
  15418. * Send the header for a block using dynamic Huffman trees: the counts, the
  15419. * lengths of the bit length codes, the literal tree and the distance tree.
  15420. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  15421. */
  15422. function send_all_trees(s, lcodes, dcodes, blcodes)
  15423. // deflate_state *s;
  15424. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  15425. {
  15426. var rank; /* index in bl_order */
  15427. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  15428. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  15429. // "too many codes");
  15430. //Tracev((stderr, "\nbl counts: "));
  15431. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  15432. send_bits(s, dcodes-1, 5);
  15433. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  15434. for (rank = 0; rank < blcodes; rank++) {
  15435. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  15436. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  15437. }
  15438. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  15439. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  15440. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  15441. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  15442. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  15443. }
  15444. /* ===========================================================================
  15445. * Check if the data type is TEXT or BINARY, using the following algorithm:
  15446. * - TEXT if the two conditions below are satisfied:
  15447. * a) There are no non-portable control characters belonging to the
  15448. * "black list" (0..6, 14..25, 28..31).
  15449. * b) There is at least one printable character belonging to the
  15450. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  15451. * - BINARY otherwise.
  15452. * - The following partially-portable control characters form a
  15453. * "gray list" that is ignored in this detection algorithm:
  15454. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  15455. * IN assertion: the fields Freq of dyn_ltree are set.
  15456. */
  15457. function detect_data_type(s) {
  15458. /* black_mask is the bit mask of black-listed bytes
  15459. * set bits 0..6, 14..25, and 28..31
  15460. * 0xf3ffc07f = binary 11110011111111111100000001111111
  15461. */
  15462. var black_mask = 0xf3ffc07f;
  15463. var n;
  15464. /* Check for non-textual ("black-listed") bytes. */
  15465. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  15466. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  15467. return Z_BINARY;
  15468. }
  15469. }
  15470. /* Check for textual ("white-listed") bytes. */
  15471. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  15472. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  15473. return Z_TEXT;
  15474. }
  15475. for (n = 32; n < LITERALS; n++) {
  15476. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  15477. return Z_TEXT;
  15478. }
  15479. }
  15480. /* There are no "black-listed" or "white-listed" bytes:
  15481. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  15482. */
  15483. return Z_BINARY;
  15484. }
  15485. var static_init_done = false;
  15486. /* ===========================================================================
  15487. * Initialize the tree data structures for a new zlib stream.
  15488. */
  15489. function _tr_init(s)
  15490. {
  15491. if (!static_init_done) {
  15492. tr_static_init();
  15493. static_init_done = true;
  15494. }
  15495. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  15496. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  15497. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  15498. s.bi_buf = 0;
  15499. s.bi_valid = 0;
  15500. /* Initialize the first block of the first file: */
  15501. init_block(s);
  15502. }
  15503. /* ===========================================================================
  15504. * Send a stored block
  15505. */
  15506. function _tr_stored_block(s, buf, stored_len, last)
  15507. //DeflateState *s;
  15508. //charf *buf; /* input block */
  15509. //ulg stored_len; /* length of input block */
  15510. //int last; /* one if this is the last block for a file */
  15511. {
  15512. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  15513. copy_block(s, buf, stored_len, true); /* with header */
  15514. }
  15515. /* ===========================================================================
  15516. * Send one empty static block to give enough lookahead for inflate.
  15517. * This takes 10 bits, of which 7 may remain in the bit buffer.
  15518. */
  15519. function _tr_align(s) {
  15520. send_bits(s, STATIC_TREES<<1, 3);
  15521. send_code(s, END_BLOCK, static_ltree);
  15522. bi_flush(s);
  15523. }
  15524. /* ===========================================================================
  15525. * Determine the best encoding for the current block: dynamic trees, static
  15526. * trees or store, and output the encoded block to the zip file.
  15527. */
  15528. function _tr_flush_block(s, buf, stored_len, last)
  15529. //DeflateState *s;
  15530. //charf *buf; /* input block, or NULL if too old */
  15531. //ulg stored_len; /* length of input block */
  15532. //int last; /* one if this is the last block for a file */
  15533. {
  15534. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  15535. var max_blindex = 0; /* index of last bit length code of non zero freq */
  15536. /* Build the Huffman trees unless a stored block is forced */
  15537. if (s.level > 0) {
  15538. /* Check if the file is binary or text */
  15539. if (s.strm.data_type === Z_UNKNOWN) {
  15540. s.strm.data_type = detect_data_type(s);
  15541. }
  15542. /* Construct the literal and distance trees */
  15543. build_tree(s, s.l_desc);
  15544. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  15545. // s->static_len));
  15546. build_tree(s, s.d_desc);
  15547. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  15548. // s->static_len));
  15549. /* At this point, opt_len and static_len are the total bit lengths of
  15550. * the compressed block data, excluding the tree representations.
  15551. */
  15552. /* Build the bit length tree for the above two trees, and get the index
  15553. * in bl_order of the last bit length code to send.
  15554. */
  15555. max_blindex = build_bl_tree(s);
  15556. /* Determine the best encoding. Compute the block lengths in bytes. */
  15557. opt_lenb = (s.opt_len+3+7) >>> 3;
  15558. static_lenb = (s.static_len+3+7) >>> 3;
  15559. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  15560. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  15561. // s->last_lit));
  15562. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  15563. } else {
  15564. // Assert(buf != (char*)0, "lost buf");
  15565. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  15566. }
  15567. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  15568. /* 4: two words for the lengths */
  15569. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  15570. * Otherwise we can't have processed more than WSIZE input bytes since
  15571. * the last block flush, because compression would have been
  15572. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  15573. * transform a block into a stored block.
  15574. */
  15575. _tr_stored_block(s, buf, stored_len, last);
  15576. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  15577. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  15578. compress_block(s, static_ltree, static_dtree);
  15579. } else {
  15580. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  15581. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  15582. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  15583. }
  15584. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  15585. /* The above check is made mod 2^32, for files larger than 512 MB
  15586. * and uLong implemented on 32 bits.
  15587. */
  15588. init_block(s);
  15589. if (last) {
  15590. bi_windup(s);
  15591. }
  15592. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  15593. // s->compressed_len-7*last));
  15594. }
  15595. /* ===========================================================================
  15596. * Save the match info and tally the frequency counts. Return true if
  15597. * the current block must be flushed.
  15598. */
  15599. function _tr_tally(s, dist, lc)
  15600. // deflate_state *s;
  15601. // unsigned dist; /* distance of matched string */
  15602. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  15603. {
  15604. //var out_length, in_length, dcode;
  15605. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  15606. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  15607. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  15608. s.last_lit++;
  15609. if (dist === 0) {
  15610. /* lc is the unmatched char */
  15611. s.dyn_ltree[lc*2]/*.Freq*/++;
  15612. } else {
  15613. s.matches++;
  15614. /* Here, lc is the match length - MIN_MATCH */
  15615. dist--; /* dist = match distance - 1 */
  15616. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  15617. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  15618. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  15619. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  15620. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  15621. }
  15622. // (!) This block is disabled in zlib defailts,
  15623. // don't enable it for binary compatibility
  15624. //#ifdef TRUNCATE_BLOCK
  15625. // /* Try to guess if it is profitable to stop the current block here */
  15626. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  15627. // /* Compute an upper bound for the compressed length */
  15628. // out_length = s.last_lit*8;
  15629. // in_length = s.strstart - s.block_start;
  15630. //
  15631. // for (dcode = 0; dcode < D_CODES; dcode++) {
  15632. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  15633. // }
  15634. // out_length >>>= 3;
  15635. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  15636. // // s->last_lit, in_length, out_length,
  15637. // // 100L - out_length*100L/in_length));
  15638. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  15639. // return true;
  15640. // }
  15641. // }
  15642. //#endif
  15643. return (s.last_lit === s.lit_bufsize-1);
  15644. /* We avoid equality with lit_bufsize because of wraparound at 64K
  15645. * on 16 bit machines and because stored blocks are restricted to
  15646. * 64K-1 bytes.
  15647. */
  15648. }
  15649. exports._tr_init = _tr_init;
  15650. exports._tr_stored_block = _tr_stored_block;
  15651. exports._tr_flush_block = _tr_flush_block;
  15652. exports._tr_tally = _tr_tally;
  15653. exports._tr_align = _tr_align;
  15654. },{"../utils/common":39}],51:[function(require,module,exports){
  15655. 'use strict';
  15656. function ZStream() {
  15657. /* next input byte */
  15658. this.input = null; // JS specific, because we have no pointers
  15659. this.next_in = 0;
  15660. /* number of bytes available at input */
  15661. this.avail_in = 0;
  15662. /* total number of input bytes read so far */
  15663. this.total_in = 0;
  15664. /* next output byte should be put there */
  15665. this.output = null; // JS specific, because we have no pointers
  15666. this.next_out = 0;
  15667. /* remaining free space at output */
  15668. this.avail_out = 0;
  15669. /* total number of bytes output so far */
  15670. this.total_out = 0;
  15671. /* last error message, NULL if no error */
  15672. this.msg = ''/*Z_NULL*/;
  15673. /* not visible by applications */
  15674. this.state = null;
  15675. /* best guess about the data type: binary or text */
  15676. this.data_type = 2/*Z_UNKNOWN*/;
  15677. /* adler32 value of the uncompressed data */
  15678. this.adler = 0;
  15679. }
  15680. module.exports = ZStream;
  15681. },{}],52:[function(require,module,exports){
  15682. module.exports = function arrayEquals(array) {
  15683. // if the other array is a falsy value, return
  15684. if (!array)
  15685. return false;
  15686. // compare lengths - can save a lot of time
  15687. if (this.length != array.length)
  15688. return false;
  15689. for (var i = 0, l = this.length; i < l; i++) {
  15690. // Check if we have nested arrays
  15691. if (this[i] instanceof Array && array[i] instanceof Array) {
  15692. // recurse into the nested arrays
  15693. if (!arrayEquals.apply(this[i], [array[i]]))
  15694. return false;
  15695. } else if (this[i] != array[i]) {
  15696. // Warning - two different object instances will never be equal:
  15697. // {x:20} != {x:20}
  15698. return false;
  15699. }
  15700. }
  15701. return true;
  15702. }
  15703. },{}],53:[function(require,module,exports){
  15704. exports.Interop = require('./interop');
  15705. },{"./interop":54}],54:[function(require,module,exports){
  15706. "use strict";
  15707. var transform = require('./transform');
  15708. var arrayEquals = require('./array-equals');
  15709. function Interop() {
  15710. /**
  15711. * This map holds the most recent Unified Plan offer/answer SDP that was
  15712. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  15713. * the SDP string as values.
  15714. *
  15715. * @type {{}}
  15716. */
  15717. this.cache = {};
  15718. }
  15719. module.exports = Interop;
  15720. /**
  15721. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  15722. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  15723. * application.
  15724. *
  15725. * @param desc
  15726. * @returns {*}
  15727. */
  15728. Interop.prototype.toPlanB = function(desc) {
  15729. //#region Preliminary input validation.
  15730. if (typeof desc !== 'object' || desc === null ||
  15731. typeof desc.sdp !== 'string') {
  15732. console.warn('An empty description was passed as an argument.');
  15733. return desc;
  15734. }
  15735. // Objectify the SDP for easier manipulation.
  15736. var session = transform.parse(desc.sdp);
  15737. // If the SDP contains no media, there's nothing to transform.
  15738. if (typeof session.media === 'undefined' ||
  15739. !Array.isArray(session.media) || session.media.length === 0) {
  15740. console.warn('The description has no media.');
  15741. return desc;
  15742. }
  15743. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  15744. // SDP has a video, an audio and a data "channel" at most.
  15745. if (session.media.length <= 3 && session.media.every(function(m) {
  15746. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  15747. })) {
  15748. console.warn('This description does not look like Unified Plan.');
  15749. return desc;
  15750. }
  15751. //#endregion
  15752. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  15753. // -> Unified Plan transformation.
  15754. this.cache[desc.type] = desc.sdp;
  15755. //#region Convert from Unified Plan to Plan B.
  15756. // We rebuild the session.media array.
  15757. var media = session.media;
  15758. session.media = [];
  15759. // Associative array that maps channel types to channel objects for fast
  15760. // access to channel objects by their type, e.g. type2bl['audio']->channel
  15761. // obj.
  15762. var type2bl = {};
  15763. // Used to build the group:BUNDLE value after the channels construction
  15764. // loop.
  15765. var types = [];
  15766. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  15767. media.forEach(function(unifiedLine) {
  15768. // rtcp-mux is required in the Plan B SDP.
  15769. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  15770. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  15771. unifiedLine.direction !== 'inactive') {
  15772. throw new Error('Cannot convert to Plan B because m-lines ' +
  15773. 'without the rtcp-mux attribute were found.');
  15774. }
  15775. if (unifiedLine.type === 'application') {
  15776. session.media.push(unifiedLine);
  15777. types.push(unifiedLine.mid);
  15778. return;
  15779. }
  15780. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  15781. // as the channel basis.
  15782. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  15783. type2bl[unifiedLine.type] = unifiedLine;
  15784. }
  15785. // Add sources to the channel and handle a=msid.
  15786. if (typeof unifiedLine.sources === 'object') {
  15787. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  15788. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  15789. type2bl[unifiedLine.type].sources = {};
  15790. // Assign the sources to the channel.
  15791. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  15792. if (typeof unifiedLine.msid !== 'undefined') {
  15793. // In Plan B the msid is an SSRC attribute. Also, we don't
  15794. // care about the obsolete label and mslabel attributes.
  15795. //
  15796. // Note that it is not guaranteed that the unifiedLine will have
  15797. // an msid. recvonly channels in particular don't have one.
  15798. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  15799. }
  15800. // NOTE ssrcs in ssrc groups will share msids, as
  15801. // draft-uberti-rtcweb-plan-00 mandates.
  15802. });
  15803. }
  15804. // Add ssrc groups to the channel.
  15805. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  15806. Array.isArray(unifiedLine.ssrcGroups)) {
  15807. // Create the ssrcGroups array, if it's not defined.
  15808. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  15809. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  15810. type2bl[unifiedLine.type].ssrcGroups = [];
  15811. }
  15812. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  15813. }
  15814. if (type2bl[unifiedLine.type] === unifiedLine) {
  15815. // Copy ICE related stuff from the principal media line.
  15816. unifiedLine.candidates = media[0].candidates;
  15817. unifiedLine.iceUfrag = media[0].iceUfrag;
  15818. unifiedLine.icePwd = media[0].icePwd;
  15819. unifiedLine.fingerprint = media[0].fingerprint;
  15820. // Plan B mids are in ['audio', 'video', 'data']
  15821. unifiedLine.mid = unifiedLine.type;
  15822. // Plan B doesn't support/need the bundle-only attribute.
  15823. delete unifiedLine.bundleOnly;
  15824. // In Plan B the msid is an SSRC attribute.
  15825. delete unifiedLine.msid;
  15826. // Used to build the group:BUNDLE value after this loop.
  15827. types.push(unifiedLine.type);
  15828. // Add the channel to the new media array.
  15829. session.media.push(unifiedLine);
  15830. }
  15831. });
  15832. // We regenerate the BUNDLE group with the new mids.
  15833. session.groups.some(function(group) {
  15834. if (group.type === 'BUNDLE') {
  15835. group.mids = types.join(' ');
  15836. return true;
  15837. }
  15838. });
  15839. // msid semantic
  15840. session.msidSemantic = {
  15841. semantic: 'WMS',
  15842. token: '*'
  15843. };
  15844. var resStr = transform.write(session);
  15845. return new RTCSessionDescription({
  15846. type: desc.type,
  15847. sdp: resStr
  15848. });
  15849. //#endregion
  15850. };
  15851. /**
  15852. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  15853. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  15854. * to FF.
  15855. *
  15856. * @param desc
  15857. * @returns {*}
  15858. */
  15859. Interop.prototype.toUnifiedPlan = function(desc) {
  15860. //#region Preliminary input validation.
  15861. if (typeof desc !== 'object' || desc === null ||
  15862. typeof desc.sdp !== 'string') {
  15863. console.warn('An empty description was passed as an argument.');
  15864. return desc;
  15865. }
  15866. var session = transform.parse(desc.sdp);
  15867. // If the SDP contains no media, there's nothing to transform.
  15868. if (typeof session.media === 'undefined' ||
  15869. !Array.isArray(session.media) || session.media.length === 0) {
  15870. console.warn('The description has no media.');
  15871. return desc;
  15872. }
  15873. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  15874. // a video, an audio and a data "channel" at most.
  15875. if (session.media.length > 3 || !session.media.every(function(m) {
  15876. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  15877. })) {
  15878. console.warn('This description does not look like Plan B.');
  15879. return desc;
  15880. }
  15881. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  15882. var mids = [];
  15883. session.media.forEach(function(m) {
  15884. mids.push(m.mid);
  15885. });
  15886. var hasBundle = false;
  15887. if (typeof session.groups !== 'undefined' &&
  15888. Array.isArray(session.groups)) {
  15889. hasBundle = session.groups.every(function(g) {
  15890. return g.type !== 'BUNDLE' ||
  15891. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  15892. });
  15893. }
  15894. if (!hasBundle) {
  15895. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  15896. " are not bundled were found.");
  15897. }
  15898. //#endregion
  15899. //#region Convert from Plan B to Unified Plan.
  15900. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  15901. // rebuild an equivalent Unified Plan offer/answer.
  15902. //
  15903. // For example, if this is a local answer (in Unified Plan style) that we
  15904. // convert to Plan B prior to handing it over to the application (the
  15905. // PeerConnection wrapper called us, for instance, after a successful
  15906. // createAnswer), we want to remember the m-line at which we've seen the
  15907. // (local) SSRC. That's because when the application wants to do call the
  15908. // SLD method, forcing us to do the inverse transformation (from Plan B to
  15909. // Unified Plan), we need to know to which m-line to assign the (local)
  15910. // SSRC. We also need to know all the other m-lines that the original
  15911. // answer had and include them in the transformed answer as well.
  15912. //
  15913. // Another example is if this is a remote offer that we convert to Plan B
  15914. // prior to giving it to the application, we want to remember the mid at
  15915. // which we've seen the (remote) SSRC.
  15916. //
  15917. // In the iteration that follows, we use the cached Unified Plan (if it
  15918. // exists) to assign mids to ssrcs.
  15919. var cached;
  15920. if (typeof this.cache[desc.type] !== 'undefined') {
  15921. cached = transform.parse(this.cache[desc.type]);
  15922. }
  15923. // A helper map that sends mids to m-line objects. We use it later to
  15924. // rebuild the Unified Plan style session.media array.
  15925. var mid2ul = {};
  15926. session.media.forEach(function(bLine) {
  15927. if ((typeof bLine.rtcpMux !== 'string' ||
  15928. bLine.rtcpMux !== 'rtcp-mux') &&
  15929. bLine.direction !== 'inactive') {
  15930. throw new Error("Cannot convert to Unified Plan because m-lines " +
  15931. "without the rtcp-mux attribute were found.");
  15932. }
  15933. if (bLine.type === 'application') {
  15934. mid2ul[bLine.mid] = bLine;
  15935. return;
  15936. }
  15937. // With rtcp-mux and bundle all the channels should have the same ICE
  15938. // stuff.
  15939. var sources = bLine.sources;
  15940. var ssrcGroups = bLine.ssrcGroups;
  15941. var candidates = bLine.candidates;
  15942. var iceUfrag = bLine.iceUfrag;
  15943. var icePwd = bLine.icePwd;
  15944. var fingerprint = bLine.fingerprint;
  15945. var port = bLine.port;
  15946. // We'll use the "bLine" object as a prototype for each new "mLine"
  15947. // that we create, but first we need to clean it up a bit.
  15948. delete bLine.sources;
  15949. delete bLine.ssrcGroups;
  15950. delete bLine.candidates;
  15951. delete bLine.iceUfrag;
  15952. delete bLine.icePwd;
  15953. delete bLine.fingerprint;
  15954. delete bLine.port;
  15955. delete bLine.mid;
  15956. // inverted ssrc group map
  15957. var ssrc2group = {};
  15958. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  15959. ssrcGroups.forEach(function (ssrcGroup) {
  15960. // TODO(gp) find out how to receive simulcast with FF. For the
  15961. // time being, hide it.
  15962. if (ssrcGroup.semantics === 'SIM') {
  15963. return;
  15964. }
  15965. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  15966. Array.isArray(ssrcGroup.ssrcs)) {
  15967. ssrcGroup.ssrcs.forEach(function (ssrc) {
  15968. if (typeof ssrc2group[ssrc] === 'undefined') {
  15969. ssrc2group[ssrc] = [];
  15970. }
  15971. ssrc2group[ssrc].push(ssrcGroup);
  15972. });
  15973. }
  15974. });
  15975. }
  15976. // ssrc to m-line index.
  15977. var ssrc2ml = {};
  15978. if (typeof sources === 'object') {
  15979. // Explode the Plan B channel sources with one m-line per source.
  15980. Object.keys(sources).forEach(function(ssrc) {
  15981. // The (unified) m-line for this SSRC. We either create it from
  15982. // scratch or, if it's a grouped SSRC, we re-use a related
  15983. // mline. In other words, if the source is grouped with another
  15984. // source, put the two together in the same m-line.
  15985. var unifiedLine;
  15986. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  15987. Array.isArray(ssrc2group[ssrc])) {
  15988. ssrc2group[ssrc].some(function (ssrcGroup) {
  15989. // ssrcGroup.ssrcs *is* an Array, no need to check
  15990. // again here.
  15991. return ssrcGroup.ssrcs.some(function (related) {
  15992. if (typeof ssrc2ml[related] === 'object') {
  15993. unifiedLine = ssrc2ml[related];
  15994. return true;
  15995. }
  15996. });
  15997. });
  15998. }
  15999. if (typeof unifiedLine === 'object') {
  16000. // the m-line already exists. Just add the source.
  16001. unifiedLine.sources[ssrc] = sources[ssrc];
  16002. delete sources[ssrc].msid;
  16003. } else {
  16004. // Use the "bLine" as a prototype for the "unifiedLine".
  16005. unifiedLine = Object.create(bLine);
  16006. ssrc2ml[ssrc] = unifiedLine;
  16007. if (typeof sources[ssrc].msid !== 'undefined') {
  16008. // Assign the msid of the source to the m-line. Note
  16009. // that it is not guaranteed that the source will have
  16010. // msid. In particular "recvonly" sources don't have an
  16011. // msid. Note that "recvonly" is a term only defined
  16012. // for m-lines.
  16013. unifiedLine.msid = sources[ssrc].msid;
  16014. delete sources[ssrc].msid;
  16015. }
  16016. // We assign one SSRC per media line.
  16017. unifiedLine.sources = {};
  16018. unifiedLine.sources[ssrc] = sources[ssrc];
  16019. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  16020. // Use the cached Unified Plan SDP (if it exists) to assign
  16021. // SSRCs to mids.
  16022. if (typeof cached !== 'undefined' &&
  16023. typeof cached.media !== 'undefined' &&
  16024. Array.isArray(cached.media)) {
  16025. cached.media.forEach(function (m) {
  16026. if (typeof m.sources === 'object') {
  16027. Object.keys(m.sources).forEach(function (s) {
  16028. if (s === ssrc) {
  16029. unifiedLine.mid = m.mid;
  16030. }
  16031. });
  16032. }
  16033. });
  16034. }
  16035. if (typeof unifiedLine.mid === 'undefined') {
  16036. // If this is an SSRC that we see for the first time
  16037. // assign it a new mid. This is typically the case when
  16038. // this method is called to transform a remote
  16039. // description for the first time or when there is a
  16040. // new SSRC in the remote description because a new
  16041. // peer has joined the conference. Local SSRCs should
  16042. // have already been added to the map in the toPlanB
  16043. // method.
  16044. //
  16045. // Because FF generates answers in Unified Plan style,
  16046. // we MUST already have a cached answer with all the
  16047. // local SSRCs mapped to some m-line/mid.
  16048. if (desc.type === 'answer') {
  16049. throw new Error("An unmapped SSRC was found.");
  16050. }
  16051. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  16052. }
  16053. // Include the candidates in the 1st media line.
  16054. unifiedLine.candidates = candidates;
  16055. unifiedLine.iceUfrag = iceUfrag;
  16056. unifiedLine.icePwd = icePwd;
  16057. unifiedLine.fingerprint = fingerprint;
  16058. unifiedLine.port = port;
  16059. mid2ul[unifiedLine.mid] = unifiedLine;
  16060. }
  16061. });
  16062. }
  16063. });
  16064. // Rebuild the media array in the right order and add the missing mLines
  16065. // (missing from the Plan B SDP).
  16066. session.media = [];
  16067. mids = []; // reuse
  16068. if (desc.type === 'answer') {
  16069. // The media lines in the answer must match the media lines in the
  16070. // offer. The order is important too. Here we assume that Firefox is the
  16071. // answerer, so we merely have to use the reconstructed (unified) answer
  16072. // to update the cached (unified) answer accordingly.
  16073. //
  16074. // In the general case, one would have to use the cached (unified) offer
  16075. // to find the m-lines that are missing from the reconstructed answer,
  16076. // potentially grabbing them from the cached (unified) answer. One has
  16077. // to be carefull with this approach because inactive m-lines do not
  16078. // always have an mid, making it tricky (impossible?) to find where
  16079. // exactly and which m-lines are missing from the reconstructed answer.
  16080. for (var i = 0; i < cached.media.length; i++) {
  16081. var unifiedLine = cached.media[i];
  16082. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  16083. // The mid isn't in the reconstructed (unified) answer.
  16084. // This is either a (unified) m-line containing a remote
  16085. // track only, or a (unified) m-line containing a remote
  16086. // track and a local track that has been removed.
  16087. // In either case, it MUST exist in the cached
  16088. // (unified) answer.
  16089. //
  16090. // In case this is a removed local track, clean-up
  16091. // the (unified) m-line and make sure it's 'recvonly' or
  16092. // 'inactive'.
  16093. delete unifiedLine.msid;
  16094. delete unifiedLine.sources;
  16095. delete unifiedLine.ssrcGroups;
  16096. if (!unifiedLine.direction
  16097. || unifiedLine.direction === 'sendrecv')
  16098. unifiedLine.direction = 'recvonly';
  16099. if (!unifiedLine.direction
  16100. || unifiedLine.direction === 'sendonly')
  16101. unifiedLine.direction = 'inactive';
  16102. } else {
  16103. // This is an (unified) m-line/channel that contains a local
  16104. // track (sendrecv or sendonly channel) or it's a unified
  16105. // recvonly m-line/channel. In either case, since we're
  16106. // going from PlanB -> Unified Plan this m-line MUST
  16107. // exist in the cached answer.
  16108. }
  16109. session.media.push(unifiedLine);
  16110. if (typeof unifiedLine.mid === 'string') {
  16111. // inactive lines don't/may not have an mid.
  16112. mids.push(unifiedLine.mid);
  16113. }
  16114. }
  16115. } else {
  16116. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  16117. // under any circumstances. If we are no longer interested in sending a
  16118. // track, we just remove the msid and ssrc attributes and set it to
  16119. // either a=recvonly (as the reofferer, we must use recvonly if the
  16120. // other side was previously sending on the m-section, but we can also
  16121. // leave the possibility open if it wasn't previously in use), or
  16122. // a=inacive.
  16123. if (typeof cached !== 'undefined' &&
  16124. typeof cached.media !== 'undefined' &&
  16125. Array.isArray(cached.media)) {
  16126. cached.media.forEach(function(unifiedLine) {
  16127. mids.push(unifiedLine.mid);
  16128. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  16129. session.media.push(mid2ul[unifiedLine.mid]);
  16130. } else {
  16131. delete unifiedLine.msid;
  16132. delete unifiedLine.sources;
  16133. delete unifiedLine.ssrcGroups;
  16134. if (!unifiedLine.direction
  16135. || unifiedLine.direction === 'sendrecv')
  16136. unifiedLine.direction = 'recvonly';
  16137. if (!unifiedLine.direction
  16138. || unifiedLine.direction === 'sendonly')
  16139. unifiedLine.direction = 'inactive';
  16140. session.media.push(unifiedLine);
  16141. }
  16142. });
  16143. }
  16144. // Add all the remaining (new) m-lines of the transformed SDP.
  16145. Object.keys(mid2ul).forEach(function(mid) {
  16146. if (mids.indexOf(mid) === -1) {
  16147. mids.push(mid);
  16148. if (typeof mid2ul[mid].direction === 'recvonly') {
  16149. // This is a remote recvonly channel. Add its SSRC to the
  16150. // appropriate sendrecv or sendonly channel.
  16151. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  16152. session.media.some(function (unifiedLine) {
  16153. if ((unifiedLine.direction === 'sendrecv' ||
  16154. unifiedLine.direction === 'sendonly') &&
  16155. unifiedLine.type === mid2ul[mid].type) {
  16156. // mid2ul[mid] shouldn't have any ssrc-groups
  16157. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  16158. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  16159. });
  16160. return true;
  16161. }
  16162. });
  16163. } else {
  16164. session.media.push(mid2ul[mid]);
  16165. }
  16166. }
  16167. });
  16168. }
  16169. // We regenerate the BUNDLE group (since we regenerated the mids)
  16170. session.groups.some(function(group) {
  16171. if (group.type === 'BUNDLE') {
  16172. group.mids = mids.join(' ');
  16173. return true;
  16174. }
  16175. });
  16176. // msid semantic
  16177. session.msidSemantic = {
  16178. semantic: 'WMS',
  16179. token: '*'
  16180. };
  16181. var resStr = transform.write(session);
  16182. // Cache the transformed SDP (Unified Plan) for later re-use in this
  16183. // function.
  16184. this.cache[desc.type] = resStr;
  16185. return new RTCSessionDescription({
  16186. type: desc.type,
  16187. sdp: resStr
  16188. });
  16189. //#endregion
  16190. };
  16191. },{"./array-equals":52,"./transform":55}],55:[function(require,module,exports){
  16192. var transform = require('sdp-transform');
  16193. exports.write = function(session, opts) {
  16194. if (typeof session !== 'undefined' &&
  16195. typeof session.media !== 'undefined' &&
  16196. Array.isArray(session.media)) {
  16197. session.media.forEach(function (mLine) {
  16198. // expand sources to ssrcs
  16199. if (typeof mLine.sources !== 'undefined' &&
  16200. Object.keys(mLine.sources).length !== 0) {
  16201. mLine.ssrcs = [];
  16202. Object.keys(mLine.sources).forEach(function (ssrc) {
  16203. var source = mLine.sources[ssrc];
  16204. Object.keys(source).forEach(function (attribute) {
  16205. mLine.ssrcs.push({
  16206. id: ssrc,
  16207. attribute: attribute,
  16208. value: source[attribute]
  16209. });
  16210. });
  16211. });
  16212. delete mLine.sources;
  16213. }
  16214. // join ssrcs in ssrc groups
  16215. if (typeof mLine.ssrcGroups !== 'undefined' &&
  16216. Array.isArray(mLine.ssrcGroups)) {
  16217. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  16218. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  16219. Array.isArray(ssrcGroup.ssrcs)) {
  16220. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  16221. }
  16222. });
  16223. }
  16224. });
  16225. }
  16226. // join group mids
  16227. if (typeof session !== 'undefined' &&
  16228. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  16229. session.groups.forEach(function (g) {
  16230. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  16231. g.mids = g.mids.join(' ');
  16232. }
  16233. });
  16234. }
  16235. return transform.write(session, opts);
  16236. };
  16237. exports.parse = function(sdp) {
  16238. var session = transform.parse(sdp);
  16239. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  16240. Array.isArray(session.media)) {
  16241. session.media.forEach(function (mLine) {
  16242. // group sources attributes by ssrc
  16243. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  16244. mLine.sources = {};
  16245. mLine.ssrcs.forEach(function (ssrc) {
  16246. if (!mLine.sources[ssrc.id])
  16247. mLine.sources[ssrc.id] = {};
  16248. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  16249. });
  16250. delete mLine.ssrcs;
  16251. }
  16252. // split ssrcs in ssrc groups
  16253. if (typeof mLine.ssrcGroups !== 'undefined' &&
  16254. Array.isArray(mLine.ssrcGroups)) {
  16255. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  16256. if (typeof ssrcGroup.ssrcs === 'string') {
  16257. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  16258. }
  16259. });
  16260. }
  16261. });
  16262. }
  16263. // split group mids
  16264. if (typeof session !== 'undefined' &&
  16265. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  16266. session.groups.forEach(function (g) {
  16267. if (typeof g.mids === 'string') {
  16268. g.mids = g.mids.split(' ');
  16269. }
  16270. });
  16271. }
  16272. return session;
  16273. };
  16274. },{"sdp-transform":57}],56:[function(require,module,exports){
  16275. var grammar = module.exports = {
  16276. v: [{
  16277. name: 'version',
  16278. reg: /^(\d*)$/
  16279. }],
  16280. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  16281. // NB: sessionId will be a String in most cases because it is huge
  16282. name: 'origin',
  16283. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  16284. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  16285. format: "%s %s %d %s IP%d %s"
  16286. }],
  16287. // default parsing of these only (though some of these feel outdated)
  16288. s: [{ name: 'name' }],
  16289. i: [{ name: 'description' }],
  16290. u: [{ name: 'uri' }],
  16291. e: [{ name: 'email' }],
  16292. p: [{ name: 'phone' }],
  16293. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  16294. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  16295. //k: [{}], // outdated thing ignored
  16296. t: [{ //t=0 0
  16297. name: 'timing',
  16298. reg: /^(\d*) (\d*)/,
  16299. names: ['start', 'stop'],
  16300. format: "%d %d"
  16301. }],
  16302. c: [{ //c=IN IP4 10.47.197.26
  16303. name: 'connection',
  16304. reg: /^IN IP(\d) (\S*)/,
  16305. names: ['version', 'ip'],
  16306. format: "IN IP%d %s"
  16307. }],
  16308. b: [{ //b=AS:4000
  16309. push: 'bandwidth',
  16310. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  16311. names: ['type', 'limit'],
  16312. format: "%s:%s"
  16313. }],
  16314. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  16315. // NB: special - pushes to session
  16316. // TODO: rtp/fmtp should be filtered by the payloads found here?
  16317. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  16318. names: ['type', 'port', 'protocol', 'payloads'],
  16319. format: "%s %d %s %s"
  16320. }],
  16321. a: [
  16322. { //a=rtpmap:110 opus/48000/2
  16323. push: 'rtp',
  16324. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  16325. names: ['payload', 'codec', 'rate', 'encoding'],
  16326. format: function (o) {
  16327. return (o.encoding) ?
  16328. "rtpmap:%d %s/%s/%s":
  16329. "rtpmap:%d %s/%s";
  16330. }
  16331. },
  16332. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  16333. push: 'fmtp',
  16334. reg: /^fmtp:(\d*) (\S*)/,
  16335. names: ['payload', 'config'],
  16336. format: "fmtp:%d %s"
  16337. },
  16338. { //a=control:streamid=0
  16339. name: 'control',
  16340. reg: /^control:(.*)/,
  16341. format: "control:%s"
  16342. },
  16343. { //a=rtcp:65179 IN IP4 193.84.77.194
  16344. name: 'rtcp',
  16345. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  16346. names: ['port', 'netType', 'ipVer', 'address'],
  16347. format: function (o) {
  16348. return (o.address != null) ?
  16349. "rtcp:%d %s IP%d %s":
  16350. "rtcp:%d";
  16351. }
  16352. },
  16353. { //a=rtcp-fb:98 trr-int 100
  16354. push: 'rtcpFbTrrInt',
  16355. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  16356. names: ['payload', 'value'],
  16357. format: "rtcp-fb:%d trr-int %d"
  16358. },
  16359. { //a=rtcp-fb:98 nack rpsi
  16360. push: 'rtcpFb',
  16361. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  16362. names: ['payload', 'type', 'subtype'],
  16363. format: function (o) {
  16364. return (o.subtype != null) ?
  16365. "rtcp-fb:%s %s %s":
  16366. "rtcp-fb:%s %s";
  16367. }
  16368. },
  16369. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  16370. //a=extmap:1/recvonly URI-gps-string
  16371. push: 'ext',
  16372. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  16373. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  16374. format: function (o) {
  16375. return (o.config != null) ?
  16376. "extmap:%s %s %s":
  16377. "extmap:%s %s";
  16378. }
  16379. },
  16380. {
  16381. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  16382. push: 'crypto',
  16383. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  16384. names: ['id', 'suite', 'config', 'sessionConfig'],
  16385. format: function (o) {
  16386. return (o.sessionConfig != null) ?
  16387. "crypto:%d %s %s %s":
  16388. "crypto:%d %s %s";
  16389. }
  16390. },
  16391. { //a=setup:actpass
  16392. name: 'setup',
  16393. reg: /^setup:(\w*)/,
  16394. format: "setup:%s"
  16395. },
  16396. { //a=mid:1
  16397. name: 'mid',
  16398. reg: /^mid:([^\s]*)/,
  16399. format: "mid:%s"
  16400. },
  16401. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  16402. name: 'msid',
  16403. reg: /^msid:(.*)/,
  16404. format: "msid:%s"
  16405. },
  16406. { //a=ptime:20
  16407. name: 'ptime',
  16408. reg: /^ptime:(\d*)/,
  16409. format: "ptime:%d"
  16410. },
  16411. { //a=maxptime:60
  16412. name: 'maxptime',
  16413. reg: /^maxptime:(\d*)/,
  16414. format: "maxptime:%d"
  16415. },
  16416. { //a=sendrecv
  16417. name: 'direction',
  16418. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  16419. },
  16420. { //a=ice-lite
  16421. name: 'icelite',
  16422. reg: /^(ice-lite)/
  16423. },
  16424. { //a=ice-ufrag:F7gI
  16425. name: 'iceUfrag',
  16426. reg: /^ice-ufrag:(\S*)/,
  16427. format: "ice-ufrag:%s"
  16428. },
  16429. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  16430. name: 'icePwd',
  16431. reg: /^ice-pwd:(\S*)/,
  16432. format: "ice-pwd:%s"
  16433. },
  16434. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  16435. name: 'fingerprint',
  16436. reg: /^fingerprint:(\S*) (\S*)/,
  16437. names: ['type', 'hash'],
  16438. format: "fingerprint:%s %s"
  16439. },
  16440. {
  16441. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  16442. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  16443. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  16444. push:'candidates',
  16445. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  16446. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  16447. format: function (o) {
  16448. var str = "candidate:%s %d %s %d %s %d typ %s";
  16449. // NB: candidate has two optional chunks, so %void middle one if it's missing
  16450. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  16451. if (o.generation != null) {
  16452. str += " generation %d";
  16453. }
  16454. return str;
  16455. }
  16456. },
  16457. { //a=end-of-candidates (keep after the candidates line for readability)
  16458. name: 'endOfCandidates',
  16459. reg: /^(end-of-candidates)/
  16460. },
  16461. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  16462. name: 'remoteCandidates',
  16463. reg: /^remote-candidates:(.*)/,
  16464. format: "remote-candidates:%s"
  16465. },
  16466. { //a=ice-options:google-ice
  16467. name: 'iceOptions',
  16468. reg: /^ice-options:(\S*)/,
  16469. format: "ice-options:%s"
  16470. },
  16471. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  16472. push: "ssrcs",
  16473. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  16474. names: ['id', 'attribute', 'value'],
  16475. format: "ssrc:%d %s:%s"
  16476. },
  16477. { //a=ssrc-group:FEC 1 2
  16478. push: "ssrcGroups",
  16479. reg: /^ssrc-group:(\w*) (.*)/,
  16480. names: ['semantics', 'ssrcs'],
  16481. format: "ssrc-group:%s %s"
  16482. },
  16483. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  16484. name: "msidSemantic",
  16485. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  16486. names: ['semantic', 'token'],
  16487. format: "msid-semantic: %s %s" // space after ":" is not accidental
  16488. },
  16489. { //a=group:BUNDLE audio video
  16490. push: 'groups',
  16491. reg: /^group:(\w*) (.*)/,
  16492. names: ['type', 'mids'],
  16493. format: "group:%s %s"
  16494. },
  16495. { //a=rtcp-mux
  16496. name: 'rtcpMux',
  16497. reg: /^(rtcp-mux)/
  16498. },
  16499. { //a=rtcp-rsize
  16500. name: 'rtcpRsize',
  16501. reg: /^(rtcp-rsize)/
  16502. },
  16503. { // any a= that we don't understand is kepts verbatim on media.invalid
  16504. push: 'invalid',
  16505. names: ["value"]
  16506. }
  16507. ]
  16508. };
  16509. // set sensible defaults to avoid polluting the grammar with boring details
  16510. Object.keys(grammar).forEach(function (key) {
  16511. var objs = grammar[key];
  16512. objs.forEach(function (obj) {
  16513. if (!obj.reg) {
  16514. obj.reg = /(.*)/;
  16515. }
  16516. if (!obj.format) {
  16517. obj.format = "%s";
  16518. }
  16519. });
  16520. });
  16521. },{}],57:[function(require,module,exports){
  16522. var parser = require('./parser');
  16523. var writer = require('./writer');
  16524. exports.write = writer;
  16525. exports.parse = parser.parse;
  16526. exports.parseFmtpConfig = parser.parseFmtpConfig;
  16527. exports.parsePayloads = parser.parsePayloads;
  16528. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  16529. },{"./parser":58,"./writer":59}],58:[function(require,module,exports){
  16530. var toIntIfInt = function (v) {
  16531. return String(Number(v)) === v ? Number(v) : v;
  16532. };
  16533. var attachProperties = function (match, location, names, rawName) {
  16534. if (rawName && !names) {
  16535. location[rawName] = toIntIfInt(match[1]);
  16536. }
  16537. else {
  16538. for (var i = 0; i < names.length; i += 1) {
  16539. if (match[i+1] != null) {
  16540. location[names[i]] = toIntIfInt(match[i+1]);
  16541. }
  16542. }
  16543. }
  16544. };
  16545. var parseReg = function (obj, location, content) {
  16546. var needsBlank = obj.name && obj.names;
  16547. if (obj.push && !location[obj.push]) {
  16548. location[obj.push] = [];
  16549. }
  16550. else if (needsBlank && !location[obj.name]) {
  16551. location[obj.name] = {};
  16552. }
  16553. var keyLocation = obj.push ?
  16554. {} : // blank object that will be pushed
  16555. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  16556. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  16557. if (obj.push) {
  16558. location[obj.push].push(keyLocation);
  16559. }
  16560. };
  16561. var grammar = require('./grammar');
  16562. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  16563. exports.parse = function (sdp) {
  16564. var session = {}
  16565. , media = []
  16566. , location = session; // points at where properties go under (one of the above)
  16567. // parse lines we understand
  16568. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  16569. var type = l[0];
  16570. var content = l.slice(2);
  16571. if (type === 'm') {
  16572. media.push({rtp: [], fmtp: []});
  16573. location = media[media.length-1]; // point at latest media line
  16574. }
  16575. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  16576. var obj = grammar[type][j];
  16577. if (obj.reg.test(content)) {
  16578. return parseReg(obj, location, content);
  16579. }
  16580. }
  16581. });
  16582. session.media = media; // link it up
  16583. return session;
  16584. };
  16585. var fmtpReducer = function (acc, expr) {
  16586. var s = expr.split('=');
  16587. if (s.length === 2) {
  16588. acc[s[0]] = toIntIfInt(s[1]);
  16589. }
  16590. return acc;
  16591. };
  16592. exports.parseFmtpConfig = function (str) {
  16593. return str.split(';').reduce(fmtpReducer, {});
  16594. };
  16595. exports.parsePayloads = function (str) {
  16596. return str.split(' ').map(Number);
  16597. };
  16598. exports.parseRemoteCandidates = function (str) {
  16599. var candidates = [];
  16600. var parts = str.split(' ').map(toIntIfInt);
  16601. for (var i = 0; i < parts.length; i += 3) {
  16602. candidates.push({
  16603. component: parts[i],
  16604. ip: parts[i + 1],
  16605. port: parts[i + 2]
  16606. });
  16607. }
  16608. return candidates;
  16609. };
  16610. },{"./grammar":56}],59:[function(require,module,exports){
  16611. var grammar = require('./grammar');
  16612. // customized util.format - discards excess arguments and can void middle ones
  16613. var formatRegExp = /%[sdv%]/g;
  16614. var format = function (formatStr) {
  16615. var i = 1;
  16616. var args = arguments;
  16617. var len = args.length;
  16618. return formatStr.replace(formatRegExp, function (x) {
  16619. if (i >= len) {
  16620. return x; // missing argument
  16621. }
  16622. var arg = args[i];
  16623. i += 1;
  16624. switch (x) {
  16625. case '%%':
  16626. return '%';
  16627. case '%s':
  16628. return String(arg);
  16629. case '%d':
  16630. return Number(arg);
  16631. case '%v':
  16632. return '';
  16633. }
  16634. });
  16635. // NB: we discard excess arguments - they are typically undefined from makeLine
  16636. };
  16637. var makeLine = function (type, obj, location) {
  16638. var str = obj.format instanceof Function ?
  16639. (obj.format(obj.push ? location : location[obj.name])) :
  16640. obj.format;
  16641. var args = [type + '=' + str];
  16642. if (obj.names) {
  16643. for (var i = 0; i < obj.names.length; i += 1) {
  16644. var n = obj.names[i];
  16645. if (obj.name) {
  16646. args.push(location[obj.name][n]);
  16647. }
  16648. else { // for mLine and push attributes
  16649. args.push(location[obj.names[i]]);
  16650. }
  16651. }
  16652. }
  16653. else {
  16654. args.push(location[obj.name]);
  16655. }
  16656. return format.apply(null, args);
  16657. };
  16658. // RFC specified order
  16659. // TODO: extend this with all the rest
  16660. var defaultOuterOrder = [
  16661. 'v', 'o', 's', 'i',
  16662. 'u', 'e', 'p', 'c',
  16663. 'b', 't', 'r', 'z', 'a'
  16664. ];
  16665. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  16666. module.exports = function (session, opts) {
  16667. opts = opts || {};
  16668. // ensure certain properties exist
  16669. if (session.version == null) {
  16670. session.version = 0; // "v=0" must be there (only defined version atm)
  16671. }
  16672. if (session.name == null) {
  16673. session.name = " "; // "s= " must be there if no meaningful name set
  16674. }
  16675. session.media.forEach(function (mLine) {
  16676. if (mLine.payloads == null) {
  16677. mLine.payloads = "";
  16678. }
  16679. });
  16680. var outerOrder = opts.outerOrder || defaultOuterOrder;
  16681. var innerOrder = opts.innerOrder || defaultInnerOrder;
  16682. var sdp = [];
  16683. // loop through outerOrder for matching properties on session
  16684. outerOrder.forEach(function (type) {
  16685. grammar[type].forEach(function (obj) {
  16686. if (obj.name in session && session[obj.name] != null) {
  16687. sdp.push(makeLine(type, obj, session));
  16688. }
  16689. else if (obj.push in session && session[obj.push] != null) {
  16690. session[obj.push].forEach(function (el) {
  16691. sdp.push(makeLine(type, obj, el));
  16692. });
  16693. }
  16694. });
  16695. });
  16696. // then for each media line, follow the innerOrder
  16697. session.media.forEach(function (mLine) {
  16698. sdp.push(makeLine('m', grammar.m[0], mLine));
  16699. innerOrder.forEach(function (type) {
  16700. grammar[type].forEach(function (obj) {
  16701. if (obj.name in mLine && mLine[obj.name] != null) {
  16702. sdp.push(makeLine(type, obj, mLine));
  16703. }
  16704. else if (obj.push in mLine && mLine[obj.push] != null) {
  16705. mLine[obj.push].forEach(function (el) {
  16706. sdp.push(makeLine(type, obj, el));
  16707. });
  16708. }
  16709. });
  16710. });
  16711. });
  16712. return sdp.join('\r\n') + '\r\n';
  16713. };
  16714. },{"./grammar":56}],60:[function(require,module,exports){
  16715. var transform = require('sdp-transform');
  16716. var transformUtils = require('./transform-utils');
  16717. var parseSsrcs = transformUtils.parseSsrcs;
  16718. var writeSsrcs = transformUtils.writeSsrcs;
  16719. //region Constants
  16720. var DEFAULT_NUM_OF_LAYERS = 3;
  16721. //endregion
  16722. //region Ctor
  16723. function Simulcast(options) {
  16724. this.options = options ? options : {};
  16725. if (!this.options.numOfLayers) {
  16726. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  16727. }
  16728. this.layers = [];
  16729. }
  16730. //endregion
  16731. //region Stateless private utility functions
  16732. /**
  16733. * Returns a random integer between min (included) and max (excluded)
  16734. * Using Math.round() gives a non-uniform distribution!
  16735. * @returns {number}
  16736. */
  16737. function generateSSRC() {
  16738. var min = 0, max = 0xffffffff;
  16739. return Math.floor(Math.random() * (max - min)) + min;
  16740. };
  16741. function processVideo(session, action) {
  16742. if (session == null || !Array.isArray(session.media)) {
  16743. return;
  16744. }
  16745. session.media.forEach(function (mLine) {
  16746. if (mLine.type === 'video') {
  16747. action(mLine);
  16748. }
  16749. });
  16750. }
  16751. function validateDescription(desc)
  16752. {
  16753. return desc && desc != null
  16754. && desc.type && desc.type != ''
  16755. && desc.sdp && desc.sdp != '';
  16756. }
  16757. function explodeRemoteSimulcast(mLine) {
  16758. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16759. return;
  16760. }
  16761. var sources = parseSsrcs(mLine);
  16762. var order = [];
  16763. // Find the SIM group and explode its sources.
  16764. var j = mLine.ssrcGroups.length;
  16765. while (j--) {
  16766. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  16767. continue;
  16768. }
  16769. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  16770. for (var i = 0; i < simulcastSsrcs.length; i++) {
  16771. var ssrc = simulcastSsrcs[i];
  16772. order.push(ssrc);
  16773. var parts = sources[ssrc].msid.split(' ');
  16774. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  16775. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  16776. // Remove all the groups that this SSRC participates in.
  16777. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16778. if (relatedGroup.semantics === 'SIM') {
  16779. return;
  16780. }
  16781. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  16782. if (relatedSsrcs.indexOf(ssrc) === -1) {
  16783. return;
  16784. }
  16785. // Nuke all the related SSRCs.
  16786. relatedSsrcs.forEach(function (relatedSSRC) {
  16787. sources[relatedSSRC].msid = sources[ssrc].msid;
  16788. sources[relatedSSRC].cname = sources[ssrc].cname;
  16789. if (relatedSSRC !== ssrc) {
  16790. order.push(relatedSSRC);
  16791. }
  16792. });
  16793. // Schedule the related group for nuking.
  16794. })
  16795. }
  16796. mLine.ssrcs = writeSsrcs(sources, order);
  16797. mLine.ssrcGroups.splice(j, 1);
  16798. };
  16799. }
  16800. function squeezeRemoteSimulcast(mLine) {
  16801. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16802. return;
  16803. }
  16804. var sources = parseSsrcs(mLine);
  16805. // Find the SIM group and nuke it.
  16806. mLine.ssrcGroups.some(function (simulcastGroup) {
  16807. if (simulcastGroup.semantics !== 'SIM') {
  16808. return false;
  16809. }
  16810. // Schedule the SIM group for nuking.
  16811. simulcastGroup.nuke = true;
  16812. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  16813. // Nuke all the higher layer SSRCs.
  16814. for (var i = 1; i < simulcastSsrcs.length; i++) {
  16815. var ssrc = simulcastSsrcs[i];
  16816. delete sources[ssrc];
  16817. // Remove all the groups that this SSRC participates in.
  16818. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16819. if (relatedGroup.semantics === 'SIM') {
  16820. return;
  16821. }
  16822. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  16823. if (relatedSsrcs.indexOf(ssrc) === -1) {
  16824. return;
  16825. }
  16826. // Nuke all the related SSRCs.
  16827. relatedSsrcs.forEach(function (relatedSSRC) {
  16828. delete sources[relatedSSRC];
  16829. });
  16830. // Schedule the related group for nuking.
  16831. relatedGroup.nuke = true;
  16832. })
  16833. }
  16834. return true;
  16835. });
  16836. mLine.ssrcs = writeSsrcs(sources);
  16837. // Nuke all the scheduled groups.
  16838. var i = mLine.ssrcGroups.length;
  16839. while (i--) {
  16840. if (mLine.ssrcGroups[i].nuke) {
  16841. mLine.ssrcGroups.splice(i, 1);
  16842. }
  16843. }
  16844. }
  16845. function removeGoogConference(mLine) {
  16846. if (!mLine || !Array.isArray(mLine.invalid)) {
  16847. return;
  16848. }
  16849. var i = mLine.invalid.length;
  16850. while (i--) {
  16851. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  16852. mLine.invalid.splice(i, 1);
  16853. }
  16854. }
  16855. }
  16856. function assertGoogConference(mLine) {
  16857. if (!mLine) {
  16858. return;
  16859. }
  16860. if (!Array.isArray(mLine.invalid)) {
  16861. mLine.invalid = [];
  16862. }
  16863. if (!mLine.invalid.some(
  16864. function (i) { return i.value === 'x-google-flag:conference' })) {
  16865. mLine.invalid.push({'value': 'x-google-flag:conference'});
  16866. }
  16867. }
  16868. //endregion
  16869. //region "Private" functions
  16870. /**
  16871. *
  16872. * @param mLine
  16873. * @private
  16874. */
  16875. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  16876. if (!mLine || mLine.type !== 'video') {
  16877. return;
  16878. }
  16879. var sources = parseSsrcs(mLine);
  16880. if (Object.keys(sources).length === 0) {
  16881. // no sources, disable simulcast.
  16882. if (this.layers.length !== 0) {
  16883. this.layers = [];
  16884. }
  16885. return;
  16886. }
  16887. // find the base layer (we'll reuse its msid and cname).
  16888. var baseLayerSSRC = Object.keys(sources)[0];
  16889. var baseLayer = sources[baseLayerSSRC];
  16890. // todo(gp) handle screen sharing.
  16891. // check if base CNAME has changed and reinitialise layers.
  16892. if (this.layers.length > 0
  16893. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  16894. this.layers = [];
  16895. }
  16896. // (re)initialise layers
  16897. if (this.layers.length < 1) {
  16898. // first push the base layer.
  16899. this.layers.push({
  16900. ssrc: baseLayerSSRC,
  16901. msid: baseLayer.msid,
  16902. cname: baseLayer.cname
  16903. });
  16904. var rtx = false; // RFC 4588
  16905. if (Array.isArray(mLine.rtp)) {
  16906. rtx = mLine.rtp.some(
  16907. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  16908. }
  16909. if (rtx) {
  16910. this.layers[0].rtx = generateSSRC();
  16911. }
  16912. // now push additional layers.
  16913. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  16914. var layer = { ssrc: generateSSRC() };
  16915. if (rtx) {
  16916. layer.rtx = generateSSRC();
  16917. }
  16918. this.layers.push(layer);
  16919. }
  16920. }
  16921. };
  16922. /**
  16923. *
  16924. * @param mLine
  16925. * @private
  16926. */
  16927. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  16928. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  16929. var sources = {};
  16930. var msid = this.layers[0].msid;
  16931. var cname = this.layers[0].cname;
  16932. var simulcastSsrcs = [];
  16933. var ssrcGroups = [];
  16934. for (var i = 0; i < this.layers.length; i++) {
  16935. var layer = this.layers[i];
  16936. sources[layer.ssrc] = { msid: msid, cname: cname };
  16937. simulcastSsrcs.push(layer.ssrc);
  16938. if (layer.rtx) {
  16939. sources[layer.rtx] = {
  16940. msid: msid,
  16941. cname: cname
  16942. }
  16943. ssrcGroups.push({
  16944. semantics: 'FID',
  16945. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  16946. });
  16947. }
  16948. }
  16949. ssrcGroups.push({
  16950. semantics: 'SIM',
  16951. ssrcs: simulcastSsrcs.join(' ')
  16952. });
  16953. mLine.ssrcGroups = ssrcGroups;
  16954. mLine.ssrcs = writeSsrcs(sources);
  16955. }
  16956. }
  16957. //endregion
  16958. //region "Public" functions
  16959. Simulcast.prototype.isSupported = function () {
  16960. return window.chrome;
  16961. // TODO this needs improvements. For example I doubt that Chrome in Android
  16962. // has simulcast support. Also, only recent versions of Chromium have native
  16963. // simulcast support.
  16964. }
  16965. /**
  16966. *
  16967. * @param desc
  16968. * @returns {RTCSessionDescription}
  16969. */
  16970. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  16971. if (!validateDescription(desc)) {
  16972. return desc;
  16973. }
  16974. var session = transform.parse(desc.sdp);
  16975. var self = this;
  16976. processVideo(session, function (mLine) {
  16977. // Handle simulcast reception.
  16978. if (self.options.explodeRemoteSimulcast) {
  16979. explodeRemoteSimulcast(mLine);
  16980. } else {
  16981. squeezeRemoteSimulcast(mLine);
  16982. }
  16983. // If native simulcast is enabled, we must append the x-goog-conference
  16984. // attribute to the SDP.
  16985. if (self.layers.length < 1) {
  16986. removeGoogConference(mLine);
  16987. } else {
  16988. assertGoogConference(mLine);
  16989. }
  16990. });
  16991. return new RTCSessionDescription({
  16992. type: desc.type,
  16993. sdp: transform.write(session)
  16994. });
  16995. };
  16996. /**
  16997. *
  16998. * @param desc
  16999. * @returns {RTCSessionDescription}
  17000. */
  17001. Simulcast.prototype.mungeLocalDescription = function (desc) {
  17002. if (!validateDescription(desc) || !this.isSupported()) {
  17003. return desc;
  17004. }
  17005. var session = transform.parse(desc.sdp);
  17006. var self = this;
  17007. processVideo(session, function (mLine) {
  17008. // Initialize native simulcast layers, if not already done.
  17009. self._maybeInitializeLayers(mLine);
  17010. // Update the SDP with the simulcast layers.
  17011. self._restoreSimulcastView(mLine);
  17012. });
  17013. return new RTCSessionDescription({
  17014. type: desc.type,
  17015. sdp: transform.write(session)
  17016. });
  17017. };
  17018. //endregion
  17019. module.exports = Simulcast;
  17020. },{"./transform-utils":61,"sdp-transform":63}],61:[function(require,module,exports){
  17021. exports.writeSsrcs = function(sources, order) {
  17022. var ssrcs = [];
  17023. // expand sources to ssrcs
  17024. if (typeof sources !== 'undefined' &&
  17025. Object.keys(sources).length !== 0) {
  17026. if (Array.isArray(order)) {
  17027. for (var i = 0; i < order.length; i++) {
  17028. var ssrc = order[i];
  17029. var source = sources[ssrc];
  17030. Object.keys(source).forEach(function (attribute) {
  17031. ssrcs.push({
  17032. id: ssrc,
  17033. attribute: attribute,
  17034. value: source[attribute]
  17035. });
  17036. });
  17037. }
  17038. } else {
  17039. Object.keys(sources).forEach(function (ssrc) {
  17040. var source = sources[ssrc];
  17041. Object.keys(source).forEach(function (attribute) {
  17042. ssrcs.push({
  17043. id: ssrc,
  17044. attribute: attribute,
  17045. value: source[attribute]
  17046. });
  17047. });
  17048. });
  17049. }
  17050. }
  17051. return ssrcs;
  17052. };
  17053. exports.parseSsrcs = function (mLine) {
  17054. var sources = {};
  17055. // group sources attributes by ssrc.
  17056. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  17057. mLine.ssrcs.forEach(function (ssrc) {
  17058. if (!sources[ssrc.id])
  17059. sources[ssrc.id] = {};
  17060. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  17061. });
  17062. }
  17063. return sources;
  17064. };
  17065. },{}],62:[function(require,module,exports){
  17066. arguments[4][56][0].apply(exports,arguments)
  17067. },{"dup":56}],63:[function(require,module,exports){
  17068. arguments[4][57][0].apply(exports,arguments)
  17069. },{"./parser":64,"./writer":65,"dup":57}],64:[function(require,module,exports){
  17070. arguments[4][58][0].apply(exports,arguments)
  17071. },{"./grammar":62,"dup":58}],65:[function(require,module,exports){
  17072. arguments[4][59][0].apply(exports,arguments)
  17073. },{"./grammar":62,"dup":59}],66:[function(require,module,exports){
  17074. var grammar = module.exports = {
  17075. v: [{
  17076. name: 'version',
  17077. reg: /^(\d*)$/
  17078. }],
  17079. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  17080. // NB: sessionId will be a String in most cases because it is huge
  17081. name: 'origin',
  17082. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  17083. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  17084. format: "%s %s %d %s IP%d %s"
  17085. }],
  17086. // default parsing of these only (though some of these feel outdated)
  17087. s: [{ name: 'name' }],
  17088. i: [{ name: 'description' }],
  17089. u: [{ name: 'uri' }],
  17090. e: [{ name: 'email' }],
  17091. p: [{ name: 'phone' }],
  17092. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  17093. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  17094. //k: [{}], // outdated thing ignored
  17095. t: [{ //t=0 0
  17096. name: 'timing',
  17097. reg: /^(\d*) (\d*)/,
  17098. names: ['start', 'stop'],
  17099. format: "%d %d"
  17100. }],
  17101. c: [{ //c=IN IP4 10.47.197.26
  17102. name: 'connection',
  17103. reg: /^IN IP(\d) (\S*)/,
  17104. names: ['version', 'ip'],
  17105. format: "IN IP%d %s"
  17106. }],
  17107. b: [{ //b=AS:4000
  17108. push: 'bandwidth',
  17109. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  17110. names: ['type', 'limit'],
  17111. format: "%s:%s"
  17112. }],
  17113. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  17114. // NB: special - pushes to session
  17115. // TODO: rtp/fmtp should be filtered by the payloads found here?
  17116. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  17117. names: ['type', 'port', 'protocol', 'payloads'],
  17118. format: "%s %d %s %s"
  17119. }],
  17120. a: [
  17121. { //a=rtpmap:110 opus/48000/2
  17122. push: 'rtp',
  17123. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  17124. names: ['payload', 'codec', 'rate', 'encoding'],
  17125. format: function (o) {
  17126. return (o.encoding) ?
  17127. "rtpmap:%d %s/%s/%s":
  17128. "rtpmap:%d %s/%s";
  17129. }
  17130. },
  17131. {
  17132. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  17133. //a=fmtp:111 minptime=10; useinbandfec=1
  17134. push: 'fmtp',
  17135. reg: /^fmtp:(\d*) ([\S| ]*)/,
  17136. names: ['payload', 'config'],
  17137. format: "fmtp:%d %s"
  17138. },
  17139. { //a=control:streamid=0
  17140. name: 'control',
  17141. reg: /^control:(.*)/,
  17142. format: "control:%s"
  17143. },
  17144. { //a=rtcp:65179 IN IP4 193.84.77.194
  17145. name: 'rtcp',
  17146. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  17147. names: ['port', 'netType', 'ipVer', 'address'],
  17148. format: function (o) {
  17149. return (o.address != null) ?
  17150. "rtcp:%d %s IP%d %s":
  17151. "rtcp:%d";
  17152. }
  17153. },
  17154. { //a=rtcp-fb:98 trr-int 100
  17155. push: 'rtcpFbTrrInt',
  17156. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  17157. names: ['payload', 'value'],
  17158. format: "rtcp-fb:%d trr-int %d"
  17159. },
  17160. { //a=rtcp-fb:98 nack rpsi
  17161. push: 'rtcpFb',
  17162. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  17163. names: ['payload', 'type', 'subtype'],
  17164. format: function (o) {
  17165. return (o.subtype != null) ?
  17166. "rtcp-fb:%s %s %s":
  17167. "rtcp-fb:%s %s";
  17168. }
  17169. },
  17170. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  17171. //a=extmap:1/recvonly URI-gps-string
  17172. push: 'ext',
  17173. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  17174. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  17175. format: function (o) {
  17176. return (o.config != null) ?
  17177. "extmap:%s %s %s":
  17178. "extmap:%s %s";
  17179. }
  17180. },
  17181. {
  17182. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  17183. push: 'crypto',
  17184. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  17185. names: ['id', 'suite', 'config', 'sessionConfig'],
  17186. format: function (o) {
  17187. return (o.sessionConfig != null) ?
  17188. "crypto:%d %s %s %s":
  17189. "crypto:%d %s %s";
  17190. }
  17191. },
  17192. { //a=setup:actpass
  17193. name: 'setup',
  17194. reg: /^setup:(\w*)/,
  17195. format: "setup:%s"
  17196. },
  17197. { //a=mid:1
  17198. name: 'mid',
  17199. reg: /^mid:([^\s]*)/,
  17200. format: "mid:%s"
  17201. },
  17202. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  17203. name: 'msid',
  17204. reg: /^msid:(.*)/,
  17205. format: "msid:%s"
  17206. },
  17207. { //a=ptime:20
  17208. name: 'ptime',
  17209. reg: /^ptime:(\d*)/,
  17210. format: "ptime:%d"
  17211. },
  17212. { //a=maxptime:60
  17213. name: 'maxptime',
  17214. reg: /^maxptime:(\d*)/,
  17215. format: "maxptime:%d"
  17216. },
  17217. { //a=sendrecv
  17218. name: 'direction',
  17219. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  17220. },
  17221. { //a=ice-lite
  17222. name: 'icelite',
  17223. reg: /^(ice-lite)/
  17224. },
  17225. { //a=ice-ufrag:F7gI
  17226. name: 'iceUfrag',
  17227. reg: /^ice-ufrag:(\S*)/,
  17228. format: "ice-ufrag:%s"
  17229. },
  17230. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  17231. name: 'icePwd',
  17232. reg: /^ice-pwd:(\S*)/,
  17233. format: "ice-pwd:%s"
  17234. },
  17235. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  17236. name: 'fingerprint',
  17237. reg: /^fingerprint:(\S*) (\S*)/,
  17238. names: ['type', 'hash'],
  17239. format: "fingerprint:%s %s"
  17240. },
  17241. {
  17242. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  17243. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  17244. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  17245. push:'candidates',
  17246. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  17247. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  17248. format: function (o) {
  17249. var str = "candidate:%s %d %s %d %s %d typ %s";
  17250. // NB: candidate has two optional chunks, so %void middle one if it's missing
  17251. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  17252. if (o.generation != null) {
  17253. str += " generation %d";
  17254. }
  17255. return str;
  17256. }
  17257. },
  17258. { //a=end-of-candidates (keep after the candidates line for readability)
  17259. name: 'endOfCandidates',
  17260. reg: /^(end-of-candidates)/
  17261. },
  17262. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  17263. name: 'remoteCandidates',
  17264. reg: /^remote-candidates:(.*)/,
  17265. format: "remote-candidates:%s"
  17266. },
  17267. { //a=ice-options:google-ice
  17268. name: 'iceOptions',
  17269. reg: /^ice-options:(\S*)/,
  17270. format: "ice-options:%s"
  17271. },
  17272. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  17273. push: "ssrcs",
  17274. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  17275. names: ['id', 'attribute', 'value'],
  17276. format: "ssrc:%d %s:%s"
  17277. },
  17278. { //a=ssrc-group:FEC 1 2
  17279. push: "ssrcGroups",
  17280. reg: /^ssrc-group:(\w*) (.*)/,
  17281. names: ['semantics', 'ssrcs'],
  17282. format: "ssrc-group:%s %s"
  17283. },
  17284. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  17285. name: "msidSemantic",
  17286. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  17287. names: ['semantic', 'token'],
  17288. format: "msid-semantic: %s %s" // space after ":" is not accidental
  17289. },
  17290. { //a=group:BUNDLE audio video
  17291. push: 'groups',
  17292. reg: /^group:(\w*) (.*)/,
  17293. names: ['type', 'mids'],
  17294. format: "group:%s %s"
  17295. },
  17296. { //a=rtcp-mux
  17297. name: 'rtcpMux',
  17298. reg: /^(rtcp-mux)/
  17299. },
  17300. { //a=rtcp-rsize
  17301. name: 'rtcpRsize',
  17302. reg: /^(rtcp-rsize)/
  17303. },
  17304. { // any a= that we don't understand is kepts verbatim on media.invalid
  17305. push: 'invalid',
  17306. names: ["value"]
  17307. }
  17308. ]
  17309. };
  17310. // set sensible defaults to avoid polluting the grammar with boring details
  17311. Object.keys(grammar).forEach(function (key) {
  17312. var objs = grammar[key];
  17313. objs.forEach(function (obj) {
  17314. if (!obj.reg) {
  17315. obj.reg = /(.*)/;
  17316. }
  17317. if (!obj.format) {
  17318. obj.format = "%s";
  17319. }
  17320. });
  17321. });
  17322. },{}],67:[function(require,module,exports){
  17323. arguments[4][57][0].apply(exports,arguments)
  17324. },{"./parser":68,"./writer":69,"dup":57}],68:[function(require,module,exports){
  17325. var toIntIfInt = function (v) {
  17326. return String(Number(v)) === v ? Number(v) : v;
  17327. };
  17328. var attachProperties = function (match, location, names, rawName) {
  17329. if (rawName && !names) {
  17330. location[rawName] = toIntIfInt(match[1]);
  17331. }
  17332. else {
  17333. for (var i = 0; i < names.length; i += 1) {
  17334. if (match[i+1] != null) {
  17335. location[names[i]] = toIntIfInt(match[i+1]);
  17336. }
  17337. }
  17338. }
  17339. };
  17340. var parseReg = function (obj, location, content) {
  17341. var needsBlank = obj.name && obj.names;
  17342. if (obj.push && !location[obj.push]) {
  17343. location[obj.push] = [];
  17344. }
  17345. else if (needsBlank && !location[obj.name]) {
  17346. location[obj.name] = {};
  17347. }
  17348. var keyLocation = obj.push ?
  17349. {} : // blank object that will be pushed
  17350. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  17351. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  17352. if (obj.push) {
  17353. location[obj.push].push(keyLocation);
  17354. }
  17355. };
  17356. var grammar = require('./grammar');
  17357. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  17358. exports.parse = function (sdp) {
  17359. var session = {}
  17360. , media = []
  17361. , location = session; // points at where properties go under (one of the above)
  17362. // parse lines we understand
  17363. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  17364. var type = l[0];
  17365. var content = l.slice(2);
  17366. if (type === 'm') {
  17367. media.push({rtp: [], fmtp: []});
  17368. location = media[media.length-1]; // point at latest media line
  17369. }
  17370. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  17371. var obj = grammar[type][j];
  17372. if (obj.reg.test(content)) {
  17373. return parseReg(obj, location, content);
  17374. }
  17375. }
  17376. });
  17377. session.media = media; // link it up
  17378. return session;
  17379. };
  17380. var fmtpReducer = function (acc, expr) {
  17381. var s = expr.split('=');
  17382. if (s.length === 2) {
  17383. acc[s[0]] = toIntIfInt(s[1]);
  17384. }
  17385. return acc;
  17386. };
  17387. exports.parseFmtpConfig = function (str) {
  17388. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  17389. };
  17390. exports.parsePayloads = function (str) {
  17391. return str.split(' ').map(Number);
  17392. };
  17393. exports.parseRemoteCandidates = function (str) {
  17394. var candidates = [];
  17395. var parts = str.split(' ').map(toIntIfInt);
  17396. for (var i = 0; i < parts.length; i += 3) {
  17397. candidates.push({
  17398. component: parts[i],
  17399. ip: parts[i + 1],
  17400. port: parts[i + 2]
  17401. });
  17402. }
  17403. return candidates;
  17404. };
  17405. },{"./grammar":66}],69:[function(require,module,exports){
  17406. arguments[4][59][0].apply(exports,arguments)
  17407. },{"./grammar":66,"dup":59}],70:[function(require,module,exports){
  17408. var MediaStreamType = {
  17409. VIDEO_TYPE: "Video",
  17410. AUDIO_TYPE: "Audio"
  17411. };
  17412. module.exports = MediaStreamType;
  17413. },{}],71:[function(require,module,exports){
  17414. var RTCEvents = {
  17415. RTC_READY: "rtc.ready",
  17416. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  17417. LASTN_CHANGED: "rtc.lastn_changed",
  17418. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  17419. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  17420. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  17421. AUDIO_MUTE: "rtc.audio_mute",
  17422. VIDEO_MUTE: "rtc.video_mute"
  17423. };
  17424. module.exports = RTCEvents;
  17425. },{}],72:[function(require,module,exports){
  17426. var Resolutions = {
  17427. "1080": {
  17428. width: 1920,
  17429. height: 1080,
  17430. order: 7
  17431. },
  17432. "fullhd": {
  17433. width: 1920,
  17434. height: 1080,
  17435. order: 7
  17436. },
  17437. "720": {
  17438. width: 1280,
  17439. height: 720,
  17440. order: 6
  17441. },
  17442. "hd": {
  17443. width: 1280,
  17444. height: 720,
  17445. order: 6
  17446. },
  17447. "960": {
  17448. width: 960,
  17449. height: 720,
  17450. order: 5
  17451. },
  17452. "640": {
  17453. width: 640,
  17454. height: 480,
  17455. order: 4
  17456. },
  17457. "vga": {
  17458. width: 640,
  17459. height: 480,
  17460. order: 4
  17461. },
  17462. "360": {
  17463. width: 640,
  17464. height: 360,
  17465. order: 3
  17466. },
  17467. "320": {
  17468. width: 320,
  17469. height: 240,
  17470. order: 2
  17471. },
  17472. "180": {
  17473. width: 320,
  17474. height: 180,
  17475. order: 1
  17476. }
  17477. };
  17478. module.exports = Resolutions;
  17479. },{}],73:[function(require,module,exports){
  17480. var StreamEventTypes = {
  17481. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  17482. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  17483. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  17484. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  17485. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  17486. };
  17487. module.exports = StreamEventTypes;
  17488. },{}],74:[function(require,module,exports){
  17489. var AuthenticationEvents = {
  17490. /**
  17491. * Event callback arguments:
  17492. * function(authenticationEnabled, userIdentity)
  17493. * authenticationEnabled - indicates whether authentication has been enabled
  17494. * in this session
  17495. * userIdentity - if user has been logged in then it contains user name. If
  17496. * contains 'null' or 'undefined' then user is not logged in.
  17497. */
  17498. IDENTITY_UPDATED: "authentication.identity_updated"
  17499. };
  17500. module.exports = AuthenticationEvents;
  17501. },{}],75:[function(require,module,exports){
  17502. var DesktopSharingEventTypes = {
  17503. INIT: "ds.init",
  17504. SWITCHING_DONE: "ds.switching_done",
  17505. NEW_STREAM_CREATED: "ds.new_stream_created"
  17506. };
  17507. module.exports = DesktopSharingEventTypes;
  17508. },{}],76:[function(require,module,exports){
  17509. var XMPPEvents = {
  17510. CONNECTION_FAILED: "xmpp.connection.failed",
  17511. // Indicates an interrupted connection event.
  17512. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  17513. // Indicates a restored connection event.
  17514. CONNECTION_RESTORED: "xmpp.connection.restored",
  17515. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  17516. CALL_INCOMING: "xmpp.callincoming.jingle",
  17517. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  17518. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  17519. KICKED: "xmpp.kicked",
  17520. BRIDGE_DOWN: "xmpp.bridge_down",
  17521. USER_ID_CHANGED: "xmpp.user_id_changed",
  17522. // We joined the MUC
  17523. MUC_JOINED: "xmpp.muc_joined",
  17524. // A member joined the MUC
  17525. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  17526. // A member left the MUC
  17527. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  17528. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  17529. MUC_DESTROYED: "xmpp.muc_destroyed",
  17530. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  17531. REMOTE_STATS: "xmpp.remote_stats",
  17532. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  17533. PRESENCE_STATUS: "xmpp.presence_status",
  17534. RESERVATION_ERROR: "xmpp.room_reservation_error",
  17535. SUBJECT_CHANGED: "xmpp.subject_changed",
  17536. MESSAGE_RECEIVED: "xmpp.message_received",
  17537. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  17538. PASSWORD_REQUIRED: "xmpp.password_required",
  17539. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  17540. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  17541. ETHERPAD: "xmpp.etherpad",
  17542. DEVICE_AVAILABLE: "xmpp.device_available",
  17543. VIDEO_TYPE: "xmpp.video_type",
  17544. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  17545. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  17546. AUDIO_MUTED: "xmpp.audio_muted",
  17547. VIDEO_MUTED: "xmpp.video_muted",
  17548. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  17549. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  17550. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  17551. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  17552. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  17553. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  17554. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  17555. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  17556. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  17557. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  17558. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  17559. // xmpp is connected and obtained user media
  17560. READY_TO_JOIN: 'xmpp.ready_to_join',
  17561. FOCUS_LEFT: "xmpp.focus_left",
  17562. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  17563. };
  17564. module.exports = XMPPEvents;
  17565. },{}],77:[function(require,module,exports){
  17566. // Copyright Joyent, Inc. and other Node contributors.
  17567. //
  17568. // Permission is hereby granted, free of charge, to any person obtaining a
  17569. // copy of this software and associated documentation files (the
  17570. // "Software"), to deal in the Software without restriction, including
  17571. // without limitation the rights to use, copy, modify, merge, publish,
  17572. // distribute, sublicense, and/or sell copies of the Software, and to permit
  17573. // persons to whom the Software is furnished to do so, subject to the
  17574. // following conditions:
  17575. //
  17576. // The above copyright notice and this permission notice shall be included
  17577. // in all copies or substantial portions of the Software.
  17578. //
  17579. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  17580. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17581. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  17582. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  17583. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  17584. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  17585. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  17586. function EventEmitter() {
  17587. this._events = this._events || {};
  17588. this._maxListeners = this._maxListeners || undefined;
  17589. }
  17590. module.exports = EventEmitter;
  17591. // Backwards-compat with node 0.10.x
  17592. EventEmitter.EventEmitter = EventEmitter;
  17593. EventEmitter.prototype._events = undefined;
  17594. EventEmitter.prototype._maxListeners = undefined;
  17595. // By default EventEmitters will print a warning if more than 10 listeners are
  17596. // added to it. This is a useful default which helps finding memory leaks.
  17597. EventEmitter.defaultMaxListeners = 10;
  17598. // Obviously not all Emitters should be limited to 10. This function allows
  17599. // that to be increased. Set to zero for unlimited.
  17600. EventEmitter.prototype.setMaxListeners = function(n) {
  17601. if (!isNumber(n) || n < 0 || isNaN(n))
  17602. throw TypeError('n must be a positive number');
  17603. this._maxListeners = n;
  17604. return this;
  17605. };
  17606. EventEmitter.prototype.emit = function(type) {
  17607. var er, handler, len, args, i, listeners;
  17608. if (!this._events)
  17609. this._events = {};
  17610. // If there is no 'error' event listener then throw.
  17611. if (type === 'error') {
  17612. if (!this._events.error ||
  17613. (isObject(this._events.error) && !this._events.error.length)) {
  17614. er = arguments[1];
  17615. if (er instanceof Error) {
  17616. throw er; // Unhandled 'error' event
  17617. }
  17618. throw TypeError('Uncaught, unspecified "error" event.');
  17619. }
  17620. }
  17621. handler = this._events[type];
  17622. if (isUndefined(handler))
  17623. return false;
  17624. if (isFunction(handler)) {
  17625. switch (arguments.length) {
  17626. // fast cases
  17627. case 1:
  17628. handler.call(this);
  17629. break;
  17630. case 2:
  17631. handler.call(this, arguments[1]);
  17632. break;
  17633. case 3:
  17634. handler.call(this, arguments[1], arguments[2]);
  17635. break;
  17636. // slower
  17637. default:
  17638. len = arguments.length;
  17639. args = new Array(len - 1);
  17640. for (i = 1; i < len; i++)
  17641. args[i - 1] = arguments[i];
  17642. handler.apply(this, args);
  17643. }
  17644. } else if (isObject(handler)) {
  17645. len = arguments.length;
  17646. args = new Array(len - 1);
  17647. for (i = 1; i < len; i++)
  17648. args[i - 1] = arguments[i];
  17649. listeners = handler.slice();
  17650. len = listeners.length;
  17651. for (i = 0; i < len; i++)
  17652. listeners[i].apply(this, args);
  17653. }
  17654. return true;
  17655. };
  17656. EventEmitter.prototype.addListener = function(type, listener) {
  17657. var m;
  17658. if (!isFunction(listener))
  17659. throw TypeError('listener must be a function');
  17660. if (!this._events)
  17661. this._events = {};
  17662. // To avoid recursion in the case that type === "newListener"! Before
  17663. // adding it to the listeners, first emit "newListener".
  17664. if (this._events.newListener)
  17665. this.emit('newListener', type,
  17666. isFunction(listener.listener) ?
  17667. listener.listener : listener);
  17668. if (!this._events[type])
  17669. // Optimize the case of one listener. Don't need the extra array object.
  17670. this._events[type] = listener;
  17671. else if (isObject(this._events[type]))
  17672. // If we've already got an array, just append.
  17673. this._events[type].push(listener);
  17674. else
  17675. // Adding the second element, need to change to array.
  17676. this._events[type] = [this._events[type], listener];
  17677. // Check for listener leak
  17678. if (isObject(this._events[type]) && !this._events[type].warned) {
  17679. var m;
  17680. if (!isUndefined(this._maxListeners)) {
  17681. m = this._maxListeners;
  17682. } else {
  17683. m = EventEmitter.defaultMaxListeners;
  17684. }
  17685. if (m && m > 0 && this._events[type].length > m) {
  17686. this._events[type].warned = true;
  17687. console.error('(node) warning: possible EventEmitter memory ' +
  17688. 'leak detected. %d listeners added. ' +
  17689. 'Use emitter.setMaxListeners() to increase limit.',
  17690. this._events[type].length);
  17691. if (typeof console.trace === 'function') {
  17692. // not supported in IE 10
  17693. console.trace();
  17694. }
  17695. }
  17696. }
  17697. return this;
  17698. };
  17699. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  17700. EventEmitter.prototype.once = function(type, listener) {
  17701. if (!isFunction(listener))
  17702. throw TypeError('listener must be a function');
  17703. var fired = false;
  17704. function g() {
  17705. this.removeListener(type, g);
  17706. if (!fired) {
  17707. fired = true;
  17708. listener.apply(this, arguments);
  17709. }
  17710. }
  17711. g.listener = listener;
  17712. this.on(type, g);
  17713. return this;
  17714. };
  17715. // emits a 'removeListener' event iff the listener was removed
  17716. EventEmitter.prototype.removeListener = function(type, listener) {
  17717. var list, position, length, i;
  17718. if (!isFunction(listener))
  17719. throw TypeError('listener must be a function');
  17720. if (!this._events || !this._events[type])
  17721. return this;
  17722. list = this._events[type];
  17723. length = list.length;
  17724. position = -1;
  17725. if (list === listener ||
  17726. (isFunction(list.listener) && list.listener === listener)) {
  17727. delete this._events[type];
  17728. if (this._events.removeListener)
  17729. this.emit('removeListener', type, listener);
  17730. } else if (isObject(list)) {
  17731. for (i = length; i-- > 0;) {
  17732. if (list[i] === listener ||
  17733. (list[i].listener && list[i].listener === listener)) {
  17734. position = i;
  17735. break;
  17736. }
  17737. }
  17738. if (position < 0)
  17739. return this;
  17740. if (list.length === 1) {
  17741. list.length = 0;
  17742. delete this._events[type];
  17743. } else {
  17744. list.splice(position, 1);
  17745. }
  17746. if (this._events.removeListener)
  17747. this.emit('removeListener', type, listener);
  17748. }
  17749. return this;
  17750. };
  17751. EventEmitter.prototype.removeAllListeners = function(type) {
  17752. var key, listeners;
  17753. if (!this._events)
  17754. return this;
  17755. // not listening for removeListener, no need to emit
  17756. if (!this._events.removeListener) {
  17757. if (arguments.length === 0)
  17758. this._events = {};
  17759. else if (this._events[type])
  17760. delete this._events[type];
  17761. return this;
  17762. }
  17763. // emit removeListener for all listeners on all events
  17764. if (arguments.length === 0) {
  17765. for (key in this._events) {
  17766. if (key === 'removeListener') continue;
  17767. this.removeAllListeners(key);
  17768. }
  17769. this.removeAllListeners('removeListener');
  17770. this._events = {};
  17771. return this;
  17772. }
  17773. listeners = this._events[type];
  17774. if (isFunction(listeners)) {
  17775. this.removeListener(type, listeners);
  17776. } else {
  17777. // LIFO order
  17778. while (listeners.length)
  17779. this.removeListener(type, listeners[listeners.length - 1]);
  17780. }
  17781. delete this._events[type];
  17782. return this;
  17783. };
  17784. EventEmitter.prototype.listeners = function(type) {
  17785. var ret;
  17786. if (!this._events || !this._events[type])
  17787. ret = [];
  17788. else if (isFunction(this._events[type]))
  17789. ret = [this._events[type]];
  17790. else
  17791. ret = this._events[type].slice();
  17792. return ret;
  17793. };
  17794. EventEmitter.listenerCount = function(emitter, type) {
  17795. var ret;
  17796. if (!emitter._events || !emitter._events[type])
  17797. ret = 0;
  17798. else if (isFunction(emitter._events[type]))
  17799. ret = 1;
  17800. else
  17801. ret = emitter._events[type].length;
  17802. return ret;
  17803. };
  17804. function isFunction(arg) {
  17805. return typeof arg === 'function';
  17806. }
  17807. function isNumber(arg) {
  17808. return typeof arg === 'number';
  17809. }
  17810. function isObject(arg) {
  17811. return typeof arg === 'object' && arg !== null;
  17812. }
  17813. function isUndefined(arg) {
  17814. return arg === void 0;
  17815. }
  17816. },{}],78:[function(require,module,exports){
  17817. // shim for using process in browser
  17818. var process = module.exports = {};
  17819. var queue = [];
  17820. var draining = false;
  17821. function drainQueue() {
  17822. if (draining) {
  17823. return;
  17824. }
  17825. draining = true;
  17826. var currentQueue;
  17827. var len = queue.length;
  17828. while(len) {
  17829. currentQueue = queue;
  17830. queue = [];
  17831. var i = -1;
  17832. while (++i < len) {
  17833. currentQueue[i]();
  17834. }
  17835. len = queue.length;
  17836. }
  17837. draining = false;
  17838. }
  17839. process.nextTick = function (fun) {
  17840. queue.push(fun);
  17841. if (!draining) {
  17842. setTimeout(drainQueue, 0);
  17843. }
  17844. };
  17845. process.title = 'browser';
  17846. process.browser = true;
  17847. process.env = {};
  17848. process.argv = [];
  17849. process.version = ''; // empty string to avoid regexp issues
  17850. function noop() {}
  17851. process.on = noop;
  17852. process.addListener = noop;
  17853. process.once = noop;
  17854. process.off = noop;
  17855. process.removeListener = noop;
  17856. process.removeAllListeners = noop;
  17857. process.emit = noop;
  17858. process.binding = function (name) {
  17859. throw new Error('process.binding is not supported');
  17860. };
  17861. // TODO(shtylman)
  17862. process.cwd = function () { return '/' };
  17863. process.chdir = function (dir) {
  17864. throw new Error('process.chdir is not supported');
  17865. };
  17866. process.umask = function() { return 0; };
  17867. },{}]},{},[7])(7)
  17868. });