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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150
  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 EventEmitter = require("events");
  6. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  7. /**
  8. * Creates a JitsiConference object with the given name and properties.
  9. * Note: this constructor is not a part of the public API (objects should be
  10. * created using JitsiConnection.createConference).
  11. * @param options.config properties / settings related to the conference that will be created.
  12. * @param options.name the name of the conference
  13. * @param options.connection the JitsiConnection object for this JitsiConference.
  14. * @constructor
  15. */
  16. function JitsiConference(options) {
  17. this.options = options;
  18. this.connection = this.options.connection;
  19. this.xmpp = this.connection.xmpp;
  20. this.eventEmitter = new EventEmitter();
  21. this.room = this.xmpp.createRoom(this.options.name, null, null, this.options.config);
  22. this.rtc = new RTC(this.room, options);
  23. setupListeners(this);
  24. }
  25. /**
  26. * Joins the conference.
  27. * @param password {string} the password
  28. */
  29. JitsiConference.prototype.join = function (password) {
  30. this.room.join(password);
  31. }
  32. /**
  33. * Leaves the conference.
  34. */
  35. JitsiConference.prototype.leave = function () {
  36. this.xmpp.leaveRoom(room.roomjid);
  37. this.room = null;
  38. }
  39. /**
  40. * Creates the media tracks and returns them via the callback.
  41. * @param options Object with properties / settings specifying the tracks which should be created.
  42. * should be created or some additional configurations about resolution for example.
  43. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  44. * or a JitsiConferenceError if rejected.
  45. */
  46. JitsiConference.prototype.createLocalTracks = function (options) {
  47. return this.rtc.obtainAudioAndVideoPermissions(options || {});
  48. }
  49. /**
  50. * Returns the local tracks.
  51. */
  52. JitsiConference.prototype.getLocalTracks = function () {
  53. return this.rtc.localStreams;
  54. };
  55. /**
  56. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  57. * in JitsiConferenceEvents.
  58. * @param eventId the event ID.
  59. * @param handler handler for the event.
  60. *
  61. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  62. */
  63. JitsiConference.prototype.on = function (eventId, handler) {
  64. this.eventEmitter.on(eventId, handler);
  65. }
  66. /**
  67. * Removes event listener
  68. * @param eventId the event ID.
  69. * @param [handler] optional, the specific handler to unbind
  70. *
  71. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  72. */
  73. JitsiConference.prototype.off = function (eventId, handler) {
  74. this.eventEmitter.removeListener(eventId, listener);
  75. }
  76. // Common aliases for event emitter
  77. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  78. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  79. /**
  80. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  81. * @param command {String} the name of the command
  82. * @param handler {Function} handler for the command
  83. */
  84. JitsiConference.prototype.addCommandListener = function (command, handler) {
  85. this.room.addPresenceListener(command, handler);
  86. }
  87. /**
  88. * Removes command listener
  89. * @param command {String} the name of the command
  90. */
  91. JitsiConference.prototype.removeCommandListener = function (command) {
  92. this.room.removePresenceListener(command);
  93. }
  94. /**
  95. * Sends text message to the other participants in the conference
  96. * @param message the text message.
  97. */
  98. JitsiConference.prototype.sendTextMessage = function (message) {
  99. this.room.sendMessage(message);
  100. }
  101. /**
  102. * Send presence command.
  103. * @param name the name of the command.
  104. * @param values Object with keys and values that will be send.
  105. **/
  106. JitsiConference.prototype.sendCommand = function (name, values) {
  107. this.room.addToPresence(name, values);
  108. this.room.sendPresence();
  109. }
  110. /**
  111. * Send presence command one time.
  112. * @param name the name of the command.
  113. * @param values Object with keys and values that will be send.
  114. **/
  115. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  116. this.sendCommand(name, values);
  117. this.removeCommand(name);
  118. }
  119. /**
  120. * Send presence command.
  121. * @param name the name of the command.
  122. * @param values Object with keys and values that will be send.
  123. * @param persistent if false the command will be sent only one time
  124. **/
  125. JitsiConference.prototype.removeCommand = function (name) {
  126. this.room.removeFromPresence(name);
  127. }
  128. /**
  129. * Sets the display name for this conference.
  130. * @param name the display name to set
  131. */
  132. JitsiConference.prototype.setDisplayName = function(name) {
  133. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  134. }
  135. /**
  136. * Elects the participant with the given id to be the selected participant or the speaker.
  137. * @param id the identifier of the participant
  138. */
  139. JitsiConference.prototype.selectParticipant = function(participantId) {
  140. this.rtc.selectedEndpoint(participantId);
  141. }
  142. /**
  143. *
  144. * @param id the identifier of the participant
  145. */
  146. JitsiConference.prototype.pinParticipant = function(participantId) {
  147. this.rtc.pinEndpoint(participantId);
  148. }
  149. /**
  150. * Returns the list of participants for this conference.
  151. * @return Object a list of participant identifiers containing all conference participants.
  152. */
  153. JitsiConference.prototype.getParticipants = function() {
  154. }
  155. /**
  156. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  157. * null if there isn't one).
  158. * @param id the id of the participant.
  159. */
  160. JitsiConference.prototype.getParticipantById = function(id) {
  161. }
  162. function setupListeners(conference) {
  163. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING,
  164. conference.rtc.onIncommingCall.bind(conference.rtc));
  165. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  166. conference.rtc.createRemoteStream.bind(conference.rtc));
  167. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, function (stream) {
  168. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, stream);
  169. });
  170. conference.rtc.addListener(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, function (stream) {
  171. conference.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, stream);
  172. })
  173. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  174. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  175. })
  176. }
  177. module.exports = JitsiConference;
  178. },{"./JitsiConferenceEvents":3,"./modules/RTC/RTC":12,"./service/RTC/StreamEventTypes":72,"./service/xmpp/XMPPEvents":75,"events":76}],2:[function(require,module,exports){
  179. /**
  180. * Enumeration with the errors for the conference.
  181. * @type {{string: string}}
  182. */
  183. var JitsiConferenceErrors = {
  184. /**
  185. * Indicates that a password is required in order to join the conference.
  186. */
  187. PASSWORD_REQUIRED: "conference.passwordRequired",
  188. /**
  189. * Indicates that a connection error occurred when trying to join a conference.
  190. */
  191. CONNECTION_ERROR: "conference.connectionError",
  192. /**
  193. * Indicates that there is no available videobridge.
  194. */
  195. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  196. /**
  197. * Many more errors TBD here.
  198. */
  199. };
  200. module.exports = JitsiConferenceErrors;
  201. },{}],3:[function(require,module,exports){
  202. /**
  203. * Enumeration with the events for the conference.
  204. * @type {{string: string}}
  205. */
  206. var JitsiConferenceEvents = {
  207. /**
  208. * A new media track was added to the conference.
  209. */
  210. TRACK_ADDED: "conference.trackAdded",
  211. /**
  212. * The media track was removed to the conference.
  213. */
  214. TRACK_REMOVED: "conference.trackRemoved",
  215. /**
  216. * The active speaker was changed.
  217. */
  218. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  219. /**
  220. * A new user joinned the conference.
  221. */
  222. USER_JOINED: "conference.userJoined",
  223. /**
  224. * A user has left the conference.
  225. */
  226. USER_LEFT: "conference.userLeft",
  227. /**
  228. * New text message was received.
  229. */
  230. MESSAGE_RECEIVED: "conference.messageReceived",
  231. /**
  232. * A user has changed it display name
  233. */
  234. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  235. /**
  236. * A participant avatar has changed.
  237. */
  238. AVATAR_CHANGED: "conference.avatarChanged",
  239. /**
  240. * New connection statistics are received.
  241. */
  242. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  243. /**
  244. * The Last N set is changed.
  245. */
  246. LAST_N_CHANGED: "conference.lastNChanged",
  247. /**
  248. * A media track was muted.
  249. */
  250. TRACK_MUTED: "conference.trackMuted",
  251. /**
  252. * A media track was unmuted.
  253. */
  254. TRACK_UNMUTED: "conference.trackUnmuted",
  255. /**
  256. * Audio levels of a media track was changed.
  257. */
  258. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  259. /**
  260. * Indicates that the connection to the conference has been interrupted for some reason.
  261. */
  262. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  263. /**
  264. * Indicates that the connection to the conference has been restored.
  265. */
  266. CONNECTION_RESTORED: "conference.connecionRestored",
  267. /**
  268. * Indicates that conference has been joined.
  269. */
  270. CONFERENCE_JOINED: "conference.joined",
  271. /**
  272. * Indicates that conference has been left.
  273. */
  274. CONFERENCE_LEFT: "conference.left"
  275. };
  276. module.exports = JitsiConferenceEvents;
  277. },{}],4:[function(require,module,exports){
  278. var JitsiConference = require("./JitsiConference");
  279. var XMPP = require("./modules/xmpp/xmpp");
  280. /**
  281. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  282. * JitsiConference interface.
  283. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  284. * @param token secret generated by the provider of Jitsi Meet video conferencing services.
  285. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  286. * @param options Object with properties / settings related to connection with the server.
  287. * @constructor
  288. */
  289. function JitsiConnection(appID, token, options) {
  290. this.appID = appID;
  291. this.token = token;
  292. this.options = options;
  293. this.xmpp = new XMPP(options);
  294. this.conferences = {};
  295. }
  296. /**
  297. * Connect the client with the server.
  298. * @param options {object} connecting options (for example authentications parameters).
  299. */
  300. JitsiConnection.prototype.connect = function (options) {
  301. if(!options)
  302. options = {};
  303. this.xmpp.connect(options.id, options.password);
  304. }
  305. /**
  306. * Disconnect the client from the server.
  307. */
  308. JitsiConnection.prototype.disconnect = function () {
  309. this.xmpp.disconnect();
  310. }
  311. /**
  312. * This method allows renewal of the tokens if they are expiring.
  313. * @param token the new token.
  314. */
  315. JitsiConnection.prototype.setToken = function (token) {
  316. this.token = token;
  317. }
  318. /**
  319. * Creates and joins new conference.
  320. * @param name the name of the conference; if null - a generated name will be provided from the api
  321. * @param options Object with properties / settings related to the conference that will be created.
  322. * @returns {JitsiConference} returns the new conference object.
  323. */
  324. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  325. this.conferences[name] = new JitsiConference({name: name, config: options, connection: this});
  326. return this.conferences[name];
  327. }
  328. /**
  329. * Subscribes the passed listener to the event.
  330. * @param event {JitsiConnectionEvents} the connection event.
  331. * @param listener {Function} the function that will receive the event
  332. */
  333. JitsiConnection.prototype.addEventListener = function (event, listener) {
  334. this.xmpp.addListener(event, listener);
  335. }
  336. /**
  337. * Unsubscribes the passed handler.
  338. * @param event {JitsiConnectionEvents} the connection event.
  339. * @param listener {Function} the function that will receive the event
  340. */
  341. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  342. this.xmpp.removeListener(event, listener);
  343. }
  344. module.exports = JitsiConnection;
  345. },{"./JitsiConference":1,"./modules/xmpp/xmpp":32}],5:[function(require,module,exports){
  346. /**
  347. * Enumeration with the errors for the connection.
  348. * @type {{string: string}}
  349. */
  350. var JitsiConnectionErrors = {
  351. /**
  352. * Indicates that a password is required in order to join the conference.
  353. */
  354. PASSWORD_REQUIRED: "connection.passwordRequired",
  355. /**
  356. * Indicates that a connection error occurred when trying to join a conference.
  357. */
  358. CONNECTION_ERROR: "connection.connectionError",
  359. /**
  360. * Not specified errors.
  361. */
  362. OTHER_ERROR: "connection.otherError"
  363. };
  364. module.exports = JitsiConnectionErrors;
  365. },{}],6:[function(require,module,exports){
  366. /**
  367. * Enumeration with the events for the connection.
  368. * @type {{string: string}}
  369. */
  370. var JitsiConnnectionEvents = {
  371. /**
  372. * Indicates that the connection has been failed for some reason.
  373. */
  374. CONNECTION_FAILED: "connection.connecionFailed",
  375. /**
  376. * Indicates that the connection has been established.
  377. */
  378. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  379. /**
  380. * Indicates that the connection has been disconnected.
  381. */
  382. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  383. /**
  384. * Indicates that the perfomed action cannot be executed because the
  385. * connection is not in the correct state(connected, disconnected, etc.)
  386. */
  387. WRONG_STATE: "connection.wrongState"
  388. };
  389. module.exports = JitsiConnnectionEvents;
  390. },{}],7:[function(require,module,exports){
  391. var JitsiConnection = require("./JitsiConnection");
  392. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  393. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  394. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  395. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  396. /**
  397. * Namespace for the interface of Jitsi Meet Library.
  398. */
  399. var LibJitsiMeet = {
  400. JitsiConnection: JitsiConnection,
  401. events: {
  402. conference: JitsiConferenceEvents,
  403. connection: JitsiConnectionEvents
  404. },
  405. errors: {
  406. conference: JitsiConferenceErrors,
  407. connection: JitsiConnectionErrors
  408. },
  409. init: function (options) {
  410. require("./modules/RTC/RTC").init(options || {});
  411. }
  412. }
  413. //Setups the promise object.
  414. window.Promise = window.Promise || require("es6-promise").polyfill();
  415. module.exports = LibJitsiMeet;
  416. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./modules/RTC/RTC":12,"es6-promise":34}],8:[function(require,module,exports){
  417. /* global config, APP, Strophe */
  418. // cache datachannels to avoid garbage collection
  419. // https://code.google.com/p/chromium/issues/detail?id=405545
  420. var RTCEvents = require("../../service/RTC/RTCEvents");
  421. /**
  422. * Binds "ondatachannel" event listener to given PeerConnection instance.
  423. * @param peerConnection WebRTC peer connection instance.
  424. */
  425. function DataChannels(peerConnection, emitter) {
  426. peerConnection.ondatachannel = this.onDataChannel;
  427. this.eventEmitter = emitter;
  428. this._dataChannels = [];
  429. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  430. // Although it's not a requirement to open separate channels from both bridge
  431. // and peer as single channel can be used for sending and receiving data.
  432. // So either channel opened by the bridge or the one opened here is enough
  433. // for communication with the bridge.
  434. /*var dataChannelOptions =
  435. {
  436. reliable: true
  437. };
  438. var dataChannel
  439. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  440. // Can be used only when is in open state
  441. dataChannel.onopen = function ()
  442. {
  443. dataChannel.send("My channel !!!");
  444. };
  445. dataChannel.onmessage = function (event)
  446. {
  447. var msgData = event.data;
  448. console.info("Got My Data Channel Message:", msgData, dataChannel);
  449. };*/
  450. };
  451. /**
  452. * Callback triggered by PeerConnection when new data channel is opened
  453. * on the bridge.
  454. * @param event the event info object.
  455. */
  456. DataChannels.prototype.onDataChannel = function (event) {
  457. var dataChannel = event.channel;
  458. dataChannel.onopen = function () {
  459. console.info("Data channel opened by the Videobridge!", dataChannel);
  460. // Code sample for sending string and/or binary data
  461. // Sends String message to the bridge
  462. //dataChannel.send("Hello bridge!");
  463. // Sends 12 bytes binary message to the bridge
  464. //dataChannel.send(new ArrayBuffer(12));
  465. this.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  466. }.bind(this);
  467. dataChannel.onerror = function (error) {
  468. console.error("Data Channel Error:", error, dataChannel);
  469. };
  470. dataChannel.onmessage = function (event) {
  471. var data = event.data;
  472. // JSON
  473. var obj;
  474. try {
  475. obj = JSON.parse(data);
  476. }
  477. catch (e) {
  478. console.error(
  479. "Failed to parse data channel message as JSON: ",
  480. data,
  481. dataChannel);
  482. }
  483. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  484. var colibriClass = obj.colibriClass;
  485. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  486. // Endpoint ID from the Videobridge.
  487. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  488. console.info(
  489. "Data channel new dominant speaker event: ",
  490. dominantSpeakerEndpoint);
  491. this.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  492. }
  493. else if ("InLastNChangeEvent" === colibriClass) {
  494. var oldValue = obj.oldValue;
  495. var newValue = obj.newValue;
  496. // Make sure that oldValue and newValue are of type boolean.
  497. var type;
  498. if ((type = typeof oldValue) !== 'boolean') {
  499. if (type === 'string') {
  500. oldValue = (oldValue == "true");
  501. } else {
  502. oldValue = new Boolean(oldValue).valueOf();
  503. }
  504. }
  505. if ((type = typeof newValue) !== 'boolean') {
  506. if (type === 'string') {
  507. newValue = (newValue == "true");
  508. } else {
  509. newValue = new Boolean(newValue).valueOf();
  510. }
  511. }
  512. this.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  513. }
  514. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  515. // The new/latest list of last-n endpoint IDs.
  516. var lastNEndpoints = obj.lastNEndpoints;
  517. // The list of endpoint IDs which are entering the list of
  518. // last-n at this time i.e. were not in the old list of last-n
  519. // endpoint IDs.
  520. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  521. console.log(
  522. "Data channel new last-n event: ",
  523. lastNEndpoints, endpointsEnteringLastN, obj);
  524. this.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  525. lastNEndpoints, endpointsEnteringLastN, obj);
  526. }
  527. else {
  528. console.debug("Data channel JSON-formatted message: ", obj);
  529. }
  530. }
  531. }.bind(this);
  532. dataChannel.onclose = function () {
  533. console.info("The Data Channel closed", dataChannel);
  534. var idx = this._dataChannels.indexOf(dataChannel);
  535. if (idx > -1)
  536. this._dataChannels = this._dataChannels.splice(idx, 1);
  537. }.bind(this);
  538. this._dataChannels.push(dataChannel);
  539. };
  540. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  541. console.log('selected endpoint changed: ', userResource);
  542. if (this._dataChannels && this._dataChannels.length != 0) {
  543. this._dataChannels.some(function (dataChannel) {
  544. if (dataChannel.readyState == 'open') {
  545. console.log('sending selected endpoint changed ' +
  546. 'notification to the bridge: ', userResource);
  547. dataChannel.send(JSON.stringify({
  548. 'colibriClass': 'SelectedEndpointChangedEvent',
  549. 'selectedEndpoint':
  550. (!userResource || userResource === null)?
  551. null : userResource
  552. }));
  553. return true;
  554. }
  555. });
  556. }
  557. }
  558. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  559. console.log('pinned endpoint changed: ', userResource);
  560. if (this._dataChannels && this._dataChannels.length != 0) {
  561. this._dataChannels.some(function (dataChannel) {
  562. if (dataChannel.readyState == 'open') {
  563. dataChannel.send(JSON.stringify({
  564. 'colibriClass': 'PinnedEndpointChangedEvent',
  565. 'pinnedEndpoint':
  566. (!userResource || userResource == null)?
  567. null : userResource
  568. }));
  569. return true;
  570. }
  571. });
  572. }
  573. }
  574. module.exports = DataChannels;
  575. },{"../../service/RTC/RTCEvents":70}],9:[function(require,module,exports){
  576. var JitsiTrack = require("./JitsiTrack");
  577. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  578. var RTCEvents = require("../../service/RTC/RTCEvents");
  579. var RTCBrowserType = require("./RTCBrowserType");
  580. /**
  581. * This implements 'onended' callback normally fired by WebRTC after the stream
  582. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  583. * @param stream original WebRTC stream object to which 'onended' handling
  584. * will be added.
  585. */
  586. function implementOnEndedHandling(stream) {
  587. var originalStop = stream.stop;
  588. stream.stop = function () {
  589. originalStop.apply(stream);
  590. if (!stream.ended) {
  591. stream.ended = true;
  592. stream.onended();
  593. }
  594. };
  595. }
  596. /**
  597. * Represents a single media track (either audio or video).
  598. * @constructor
  599. */
  600. function JitsiLocalTrack(RTC, stream, eventEmitter, videoType, isGUMStream)
  601. {
  602. JitsiTrack.call(this, RTC, stream);
  603. this.eventEmitter = eventEmitter;
  604. this.videoType = videoType;
  605. this.isGUMStream = true;
  606. if(isGUMStream === false)
  607. this.isGUMStream = isGUMStream;
  608. this.stream.onended = function () {
  609. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  610. }.bind(this);
  611. if (RTCBrowserType.isFirefox()) {
  612. implementOnEndedHandling(this.stream);
  613. }
  614. }
  615. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  616. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  617. /**
  618. * Mutes / unmutes the track.
  619. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  620. */
  621. JitsiLocalTrack.prototype._setMute = function (mute) {
  622. var isAudio = this.type === JitsiTrack.AUDIO;
  623. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  624. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  625. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  626. // FIXME FF does not support 'removeStream' method used to mute
  627. RTCBrowserType.isFirefox()) {
  628. var tracks = this.getTracks();
  629. for (var idx = 0; idx < tracks.length; idx++) {
  630. tracks[idx].enabled = !mute;
  631. }
  632. if(isAudio)
  633. this.rtc.room.setAudioMute(mute);
  634. else
  635. this.rtc.room.setVideoMute(mute);
  636. this.eventEmitter.emit(eventType, mute);
  637. } else {
  638. if (mute) {
  639. this.rtc.room.removeStream(this.stream);
  640. this.stream.stop();
  641. if(isAudio)
  642. this.rtc.room.setAudioMute(mute);
  643. else
  644. this.rtc.room.setVideoMute(mute);
  645. this.eventEmitter.emit(eventType, true);
  646. } else {
  647. var self = this;
  648. this.rtc.obtainAudioAndVideoPermissions(
  649. {devices: (this.isAudioStream() ? ["audio"] : ["video"])})
  650. .then(function (stream) {
  651. if (isAudio) {
  652. self.rtc.changeLocalAudio(stream,
  653. function () {
  654. this.rtc.room.setAudioMute(mute);
  655. self.eventEmitter.emit(eventType, false);
  656. });
  657. } else {
  658. self.rtc.changeLocalVideo(stream, false,
  659. function () {
  660. this.rtc.room.setVideoMute(mute);
  661. self.eventEmitter.emit(eventType, false);
  662. });
  663. }
  664. });
  665. }
  666. }
  667. }
  668. /**
  669. * Stops sending the media track. And removes it from the HTML.
  670. * NOTE: Works for local tracks only.
  671. */
  672. JitsiLocalTrack.prototype.stop = function () {
  673. this.rtc.room.removeStream(this.stream);
  674. this.stream.stop();
  675. this.detach();
  676. }
  677. /**
  678. * Starts sending the track.
  679. * NOTE: Works for local tracks only.
  680. */
  681. JitsiLocalTrack.prototype.start = function() {
  682. this.rtc.room.addStream(this.stream, function () {});
  683. }
  684. module.exports = JitsiLocalTrack;
  685. },{"../../service/RTC/RTCEvents":70,"../../service/RTC/StreamEventTypes":72,"./JitsiTrack":11,"./RTCBrowserType":13}],10:[function(require,module,exports){
  686. var JitsiTrack = require("./JitsiTrack");
  687. /**
  688. * Represents a single media track (either audio or video).
  689. * @constructor
  690. */
  691. function JitsiRemoteTrack(RTC, data, sid, ssrc, browser, eventEmitter) {
  692. JitsiTrack.call(this, RTC, data.stream);
  693. this.rtc = RTC;
  694. this.sid = sid;
  695. this.stream = data.stream;
  696. this.peerjid = data.peerjid;
  697. this.videoType = data.videoType;
  698. this.ssrc = ssrc;
  699. this.muted = false;
  700. this.eventEmitter = eventEmitter;
  701. }
  702. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  703. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  704. JitsiRemoteTrack.prototype._setMute = function (value) {
  705. this.stream.muted = value;
  706. this.muted = value;
  707. };
  708. delete JitsiRemoteTrack.prototype.stop;
  709. delete JitsiRemoteTrack.prototype.start;
  710. module.exports = JitsiRemoteTrack;
  711. },{"./JitsiTrack":11}],11:[function(require,module,exports){
  712. var RTC = require("./RTCUtils");
  713. /**
  714. * Represents a single media track (either audio or video).
  715. * @constructor
  716. */
  717. function JitsiTrack(RTC, stream)
  718. {
  719. this.rtc = RTC;
  720. this.stream = stream;
  721. this.type = (this.stream.getVideoTracks().length > 0)?
  722. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  723. if(this.type == "audio") {
  724. this._getTracks = function () {
  725. return this.stream.getAudioTracks();
  726. }.bind(this);
  727. } else {
  728. this._getTracks = function () {
  729. return this.stream.getVideoTracks();
  730. }.bind(this);
  731. }
  732. }
  733. /**
  734. * JitsiTrack video type.
  735. * @type {string}
  736. */
  737. JitsiTrack.VIDEO = "video";
  738. /**
  739. * JitsiTrack audio type.
  740. * @type {string}
  741. */
  742. JitsiTrack.AUDIO = "audio";
  743. /**
  744. * Returns the type (audio or video) of this track.
  745. */
  746. JitsiTrack.prototype.getType = function() {
  747. return this.type;
  748. };
  749. /**
  750. * @returns {JitsiParticipant} to which this track belongs, or null if it is a local track.
  751. */
  752. JitsiTrack.prototype.getParitcipant = function() {
  753. };
  754. /**
  755. * Returns the RTCMediaStream from the browser (?).
  756. */
  757. JitsiTrack.prototype.getOriginalStream = function() {
  758. return this.stream;
  759. }
  760. /**
  761. * Mutes the track.
  762. */
  763. JitsiTrack.prototype.mute = function () {
  764. this._setMute(true);
  765. }
  766. /**
  767. * Unmutes the stream.
  768. */
  769. JitsiTrack.prototype.unmute = function () {
  770. this._setMute(false);
  771. }
  772. /**
  773. * Attaches the MediaStream of this track to an HTML container (?).
  774. * @param container the HTML container
  775. */
  776. JitsiTrack.prototype.attach = function (container) {
  777. RTC.attachMediaStream(container, this.stream);
  778. }
  779. /**
  780. * Removes the track from the passed HTML container.
  781. * @param container the HTML container
  782. */
  783. JitsiTrack.prototype.detach = function (container) {
  784. $(container).find(">video").remove();
  785. }
  786. /**
  787. * Stops sending the media track. And removes it from the HTML.
  788. * NOTE: Works for local tracks only.
  789. */
  790. JitsiTrack.prototype.stop = function () {
  791. this.detach();
  792. }
  793. /**
  794. * Starts sending the track.
  795. * NOTE: Works for local tracks only.
  796. */
  797. JitsiTrack.prototype.start = function() {
  798. }
  799. /**
  800. * Returns true if this is a video track and the source of the video is a
  801. * screen capture as opposed to a camera.
  802. */
  803. JitsiTrack.prototype.isScreenSharing = function(){
  804. }
  805. /**
  806. * Returns id of the track.
  807. * @returns {string} id of the track or null if this is fake track.
  808. */
  809. JitsiTrack.prototype.getId = function () {
  810. var tracks = this.stream.getTracks();
  811. if(!tracks || tracks.length === 0)
  812. return null;
  813. return tracks[0].id;
  814. };
  815. module.exports = JitsiTrack;
  816. },{"./RTCUtils":14}],12:[function(require,module,exports){
  817. /* global APP */
  818. var EventEmitter = require("events");
  819. var RTCBrowserType = require("./RTCBrowserType");
  820. var RTCUtils = require("./RTCUtils.js");
  821. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  822. var DataChannels = require("./DataChannels");
  823. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  824. var DesktopSharingEventTypes
  825. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  826. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  827. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  828. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  829. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  830. var desktopsharing = require("../desktopsharing/desktopsharing");
  831. function getMediaStreamUsage()
  832. {
  833. var result = {
  834. audio: true,
  835. video: true
  836. };
  837. /** There are some issues with the desktop sharing
  838. * when this property is enabled.
  839. * WARNING: We must change the implementation to start video/audio if we
  840. * receive from the focus that the peer is not muted.
  841. var isSecureConnection = window.location.protocol == "https:";
  842. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  843. {
  844. result = {
  845. audio: false,
  846. video: false
  847. };
  848. }
  849. **/
  850. return result;
  851. }
  852. var rtcReady = false;
  853. function RTC(room, options) {
  854. this.devices = {
  855. audio: true,
  856. video: true
  857. };
  858. this.room = room;
  859. this.localStreams = [];
  860. this.remoteStreams = {};
  861. this.localAudio = null;
  862. this.localVideo = null;
  863. this.eventEmitter = new EventEmitter();
  864. var self = this;
  865. this.options = options || {};
  866. desktopsharing.addListener(
  867. function (stream, isUsingScreenStream, callback) {
  868. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  869. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  870. }
  871. RTC.prototype.obtainAudioAndVideoPermissions = function (options) {
  872. return RTCUtils.obtainAudioAndVideoPermissions(this,
  873. options.devices, getMediaStreamUsage(), options.resolution);
  874. }
  875. RTC.prototype.onIncommingCall = function(event) {
  876. if(this.options.config.openSctp)
  877. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  878. this.room.addLocalStreams(this.localStreams);
  879. }
  880. RTC.prototype.selectedEndpoint = function (id) {
  881. if(this.dataChannels)
  882. this.dataChannels.handleSelectedEndpointEvent(id);
  883. }
  884. RTC.prototype.pinEndpoint = function (id) {
  885. if(this.dataChannels)
  886. this.dataChannels.handlePinnedEndpointEvent(id);
  887. }
  888. RTC.prototype.addStreamListener = function (listener, eventType) {
  889. this.eventEmitter.on(eventType, listener);
  890. };
  891. RTC.prototype.addListener = function (type, listener) {
  892. this.eventEmitter.on(type, listener);
  893. };
  894. RTC.prototype.removeListener = function (listener, eventType) {
  895. this.eventEmitter.removeListener(eventType, listener);
  896. };
  897. RTC.prototype.removeStreamListener = function (listener, eventType) {
  898. if(!(eventType instanceof StreamEventTypes))
  899. throw "Illegal argument";
  900. this.eventEmitter.removeListener(eventType, listener);
  901. };
  902. RTC.addRTCReadyListener = function (listener) {
  903. RTCUtils.eventEmitter.on(RTCEvents.RTC_READY, listener);
  904. }
  905. RTC.removeRTCReadyListener = function (listener) {
  906. RTCUtils.eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  907. }
  908. RTC.isRTCReady = function () {
  909. return rtcReady;
  910. }
  911. RTC.init = function (options) {
  912. // In case of IE we continue from 'onReady' callback
  913. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  914. // once it is initialized.
  915. var onReady = function () {
  916. rtcReady = true;
  917. RTCUtils.eventEmitter.emit(RTCEvents.RTC_READY, true);
  918. };
  919. RTCUtils.init(onReady, options || {});
  920. // Call onReady() if Temasys plugin is not used
  921. if (!RTCBrowserType.isTemasysPluginUsed()) {
  922. onReady();
  923. }
  924. }
  925. RTC.prototype.createLocalStreams = function (streams, change) {
  926. for (var i = 0; i < streams.length; i++) {
  927. var localStream = new JitsiLocalTrack(this, streams[i].stream,
  928. this.eventEmitter, streams[i].videoType,
  929. streams[i].isGUMStream);
  930. this.localStreams.push(localStream);
  931. if (streams[i].isMuted === true)
  932. localStream.setMute(true);
  933. if (streams[i].type == "audio") {
  934. this.localAudio = localStream;
  935. } else {
  936. this.localVideo = localStream;
  937. }
  938. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  939. if (change)
  940. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  941. this.eventEmitter.emit(eventType, localStream, streams[i].isMuted);
  942. }
  943. return this.localStreams;
  944. };
  945. RTC.prototype.removeLocalStream = function (stream) {
  946. for(var i = 0; i < this.localStreams.length; i++) {
  947. if(this.localStreams[i].getOriginalStream() === stream) {
  948. delete this.localStreams[i];
  949. return;
  950. }
  951. }
  952. };
  953. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  954. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc,
  955. RTCBrowserType.getBrowserType(), this.eventEmitter);
  956. if(!data.peerjid)
  957. return;
  958. var jid = data.peerjid;
  959. if(!this.remoteStreams[jid]) {
  960. this.remoteStreams[jid] = {};
  961. }
  962. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  963. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  964. return remoteStream;
  965. };
  966. RTC.getPCConstraints = function () {
  967. return RTCUtils.pc_constraints;
  968. };
  969. RTC.prototype.getUserMediaWithConstraints = function(um, success_callback,
  970. failure_callback, resolution,
  971. bandwidth, fps, desktopStream)
  972. {
  973. return RTCUtils.getUserMediaWithConstraints(this, um, success_callback,
  974. failure_callback, resolution, bandwidth, fps, desktopStream);
  975. };
  976. RTC.attachMediaStream = function (elSelector, stream) {
  977. RTCUtils.attachMediaStream(elSelector, stream);
  978. };
  979. RTC.getStreamID = function (stream) {
  980. return RTCUtils.getStreamID(stream);
  981. };
  982. RTC.getVideoSrc = function (element) {
  983. return RTCUtils.getVideoSrc(element);
  984. };
  985. RTC.setVideoSrc = function (element, src) {
  986. RTCUtils.setVideoSrc(element, src);
  987. };
  988. RTC.prototype.getVideoElementName = function () {
  989. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  990. };
  991. RTC.prototype.dispose = function() {
  992. };
  993. RTC.prototype.muteRemoteVideoStream = function (jid, value) {
  994. var stream;
  995. if(this.remoteStreams[jid] &&
  996. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  997. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  998. }
  999. if(!stream)
  1000. return true;
  1001. if (value != stream.muted) {
  1002. stream.setMute(value);
  1003. return true;
  1004. }
  1005. return false;
  1006. };
  1007. RTC.prototype.switchVideoStreams = function (new_stream) {
  1008. this.localVideo.stream = new_stream;
  1009. this.localStreams = [];
  1010. //in firefox we have only one stream object
  1011. if (this.localAudio.getOriginalStream() != new_stream)
  1012. this.localStreams.push(this.localAudio);
  1013. this.localStreams.push(this.localVideo);
  1014. };
  1015. RTC.prototype.changeLocalVideo = function (stream, isUsingScreenStream, callback) {
  1016. var oldStream = this.localVideo.getOriginalStream();
  1017. var type = (isUsingScreenStream ? "screen" : "camera");
  1018. var localCallback = callback;
  1019. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1020. localCallback = function() {
  1021. this.room.setVideoMute(false, function(mute) {
  1022. this.eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1023. }.bind(this));
  1024. callback();
  1025. };
  1026. }
  1027. // FIXME: Workaround for FF/IE/Safari
  1028. if (stream && stream.videoStream) {
  1029. stream = stream.videoStream;
  1030. }
  1031. var videoStream = RTCUtils.createStream(stream, true);
  1032. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1033. // Stop the stream to trigger onended event for old stream
  1034. oldStream.stop();
  1035. this.switchVideoStreams(videoStream, oldStream);
  1036. this.room.switchStreams(videoStream, oldStream,localCallback);
  1037. };
  1038. RTC.prototype.changeLocalAudio = function (stream, callback) {
  1039. var oldStream = this.localAudio.getOriginalStream();
  1040. var newStream = RTCUtils.createStream(stream);
  1041. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1042. // Stop the stream to trigger onended event for old stream
  1043. oldStream.stop();
  1044. this.room.switchStreams(newStream, oldStream, callback, true);
  1045. };
  1046. RTC.prototype.isVideoMuted = function (jid) {
  1047. if (jid === APP.xmpp.myJid()) {
  1048. var localVideo = APP.RTC.localVideo;
  1049. return (!localVideo || localVideo.isMuted());
  1050. } else {
  1051. if (!this.remoteStreams[jid] ||
  1052. !this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1053. return null;
  1054. }
  1055. return this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1056. }
  1057. };
  1058. RTC.prototype.setVideoMute = function (mute, callback, options) {
  1059. if (!this.localVideo)
  1060. return;
  1061. if (mute == this.localVideo.isMuted())
  1062. {
  1063. APP.xmpp.sendVideoInfoPresence(mute);
  1064. if (callback)
  1065. callback(mute);
  1066. }
  1067. else
  1068. {
  1069. this.localVideo.setMute(mute);
  1070. this.room.setVideoMute(
  1071. mute,
  1072. callback,
  1073. options);
  1074. }
  1075. };
  1076. RTC.prototype.setDeviceAvailability = function (devices) {
  1077. if(!devices)
  1078. return;
  1079. if(devices.audio === true || devices.audio === false)
  1080. this.devices.audio = devices.audio;
  1081. if(devices.video === true || devices.video === false)
  1082. this.devices.video = devices.video;
  1083. this.eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1084. };
  1085. module.exports = RTC;
  1086. },{"../../service/RTC/MediaStreamTypes":69,"../../service/RTC/RTCEvents.js":70,"../../service/RTC/StreamEventTypes.js":72,"../../service/desktopsharing/DesktopSharingEventTypes":74,"../../service/xmpp/XMPPEvents":75,"../desktopsharing/desktopsharing":16,"./DataChannels":8,"./JitsiLocalTrack.js":9,"./JitsiRemoteTrack.js":10,"./RTCBrowserType":13,"./RTCUtils.js":14,"events":76}],13:[function(require,module,exports){
  1087. var currentBrowser;
  1088. var browserVersion;
  1089. var RTCBrowserType = {
  1090. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1091. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1092. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1093. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1094. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1095. getBrowserType: function () {
  1096. return currentBrowser;
  1097. },
  1098. isChrome: function () {
  1099. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1100. },
  1101. isOpera: function () {
  1102. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1103. },
  1104. isFirefox: function () {
  1105. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1106. },
  1107. isIExplorer: function () {
  1108. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1109. },
  1110. isSafari: function () {
  1111. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1112. },
  1113. isTemasysPluginUsed: function () {
  1114. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1115. },
  1116. getFirefoxVersion: function () {
  1117. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1118. },
  1119. getChromeVersion: function () {
  1120. return RTCBrowserType.isChrome() ? browserVersion : null;
  1121. },
  1122. usesPlanB: function() {
  1123. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1124. RTCBrowserType.isTemasysPluginUsed();
  1125. },
  1126. usesUnifiedPlan: function() {
  1127. return RTCBrowserType.isFirefox();
  1128. }
  1129. // Add version getters for other browsers when needed
  1130. };
  1131. // detectOpera() must be called before detectChrome() !!!
  1132. // otherwise Opera wil be detected as Chrome
  1133. function detectChrome() {
  1134. if (navigator.webkitGetUserMedia) {
  1135. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1136. var userAgent = navigator.userAgent.toLowerCase();
  1137. // We can assume that user agent is chrome, because it's
  1138. // enforced when 'ext' streaming method is set
  1139. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1140. console.log("This appears to be Chrome, ver: " + ver);
  1141. return ver;
  1142. }
  1143. return null;
  1144. }
  1145. function detectOpera() {
  1146. var userAgent = navigator.userAgent;
  1147. if (userAgent.match(/Opera|OPR/)) {
  1148. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1149. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1150. console.info("This appears to be Opera, ver: " + version);
  1151. return version;
  1152. }
  1153. return null;
  1154. }
  1155. function detectFirefox() {
  1156. if (navigator.mozGetUserMedia) {
  1157. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1158. var version = parseInt(
  1159. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1160. console.log('This appears to be Firefox, ver: ' + version);
  1161. return version;
  1162. }
  1163. return null;
  1164. }
  1165. function detectSafari() {
  1166. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1167. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1168. console.info("This appears to be Safari");
  1169. // FIXME detect Safari version when needed
  1170. return 1;
  1171. }
  1172. return null;
  1173. }
  1174. function detectIE() {
  1175. var version;
  1176. var ua = window.navigator.userAgent;
  1177. var msie = ua.indexOf('MSIE ');
  1178. if (msie > 0) {
  1179. // IE 10 or older => return version number
  1180. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1181. }
  1182. var trident = ua.indexOf('Trident/');
  1183. if (!version && trident > 0) {
  1184. // IE 11 => return version number
  1185. var rv = ua.indexOf('rv:');
  1186. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1187. }
  1188. var edge = ua.indexOf('Edge/');
  1189. if (!version && edge > 0) {
  1190. // IE 12 => return version number
  1191. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1192. }
  1193. if (version) {
  1194. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1195. console.info("This appears to be IExplorer, ver: " + version);
  1196. }
  1197. return version;
  1198. }
  1199. function detectBrowser() {
  1200. var version;
  1201. var detectors = [
  1202. detectOpera,
  1203. detectChrome,
  1204. detectFirefox,
  1205. detectIE,
  1206. detectSafari
  1207. ];
  1208. // Try all browser detectors
  1209. for (var i = 0; i < detectors.length; i++) {
  1210. version = detectors[i]();
  1211. if (version)
  1212. return version;
  1213. }
  1214. console.error("Failed to detect browser type");
  1215. return undefined;
  1216. }
  1217. browserVersion = detectBrowser();
  1218. module.exports = RTCBrowserType;
  1219. },{}],14:[function(require,module,exports){
  1220. /* global config, require, attachMediaStream, getUserMedia */
  1221. var RTCBrowserType = require("./RTCBrowserType");
  1222. var Resolutions = require("../../service/RTC/Resolutions");
  1223. var AdapterJS = require("./adapter.screenshare");
  1224. var SDPUtil = require("../xmpp/SDPUtil");
  1225. var EventEmitter = require("events");
  1226. function DummyMediaStream(id) {
  1227. this.id = id;
  1228. this.label = id;
  1229. this.stop = function() { };
  1230. this.getAudioTracks = function() { return []; };
  1231. this.getVideoTracks = function() { return []; };
  1232. }
  1233. function getPreviousResolution(resolution) {
  1234. if(!Resolutions[resolution])
  1235. return null;
  1236. var order = Resolutions[resolution].order;
  1237. var res = null;
  1238. var resName = null;
  1239. for(var i in Resolutions) {
  1240. var tmp = Resolutions[i];
  1241. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1242. resName = i;
  1243. res = tmp;
  1244. }
  1245. }
  1246. return resName;
  1247. }
  1248. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1249. if (Resolutions[resolution]) {
  1250. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1251. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1252. }
  1253. else if (isAndroid) {
  1254. // FIXME can't remember if the purpose of this was to always request
  1255. // low resolution on Android ? if yes it should be moved up front
  1256. constraints.video.mandatory.minWidth = 320;
  1257. constraints.video.mandatory.minHeight = 240;
  1258. constraints.video.mandatory.maxFrameRate = 15;
  1259. }
  1260. if (constraints.video.mandatory.minWidth)
  1261. constraints.video.mandatory.maxWidth =
  1262. constraints.video.mandatory.minWidth;
  1263. if (constraints.video.mandatory.minHeight)
  1264. constraints.video.mandatory.maxHeight =
  1265. constraints.video.mandatory.minHeight;
  1266. }
  1267. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1268. {
  1269. var constraints = {audio: false, video: false};
  1270. if (um.indexOf('video') >= 0) {
  1271. // same behaviour as true
  1272. constraints.video = { mandatory: {}, optional: [] };
  1273. constraints.video.optional.push({ googLeakyBucket: true });
  1274. setResolutionConstraints(constraints, resolution, isAndroid);
  1275. }
  1276. if (um.indexOf('audio') >= 0) {
  1277. if (!RTCBrowserType.isFirefox()) {
  1278. // same behaviour as true
  1279. constraints.audio = { mandatory: {}, optional: []};
  1280. // if it is good enough for hangouts...
  1281. constraints.audio.optional.push(
  1282. {googEchoCancellation: true},
  1283. {googAutoGainControl: true},
  1284. {googNoiseSupression: true},
  1285. {googHighpassFilter: true},
  1286. {googNoisesuppression2: true},
  1287. {googEchoCancellation2: true},
  1288. {googAutoGainControl2: true}
  1289. );
  1290. } else {
  1291. constraints.audio = true;
  1292. }
  1293. }
  1294. if (um.indexOf('screen') >= 0) {
  1295. if (RTCBrowserType.isChrome()) {
  1296. constraints.video = {
  1297. mandatory: {
  1298. chromeMediaSource: "screen",
  1299. googLeakyBucket: true,
  1300. maxWidth: window.screen.width,
  1301. maxHeight: window.screen.height,
  1302. maxFrameRate: 3
  1303. },
  1304. optional: []
  1305. };
  1306. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1307. constraints.video = {
  1308. optional: [
  1309. {
  1310. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1311. }
  1312. ]
  1313. };
  1314. } else {
  1315. console.error(
  1316. "'screen' WebRTC media source is supported only in Chrome" +
  1317. " and with Temasys plugin");
  1318. }
  1319. }
  1320. if (um.indexOf('desktop') >= 0) {
  1321. constraints.video = {
  1322. mandatory: {
  1323. chromeMediaSource: "desktop",
  1324. chromeMediaSourceId: desktopStream,
  1325. googLeakyBucket: true,
  1326. maxWidth: window.screen.width,
  1327. maxHeight: window.screen.height,
  1328. maxFrameRate: 3
  1329. },
  1330. optional: []
  1331. };
  1332. }
  1333. if (bandwidth) {
  1334. if (!constraints.video) {
  1335. //same behaviour as true
  1336. constraints.video = {mandatory: {}, optional: []};
  1337. }
  1338. constraints.video.optional.push({bandwidth: bandwidth});
  1339. }
  1340. if (fps) {
  1341. // for some cameras it might be necessary to request 30fps
  1342. // so they choose 30fps mjpg over 10fps yuy2
  1343. if (!constraints.video) {
  1344. // same behaviour as true;
  1345. constraints.video = {mandatory: {}, optional: []};
  1346. }
  1347. constraints.video.mandatory.minFrameRate = fps;
  1348. }
  1349. return constraints;
  1350. }
  1351. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1352. var RTCUtils = {
  1353. eventEmitter: new EventEmitter(),
  1354. init: function (onTemasysPluginReady, options) {
  1355. var self = this;
  1356. if (RTCBrowserType.isFirefox()) {
  1357. var FFversion = RTCBrowserType.getFirefoxVersion();
  1358. if (FFversion >= 40) {
  1359. this.peerconnection = mozRTCPeerConnection;
  1360. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1361. this.pc_constraints = {};
  1362. this.attachMediaStream = function (element, stream) {
  1363. // srcObject is being standardized and FF will eventually
  1364. // support that unprefixed. FF also supports the
  1365. // "element.src = URL.createObjectURL(...)" combo, but that
  1366. // will be deprecated in favour of srcObject.
  1367. //
  1368. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1369. // https://github.com/webrtc/samples/issues/302
  1370. if (!element[0])
  1371. return;
  1372. element[0].mozSrcObject = stream;
  1373. element[0].play();
  1374. };
  1375. this.getStreamID = function (stream) {
  1376. var id = stream.id;
  1377. if (!id) {
  1378. var tracks = stream.getVideoTracks();
  1379. if (!tracks || tracks.length === 0) {
  1380. tracks = stream.getAudioTracks();
  1381. }
  1382. id = tracks[0].id;
  1383. }
  1384. return SDPUtil.filter_special_chars(id);
  1385. };
  1386. this.getVideoSrc = function (element) {
  1387. if (!element)
  1388. return null;
  1389. return element.mozSrcObject;
  1390. };
  1391. this.setVideoSrc = function (element, src) {
  1392. if (element)
  1393. element.mozSrcObject = src;
  1394. };
  1395. RTCSessionDescription = mozRTCSessionDescription;
  1396. RTCIceCandidate = mozRTCIceCandidate;
  1397. } else {
  1398. console.error(
  1399. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1400. window.location.href = 'unsupported_browser.html';
  1401. return;
  1402. }
  1403. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1404. this.peerconnection = webkitRTCPeerConnection;
  1405. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1406. this.attachMediaStream = function (element, stream) {
  1407. element.attr('src', webkitURL.createObjectURL(stream));
  1408. };
  1409. this.getStreamID = function (stream) {
  1410. // streams from FF endpoints have the characters '{' and '}'
  1411. // that make jQuery choke.
  1412. return SDPUtil.filter_special_chars(stream.id);
  1413. };
  1414. this.getVideoSrc = function (element) {
  1415. if (!element)
  1416. return null;
  1417. return element.getAttribute("src");
  1418. };
  1419. this.setVideoSrc = function (element, src) {
  1420. if (element)
  1421. element.setAttribute("src", src);
  1422. };
  1423. // DTLS should now be enabled by default but..
  1424. this.pc_constraints = {'optional': [
  1425. {'DtlsSrtpKeyAgreement': 'true'}
  1426. ]};
  1427. if (options.useIPv6) {
  1428. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1429. this.pc_constraints.optional.push({googIPv6: true});
  1430. }
  1431. if (navigator.userAgent.indexOf('Android') != -1) {
  1432. this.pc_constraints = {}; // disable DTLS on Android
  1433. }
  1434. if (!webkitMediaStream.prototype.getVideoTracks) {
  1435. webkitMediaStream.prototype.getVideoTracks = function () {
  1436. return this.videoTracks;
  1437. };
  1438. }
  1439. if (!webkitMediaStream.prototype.getAudioTracks) {
  1440. webkitMediaStream.prototype.getAudioTracks = function () {
  1441. return this.audioTracks;
  1442. };
  1443. }
  1444. }
  1445. // Detect IE/Safari
  1446. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1447. //AdapterJS.WebRTCPlugin.setLogLevel(
  1448. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1449. AdapterJS.webRTCReady(function (isPlugin) {
  1450. self.peerconnection = RTCPeerConnection;
  1451. self.getUserMedia = getUserMedia;
  1452. self.attachMediaStream = function (elSel, stream) {
  1453. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1454. return;
  1455. }
  1456. attachMediaStream(elSel[0], stream);
  1457. };
  1458. self.getStreamID = function (stream) {
  1459. var id = SDPUtil.filter_special_chars(stream.label);
  1460. return id;
  1461. };
  1462. self.getVideoSrc = function (element) {
  1463. if (!element) {
  1464. console.warn("Attempt to get video SRC of null element");
  1465. return null;
  1466. }
  1467. var children = element.children;
  1468. for (var i = 0; i !== children.length; ++i) {
  1469. if (children[i].name === 'streamId') {
  1470. return children[i].value;
  1471. }
  1472. }
  1473. //console.info(element.id + " SRC: " + src);
  1474. return null;
  1475. };
  1476. self.setVideoSrc = function (element, src) {
  1477. //console.info("Set video src: ", element, src);
  1478. if (!src) {
  1479. console.warn("Not attaching video stream, 'src' is null");
  1480. return;
  1481. }
  1482. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1483. var stream = AdapterJS.WebRTCPlugin.plugin
  1484. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1485. attachMediaStream(element, stream);
  1486. };
  1487. onTemasysPluginReady(isPlugin);
  1488. });
  1489. } else {
  1490. try {
  1491. console.log('Browser does not appear to be WebRTC-capable');
  1492. } catch (e) {
  1493. }
  1494. window.location.href = 'unsupported_browser.html';
  1495. }
  1496. },
  1497. getUserMediaWithConstraints: function (RTC, um, success_callback, failure_callback, resolution, bandwidth, fps, desktopStream) {
  1498. // Check if we are running on Android device
  1499. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1500. var constraints = getConstraints(
  1501. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1502. console.info("Get media constraints", constraints);
  1503. var self = this;
  1504. try {
  1505. this.getUserMedia(constraints,
  1506. function (stream) {
  1507. console.log('onUserMediaSuccess');
  1508. self.setAvailableDevices(RTC, um, true);
  1509. success_callback(stream);
  1510. },
  1511. function (error) {
  1512. self.setAvailableDevices(RTC, um, false);
  1513. console.warn('Failed to get access to local media. Error ',
  1514. error, constraints);
  1515. if (failure_callback) {
  1516. failure_callback(error, resolution);
  1517. }
  1518. });
  1519. } catch (e) {
  1520. console.error('GUM failed: ', e);
  1521. if (failure_callback) {
  1522. failure_callback(e);
  1523. }
  1524. }
  1525. },
  1526. setAvailableDevices: function (RTC, um, available) {
  1527. var devices = {};
  1528. if (um.indexOf("video") != -1) {
  1529. devices.video = available;
  1530. }
  1531. if (um.indexOf("audio") != -1) {
  1532. devices.audio = available;
  1533. }
  1534. RTC.setDeviceAvailability(devices);
  1535. },
  1536. /**
  1537. * We ask for audio and video combined stream in order to get permissions and
  1538. * not to ask twice.
  1539. */
  1540. obtainAudioAndVideoPermissions: function (RTC, devices, usageOptions, resolution) {
  1541. var self = this;
  1542. // Get AV
  1543. return new Promise(function (resolve, reject) {
  1544. var successCallback = function (stream) {
  1545. resolve(self.successCallback(RTC , stream, usageOptions));
  1546. };
  1547. if (!devices)
  1548. devices = ['audio', 'video'];
  1549. var newDevices = [];
  1550. if (usageOptions)
  1551. for (var i = 0; i < devices.length; i++) {
  1552. var device = devices[i];
  1553. if (usageOptions[device] === true)
  1554. newDevices.push(device);
  1555. }
  1556. else
  1557. newDevices = devices;
  1558. if (newDevices.length === 0) {
  1559. successCallback();
  1560. return;
  1561. }
  1562. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1563. // With FF/IE we can't split the stream into audio and video because FF
  1564. // doesn't support media stream constructors. So, we need to get the
  1565. // audio stream separately from the video stream using two distinct GUM
  1566. // calls. Not very user friendly :-( but we don't have many other
  1567. // options neither.
  1568. //
  1569. // Note that we pack those 2 streams in a single object and pass it to
  1570. // the successCallback method.
  1571. var obtainVideo = function (audioStream) {
  1572. self.getUserMediaWithConstraints(
  1573. RTC,
  1574. ['video'],
  1575. function (videoStream) {
  1576. return successCallback({
  1577. audioStream: audioStream,
  1578. videoStream: videoStream
  1579. });
  1580. },
  1581. function (error, resolution) {
  1582. console.error(
  1583. 'failed to obtain video stream - stop', error);
  1584. self.errorCallback(error, resolve, RTC, resolution);
  1585. },
  1586. config.resolution || '360');
  1587. };
  1588. var obtainAudio = function () {
  1589. self.getUserMediaWithConstraints(
  1590. RTC,
  1591. ['audio'],
  1592. function (audioStream) {
  1593. if (newDevices.indexOf('video') !== -1)
  1594. obtainVideo(audioStream);
  1595. },
  1596. function (error) {
  1597. console.error(
  1598. 'failed to obtain audio stream - stop', error);
  1599. self.errorCallback(error, resolve, RTC);
  1600. }
  1601. );
  1602. };
  1603. if (newDevices.indexOf('audio') !== -1) {
  1604. obtainAudio();
  1605. } else {
  1606. obtainVideo(null);
  1607. }
  1608. } else {
  1609. this.getUserMediaWithConstraints(
  1610. RTC,
  1611. newDevices,
  1612. function (stream) {
  1613. successCallback(stream);
  1614. },
  1615. function (error, resolution) {
  1616. self.errorCallback(error, resolve, RTC, resolution);
  1617. },
  1618. resolution || '360');
  1619. }
  1620. }.bind(this));
  1621. },
  1622. successCallback: function (RTC, stream, usageOptions) {
  1623. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1624. // it's an object with two properties: audioStream, videoStream.
  1625. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1626. console.log('got', stream, stream.getAudioTracks().length,
  1627. stream.getVideoTracks().length);
  1628. return this.handleLocalStream(RTC, stream, usageOptions);
  1629. },
  1630. errorCallback: function (error, resolve, RTC, currentResolution) {
  1631. var self = this;
  1632. console.error('failed to obtain audio/video stream - trying audio only', error);
  1633. var resolution = getPreviousResolution(currentResolution);
  1634. if (typeof error == "object" && error.constraintName && error.name
  1635. && (error.name == "ConstraintNotSatisfiedError" ||
  1636. error.name == "OverconstrainedError") &&
  1637. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1638. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1639. && resolution != null) {
  1640. self.getUserMediaWithConstraints(RTC, ['audio', 'video'],
  1641. function (stream) {
  1642. resolve(self.successCallback(RTC, stream));
  1643. }, function (error, resolution) {
  1644. return self.errorCallback(error, resolve, RTC, resolution);
  1645. }, resolution);
  1646. }
  1647. else {
  1648. self.getUserMediaWithConstraints(
  1649. RTC,
  1650. ['audio'],
  1651. function (stream) {
  1652. resolve(self.successCallback(RTC, stream));
  1653. },
  1654. function (error) {
  1655. console.error('failed to obtain audio/video stream - stop',
  1656. error);
  1657. resolve(self.successCallback(RTC, null));
  1658. }
  1659. );
  1660. }
  1661. },
  1662. handleLocalStream: function (service, stream, usageOptions) {
  1663. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1664. // an object with two properties: audioStream, videoStream.
  1665. if (window.webkitMediaStream) {
  1666. audioStream = new webkitMediaStream();
  1667. videoStream = new webkitMediaStream();
  1668. if (stream) {
  1669. var audioTracks = stream.getAudioTracks();
  1670. for (var i = 0; i < audioTracks.length; i++) {
  1671. audioStream.addTrack(audioTracks[i]);
  1672. }
  1673. var videoTracks = stream.getVideoTracks();
  1674. for (i = 0; i < videoTracks.length; i++) {
  1675. videoStream.addTrack(videoTracks[i]);
  1676. }
  1677. }
  1678. }
  1679. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  1680. if (stream && stream.audioStream)
  1681. audioStream = stream.audioStream;
  1682. else
  1683. audioStream = new DummyMediaStream("dummyAudio");
  1684. if (stream && stream.videoStream)
  1685. videoStream = stream.videoStream;
  1686. else
  1687. videoStream = new DummyMediaStream("dummyVideo");
  1688. }
  1689. var audioMuted = (usageOptions && usageOptions.audio === false),
  1690. videoMuted = (usageOptions && usageOptions.video === false);
  1691. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1692. videoGUM = (!usageOptions || usageOptions.video !== false);
  1693. return service.createLocalStreams(
  1694. [
  1695. {stream: audioStream, type: "audio", isMuted: audioMuted, isGUMStream: audioGUM, videoType: null},
  1696. {stream: videoStream, type: "video", isMuted: videoMuted, isGUMStream: videoGUM, videoType: "camera"}
  1697. ]);
  1698. },
  1699. createStream: function (stream, isVideo) {
  1700. var newStream = null;
  1701. if (window.webkitMediaStream) {
  1702. newStream = new webkitMediaStream();
  1703. if (newStream) {
  1704. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1705. for (var i = 0; i < tracks.length; i++) {
  1706. newStream.addTrack(tracks[i]);
  1707. }
  1708. }
  1709. }
  1710. else {
  1711. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1712. if (stream) {
  1713. newStream = stream;
  1714. } else {
  1715. newStream =
  1716. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1717. }
  1718. }
  1719. return newStream;
  1720. }
  1721. }
  1722. module.exports = RTCUtils;
  1723. },{"../../service/RTC/Resolutions":71,"../xmpp/SDPUtil":24,"./RTCBrowserType":13,"./adapter.screenshare":15,"events":76}],15:[function(require,module,exports){
  1724. /*! adapterjs - custom version from - 2015-08-12 */
  1725. // Adapter's interface.
  1726. var AdapterJS = AdapterJS || {};
  1727. // Browserify compatibility
  1728. if(typeof exports !== 'undefined') {
  1729. module.exports = AdapterJS;
  1730. }
  1731. AdapterJS.options = AdapterJS.options || {};
  1732. // uncomment to get virtual webcams
  1733. // AdapterJS.options.getAllCams = true;
  1734. // uncomment to prevent the install prompt when the plugin in not yet installed
  1735. // AdapterJS.options.hidePluginInstallPrompt = true;
  1736. // AdapterJS version
  1737. AdapterJS.VERSION = '0.11.1';
  1738. // This function will be called when the WebRTC API is ready to be used
  1739. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1740. // the plugin
  1741. // You may Override this function to synchronise the start of your application
  1742. // with the WebRTC API being ready.
  1743. // If you decide not to override use this synchronisation, it may result in
  1744. // an extensive CPU usage on the plugin start (once per tab loaded)
  1745. // Params:
  1746. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1747. //
  1748. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1749. // The WebRTC API is ready.
  1750. // Override me and do whatever you want here
  1751. };
  1752. // Sets a callback function to be called when the WebRTC interface is ready.
  1753. // The first argument is the function to callback.\
  1754. // Throws an error if the first argument is not a function
  1755. AdapterJS.webRTCReady = function (callback) {
  1756. if (typeof callback !== 'function') {
  1757. throw new Error('Callback provided is not a function');
  1758. }
  1759. if (true === AdapterJS.onwebrtcreadyDone) {
  1760. // All WebRTC interfaces are ready, just call the callback
  1761. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1762. } else {
  1763. // will be triggered automatically when your browser/plugin is ready.
  1764. AdapterJS.onwebrtcready = callback;
  1765. }
  1766. };
  1767. // Plugin namespace
  1768. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1769. // The object to store plugin information
  1770. AdapterJS.WebRTCPlugin.pluginInfo = {
  1771. prefix : 'Tem',
  1772. plugName : 'TemWebRTCPlugin',
  1773. pluginId : 'plugin0',
  1774. type : 'application/x-temwebrtcplugin',
  1775. onload : '__TemWebRTCReady0',
  1776. portalLink : 'http://skylink.io/plugin/',
  1777. downloadLink : null, //set below
  1778. companyName: 'Temasys'
  1779. };
  1780. if(!!navigator.platform.match(/^Mac/i)) {
  1781. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1782. }
  1783. else if(!!navigator.platform.match(/^Win/i)) {
  1784. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1785. }
  1786. // Unique identifier of each opened page
  1787. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1788. // Use this whenever you want to call the plugin.
  1789. AdapterJS.WebRTCPlugin.plugin = null;
  1790. // Set log level for the plugin once it is ready.
  1791. // The different values are
  1792. // This is an asynchronous function that will run when the plugin is ready
  1793. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1794. // Defines webrtc's JS interface according to the plugin's implementation.
  1795. // Define plugin Browsers as WebRTC Interface.
  1796. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1797. // This function detects whether or not a plugin is installed.
  1798. // Checks if Not IE (firefox, for example), else if it's IE,
  1799. // we're running IE and do something. If not it is not supported.
  1800. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1801. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1802. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1803. // Inject the HTML DOM object element into the page.
  1804. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1805. // States of readiness that the plugin goes through when
  1806. // being injected and stated
  1807. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1808. NONE : 0, // no plugin use
  1809. INITIALIZING : 1, // Detected need for plugin
  1810. INJECTING : 2, // Injecting plugin
  1811. INJECTED: 3, // Plugin element injected but not usable yet
  1812. READY: 4 // Plugin ready to be used
  1813. };
  1814. // Current state of the plugin. You cannot use the plugin before this is
  1815. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1816. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1817. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1818. // Used to make sure AdapterJS.onwebrtcready is only called once
  1819. AdapterJS.onwebrtcreadyDone = false;
  1820. // Log levels for the plugin.
  1821. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1822. /*
  1823. Log outputs are prefixed in some cases.
  1824. INFO: Information reported by the plugin.
  1825. ERROR: Errors originating from within the plugin.
  1826. WEBRTC: Error originating from within the libWebRTC library
  1827. */
  1828. // From the least verbose to the most verbose
  1829. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1830. NONE : 'NONE',
  1831. ERROR : 'ERROR',
  1832. WARNING : 'WARNING',
  1833. INFO: 'INFO',
  1834. VERBOSE: 'VERBOSE',
  1835. SENSITIVE: 'SENSITIVE'
  1836. };
  1837. // Does a waiting check before proceeding to load the plugin.
  1838. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1839. // This methid will use an interval to wait for the plugin to be ready.
  1840. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1841. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1842. // This function will be called when plugin is ready. It sends necessary
  1843. // details to the plugin.
  1844. // The function will wait for the document to be ready and the set the
  1845. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1846. // indicating that it can start being requested.
  1847. // This function is not in the IE/Safari condition brackets so that
  1848. // TemPluginLoaded function might be called on Chrome/Firefox.
  1849. // This function is the only private function that is not encapsulated to
  1850. // allow the plugin method to be called.
  1851. __TemWebRTCReady0 = function () {
  1852. if (document.readyState === 'complete') {
  1853. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1854. AdapterJS.maybeThroughWebRTCReady();
  1855. } else {
  1856. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1857. if (document.readyState === 'complete') {
  1858. // TODO: update comments, we wait for the document to be ready
  1859. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1860. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1861. AdapterJS.maybeThroughWebRTCReady();
  1862. }
  1863. }, 100);
  1864. }
  1865. };
  1866. AdapterJS.maybeThroughWebRTCReady = function() {
  1867. if (!AdapterJS.onwebrtcreadyDone) {
  1868. AdapterJS.onwebrtcreadyDone = true;
  1869. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1870. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1871. }
  1872. }
  1873. };
  1874. // Text namespace
  1875. AdapterJS.TEXT = {
  1876. PLUGIN: {
  1877. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1878. 'to work on this browser.',
  1879. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1880. BUTTON: 'Install Now'
  1881. },
  1882. REFRESH: {
  1883. REQUIRE_REFRESH: 'Please refresh page',
  1884. BUTTON: 'Refresh Page'
  1885. }
  1886. };
  1887. // The result of ice connection states.
  1888. // - starting: Ice connection is starting.
  1889. // - checking: Ice connection is checking.
  1890. // - connected Ice connection is connected.
  1891. // - completed Ice connection is connected.
  1892. // - done Ice connection has been completed.
  1893. // - disconnected Ice connection has been disconnected.
  1894. // - failed Ice connection has failed.
  1895. // - closed Ice connection is closed.
  1896. AdapterJS._iceConnectionStates = {
  1897. starting : 'starting',
  1898. checking : 'checking',
  1899. connected : 'connected',
  1900. completed : 'connected',
  1901. done : 'completed',
  1902. disconnected : 'disconnected',
  1903. failed : 'failed',
  1904. closed : 'closed'
  1905. };
  1906. //The IceConnection states that has been fired for each peer.
  1907. AdapterJS._iceConnectionFiredStates = [];
  1908. // Check if WebRTC Interface is defined.
  1909. AdapterJS.isDefined = null;
  1910. // This function helps to retrieve the webrtc detected browser information.
  1911. // This sets:
  1912. // - webrtcDetectedBrowser: The browser agent name.
  1913. // - webrtcDetectedVersion: The browser version.
  1914. // - webrtcDetectedType: The types of webRTC support.
  1915. // - 'moz': Mozilla implementation of webRTC.
  1916. // - 'webkit': WebKit implementation of webRTC.
  1917. // - 'plugin': Using the plugin implementation.
  1918. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1919. var hasMatch, checkMatch = navigator.userAgent.match(
  1920. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1921. if (/trident/i.test(checkMatch[1])) {
  1922. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1923. webrtcDetectedBrowser = 'IE';
  1924. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1925. } else if (checkMatch[1] === 'Chrome') {
  1926. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1927. if (hasMatch !== null) {
  1928. webrtcDetectedBrowser = 'opera';
  1929. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1930. }
  1931. }
  1932. if (navigator.userAgent.indexOf('Safari')) {
  1933. if (typeof InstallTrigger !== 'undefined') {
  1934. webrtcDetectedBrowser = 'firefox';
  1935. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1936. webrtcDetectedBrowser = 'IE';
  1937. } else if (
  1938. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1939. webrtcDetectedBrowser = 'safari';
  1940. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1941. webrtcDetectedBrowser = 'opera';
  1942. } else if (!!window.chrome) {
  1943. webrtcDetectedBrowser = 'chrome';
  1944. }
  1945. }
  1946. if (!webrtcDetectedBrowser) {
  1947. webrtcDetectedVersion = checkMatch[1];
  1948. }
  1949. if (!webrtcDetectedVersion) {
  1950. try {
  1951. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1952. [navigator.appName, navigator.appVersion, '-?'];
  1953. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1954. checkMatch.splice(1, 1, hasMatch[1]);
  1955. }
  1956. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1957. } catch (error) { }
  1958. }
  1959. };
  1960. // To fix configuration as some browsers does not support
  1961. // the 'urls' attribute.
  1962. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1963. if (pcConfig === null) {
  1964. return;
  1965. }
  1966. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1967. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1968. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1969. delete pcConfig.iceServers[i].urls;
  1970. }
  1971. }
  1972. };
  1973. AdapterJS.addEvent = function(elem, evnt, func) {
  1974. if (elem.addEventListener) { // W3C DOM
  1975. elem.addEventListener(evnt, func, false);
  1976. } else if (elem.attachEvent) {// OLD IE DOM
  1977. elem.attachEvent('on'+evnt, func);
  1978. } else { // No much to do
  1979. elem[evnt] = func;
  1980. }
  1981. };
  1982. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1983. // only inject once the page is ready
  1984. if (document.readyState !== 'complete') {
  1985. return;
  1986. }
  1987. var w = window;
  1988. var i = document.createElement('iframe');
  1989. i.style.position = 'fixed';
  1990. i.style.top = '-41px';
  1991. i.style.left = 0;
  1992. i.style.right = 0;
  1993. i.style.width = '100%';
  1994. i.style.height = '40px';
  1995. i.style.backgroundColor = '#ffffe1';
  1996. i.style.border = 'none';
  1997. i.style.borderBottom = '1px solid #888888';
  1998. i.style.zIndex = '9999999';
  1999. if(typeof i.style.webkitTransition === 'string') {
  2000. i.style.webkitTransition = 'all .5s ease-out';
  2001. } else if(typeof i.style.transition === 'string') {
  2002. i.style.transition = 'all .5s ease-out';
  2003. }
  2004. document.body.appendChild(i);
  2005. c = (i.contentWindow) ? i.contentWindow :
  2006. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2007. c.document.open();
  2008. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2009. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2010. 'middle; cursor: default;">' + text + '</span>');
  2011. if(buttonText && buttonLink) {
  2012. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2013. c.document.close();
  2014. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2015. if (!!displayRefreshBar) {
  2016. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2017. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2018. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2019. }
  2020. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2021. e.preventDefault();
  2022. try {
  2023. event.cancelBubble = true;
  2024. } catch(error) { }
  2025. var pluginInstallInterval = setInterval(function(){
  2026. if(! isIE) {
  2027. navigator.plugins.refresh(false);
  2028. }
  2029. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2030. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2031. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2032. function() {
  2033. clearInterval(pluginInstallInterval);
  2034. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  2035. },
  2036. function() { //Does nothing because not used here
  2037. });
  2038. } , 500);
  2039. });
  2040. }else {
  2041. c.document.close();
  2042. }
  2043. AdapterJS.addEvent(c.document, 'click', function() {
  2044. w.document.body.removeChild(i);
  2045. });
  2046. setTimeout(function() {
  2047. if(typeof i.style.webkitTransform === 'string') {
  2048. i.style.webkitTransform = 'translateY(40px)';
  2049. } else if(typeof i.style.transform === 'string') {
  2050. i.style.transform = 'translateY(40px)';
  2051. } else {
  2052. i.style.top = '0px';
  2053. }
  2054. }, 300);
  2055. };
  2056. // -----------------------------------------------------------
  2057. // Detected webrtc implementation. Types are:
  2058. // - 'moz': Mozilla implementation of webRTC.
  2059. // - 'webkit': WebKit implementation of webRTC.
  2060. // - 'plugin': Using the plugin implementation.
  2061. webrtcDetectedType = null;
  2062. // Detected webrtc datachannel support. Types are:
  2063. // - 'SCTP': SCTP datachannel support.
  2064. // - 'RTP': RTP datachannel support.
  2065. webrtcDetectedDCSupport = null;
  2066. // Set the settings for creating DataChannels, MediaStream for
  2067. // Cross-browser compability.
  2068. // - This is only for SCTP based support browsers.
  2069. // the 'urls' attribute.
  2070. checkMediaDataChannelSettings =
  2071. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2072. if (typeof callback !== 'function') {
  2073. return;
  2074. }
  2075. var beOfferer = true;
  2076. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2077. // Nightly version does not require MozDontOfferDataChannel for interop
  2078. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2079. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2080. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2081. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2082. // Resends an updated version of constraints for MozDataChannel to work
  2083. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2084. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2085. try {
  2086. delete constraints.mandatory.MozDontOfferDataChannel;
  2087. } catch (error) {
  2088. console.error('Failed deleting MozDontOfferDataChannel');
  2089. console.error(error);
  2090. }
  2091. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2092. constraints.mandatory.MozDontOfferDataChannel = true;
  2093. }
  2094. if (!isLocalFirefox) {
  2095. // temporary measure to remove Moz* constraints in non Firefox browsers
  2096. for (var prop in constraints.mandatory) {
  2097. if (constraints.mandatory.hasOwnProperty(prop)) {
  2098. if (prop.indexOf('Moz') !== -1) {
  2099. delete constraints.mandatory[prop];
  2100. }
  2101. }
  2102. }
  2103. }
  2104. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2105. // interopability of the media stream
  2106. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2107. beOfferer = false;
  2108. }
  2109. callback(beOfferer, constraints);
  2110. };
  2111. // Handles the differences for all browsers ice connection state output.
  2112. // - Tested outcomes are:
  2113. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2114. // - Chrome (answerer) : 'checking' > 'connected'
  2115. // - Firefox (offerer) : 'checking' > 'connected'
  2116. // - Firefox (answerer): 'checking' > 'connected'
  2117. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2118. if (typeof callback !== 'function') {
  2119. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2120. return;
  2121. }
  2122. peerId = (peerId) ? peerId : 'peer';
  2123. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2124. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2125. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2126. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2127. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2128. }
  2129. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2130. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2131. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2132. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2133. setTimeout(function () {
  2134. AdapterJS._iceConnectionFiredStates[peerId]
  2135. .push(AdapterJS._iceConnectionStates.done);
  2136. callback(AdapterJS._iceConnectionStates.done);
  2137. }, 1000);
  2138. }
  2139. callback(iceConnectionState);
  2140. }
  2141. return;
  2142. };
  2143. // Firefox:
  2144. // - Creates iceServer from the url for Firefox.
  2145. // - Create iceServer with stun url.
  2146. // - Create iceServer with turn url.
  2147. // - Ignore the transport parameter from TURN url for FF version <=27.
  2148. // - Return null for createIceServer if transport=tcp.
  2149. // - FF 27 and above supports transport parameters in TURN url,
  2150. // - So passing in the full url to create iceServer.
  2151. // Chrome:
  2152. // - Creates iceServer from the url for Chrome M33 and earlier.
  2153. // - Create iceServer with stun url.
  2154. // - Chrome M28 & above uses below TURN format.
  2155. // Plugin:
  2156. // - Creates Ice Server for Plugin Browsers
  2157. // - If Stun - Create iceServer with stun url.
  2158. // - Else - Create iceServer with turn url
  2159. // - This is a WebRTC Function
  2160. createIceServer = null;
  2161. // Firefox:
  2162. // - Creates IceServers for Firefox
  2163. // - Use .url for FireFox.
  2164. // - Multiple Urls support
  2165. // Chrome:
  2166. // - Creates iceServers from the urls for Chrome M34 and above.
  2167. // - .urls is supported since Chrome M34.
  2168. // - Multiple Urls support
  2169. // Plugin:
  2170. // - Creates Ice Servers for Plugin Browsers
  2171. // - Multiple Urls support
  2172. // - This is a WebRTC Function
  2173. createIceServers = null;
  2174. //------------------------------------------------------------
  2175. //The RTCPeerConnection object.
  2176. RTCPeerConnection = null;
  2177. // Creates RTCSessionDescription object for Plugin Browsers
  2178. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2179. RTCSessionDescription : null;
  2180. // Creates RTCIceCandidate object for Plugin Browsers
  2181. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2182. RTCIceCandidate : null;
  2183. // Get UserMedia (only difference is the prefix).
  2184. // Code from Adam Barth.
  2185. getUserMedia = null;
  2186. // Attach a media stream to an element.
  2187. attachMediaStream = null;
  2188. // Re-attach a media stream to an element.
  2189. reattachMediaStream = null;
  2190. // Detected browser agent name. Types are:
  2191. // - 'firefox': Firefox browser.
  2192. // - 'chrome': Chrome browser.
  2193. // - 'opera': Opera browser.
  2194. // - 'safari': Safari browser.
  2195. // - 'IE' - Internet Explorer browser.
  2196. webrtcDetectedBrowser = null;
  2197. // Detected browser version.
  2198. webrtcDetectedVersion = null;
  2199. // Check for browser types and react accordingly
  2200. if (navigator.mozGetUserMedia) {
  2201. webrtcDetectedBrowser = 'firefox';
  2202. webrtcDetectedVersion = parseInt(navigator
  2203. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2204. webrtcDetectedType = 'moz';
  2205. webrtcDetectedDCSupport = 'SCTP';
  2206. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2207. AdapterJS.maybeFixConfiguration(pcConfig);
  2208. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2209. };
  2210. // The RTCSessionDescription object.
  2211. RTCSessionDescription = mozRTCSessionDescription;
  2212. window.RTCSessionDescription = RTCSessionDescription;
  2213. // The RTCIceCandidate object.
  2214. RTCIceCandidate = mozRTCIceCandidate;
  2215. window.RTCIceCandidate = RTCIceCandidate;
  2216. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2217. navigator.getUserMedia = window.getUserMedia;
  2218. // Shim for MediaStreamTrack.getSources.
  2219. MediaStreamTrack.getSources = function(successCb) {
  2220. setTimeout(function() {
  2221. var infos = [
  2222. { kind: 'audio', id: 'default', label:'', facing:'' },
  2223. { kind: 'video', id: 'default', label:'', facing:'' }
  2224. ];
  2225. successCb(infos);
  2226. }, 0);
  2227. };
  2228. createIceServer = function (url, username, password) {
  2229. var iceServer = null;
  2230. var url_parts = url.split(':');
  2231. if (url_parts[0].indexOf('stun') === 0) {
  2232. iceServer = { url : url };
  2233. } else if (url_parts[0].indexOf('turn') === 0) {
  2234. if (webrtcDetectedVersion < 27) {
  2235. var turn_url_parts = url.split('?');
  2236. if (turn_url_parts.length === 1 ||
  2237. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2238. iceServer = {
  2239. url : turn_url_parts[0],
  2240. credential : password,
  2241. username : username
  2242. };
  2243. }
  2244. } else {
  2245. iceServer = {
  2246. url : url,
  2247. credential : password,
  2248. username : username
  2249. };
  2250. }
  2251. }
  2252. return iceServer;
  2253. };
  2254. createIceServers = function (urls, username, password) {
  2255. var iceServers = [];
  2256. for (i = 0; i < urls.length; i++) {
  2257. var iceServer = createIceServer(urls[i], username, password);
  2258. if (iceServer !== null) {
  2259. iceServers.push(iceServer);
  2260. }
  2261. }
  2262. return iceServers;
  2263. };
  2264. attachMediaStream = function (element, stream) {
  2265. element.mozSrcObject = stream;
  2266. if (stream !== null)
  2267. element.play();
  2268. return element;
  2269. };
  2270. reattachMediaStream = function (to, from) {
  2271. to.mozSrcObject = from.mozSrcObject;
  2272. to.play();
  2273. return to;
  2274. };
  2275. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2276. if (!callback) {
  2277. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2278. ': 1 argument required, but only 0 present.');
  2279. }
  2280. return callback([]);
  2281. };
  2282. // Fake get{Video,Audio}Tracks
  2283. if (!MediaStream.prototype.getVideoTracks) {
  2284. MediaStream.prototype.getVideoTracks = function () {
  2285. return [];
  2286. };
  2287. }
  2288. if (!MediaStream.prototype.getAudioTracks) {
  2289. MediaStream.prototype.getAudioTracks = function () {
  2290. return [];
  2291. };
  2292. }
  2293. AdapterJS.maybeThroughWebRTCReady();
  2294. } else if (navigator.webkitGetUserMedia) {
  2295. webrtcDetectedBrowser = 'chrome';
  2296. webrtcDetectedType = 'webkit';
  2297. webrtcDetectedVersion = parseInt(navigator
  2298. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2299. // check if browser is opera 20+
  2300. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2301. if (checkIfOpera !== null) {
  2302. webrtcDetectedBrowser = 'opera';
  2303. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2304. }
  2305. // check browser datachannel support
  2306. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2307. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2308. webrtcDetectedDCSupport = 'SCTP';
  2309. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2310. webrtcDetectedVersion > 24) {
  2311. webrtcDetectedDCSupport = 'RTP';
  2312. } else {
  2313. webrtcDetectedDCSupport = '';
  2314. }
  2315. createIceServer = function (url, username, password) {
  2316. var iceServer = null;
  2317. var url_parts = url.split(':');
  2318. if (url_parts[0].indexOf('stun') === 0) {
  2319. iceServer = { 'url' : url };
  2320. } else if (url_parts[0].indexOf('turn') === 0) {
  2321. iceServer = {
  2322. 'url' : url,
  2323. 'credential' : password,
  2324. 'username' : username
  2325. };
  2326. }
  2327. return iceServer;
  2328. };
  2329. createIceServers = function (urls, username, password) {
  2330. var iceServers = [];
  2331. if (webrtcDetectedVersion >= 34) {
  2332. iceServers = {
  2333. 'urls' : urls,
  2334. 'credential' : password,
  2335. 'username' : username
  2336. };
  2337. } else {
  2338. for (i = 0; i < urls.length; i++) {
  2339. var iceServer = createIceServer(urls[i], username, password);
  2340. if (iceServer !== null) {
  2341. iceServers.push(iceServer);
  2342. }
  2343. }
  2344. }
  2345. return iceServers;
  2346. };
  2347. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2348. if (webrtcDetectedVersion < 34) {
  2349. AdapterJS.maybeFixConfiguration(pcConfig);
  2350. }
  2351. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2352. };
  2353. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2354. navigator.getUserMedia = window.getUserMedia;
  2355. attachMediaStream = function (element, stream) {
  2356. if (typeof element.srcObject !== 'undefined') {
  2357. element.srcObject = stream;
  2358. } else if (typeof element.mozSrcObject !== 'undefined') {
  2359. element.mozSrcObject = stream;
  2360. } else if (typeof element.src !== 'undefined') {
  2361. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2362. } else {
  2363. console.log('Error attaching stream to element.');
  2364. }
  2365. return element;
  2366. };
  2367. reattachMediaStream = function (to, from) {
  2368. to.src = from.src;
  2369. return to;
  2370. };
  2371. AdapterJS.maybeThroughWebRTCReady();
  2372. } else { // TRY TO USE PLUGIN
  2373. // IE 9 is not offering an implementation of console.log until you open a console
  2374. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2375. /* jshint -W020 */
  2376. console = {} || console;
  2377. // Implemented based on console specs from MDN
  2378. // You may override these functions
  2379. console.log = function (arg) {};
  2380. console.info = function (arg) {};
  2381. console.error = function (arg) {};
  2382. console.dir = function (arg) {};
  2383. console.exception = function (arg) {};
  2384. console.trace = function (arg) {};
  2385. console.warn = function (arg) {};
  2386. console.count = function (arg) {};
  2387. console.debug = function (arg) {};
  2388. console.count = function (arg) {};
  2389. console.time = function (arg) {};
  2390. console.timeEnd = function (arg) {};
  2391. console.group = function (arg) {};
  2392. console.groupCollapsed = function (arg) {};
  2393. console.groupEnd = function (arg) {};
  2394. /* jshint +W020 */
  2395. }
  2396. webrtcDetectedType = 'plugin';
  2397. webrtcDetectedDCSupport = 'plugin';
  2398. AdapterJS.parseWebrtcDetectedBrowser();
  2399. isIE = webrtcDetectedBrowser === 'IE';
  2400. /* jshint -W035 */
  2401. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2402. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2403. /* empty because it needs to prevent the function from running. */
  2404. }
  2405. };
  2406. /* jshint +W035 */
  2407. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2408. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2409. // Call immediately if possible
  2410. // Once the plugin is set, the code will always take this path
  2411. callback();
  2412. } else {
  2413. // otherwise start a 100ms interval
  2414. var checkPluginReadyState = setInterval(function () {
  2415. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2416. clearInterval(checkPluginReadyState);
  2417. callback();
  2418. }
  2419. }, 100);
  2420. }
  2421. };
  2422. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2423. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2424. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2425. });
  2426. };
  2427. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2428. // only inject once the page is ready
  2429. if (document.readyState !== 'complete') {
  2430. return;
  2431. }
  2432. // Prevent multiple injections
  2433. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2434. return;
  2435. }
  2436. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2437. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2438. var frag = document.createDocumentFragment();
  2439. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2440. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2441. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2442. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2443. '<param name="pluginId" value="' +
  2444. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2445. '<param name="windowless" value="false" /> ' +
  2446. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2447. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2448. '" />' +
  2449. // uncomment to be able to use virtual cams
  2450. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2451. '</object>';
  2452. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2453. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2454. }
  2455. document.body.appendChild(frag);
  2456. // Need to re-fetch the plugin
  2457. AdapterJS.WebRTCPlugin.plugin =
  2458. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2459. } else {
  2460. // Load Plugin
  2461. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2462. AdapterJS.WebRTCPlugin.plugin.id =
  2463. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2464. // IE will only start the plugin if it's ACTUALLY visible
  2465. if (isIE) {
  2466. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2467. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2468. } else { // The size of the plugin on Safari should be 0x0px
  2469. // so that the autorisation prompt is at the top
  2470. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2471. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2472. }
  2473. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2474. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2475. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2476. '<param name="pluginId" value="' +
  2477. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2478. '<param name="windowless" value="false" /> ' +
  2479. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2480. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2481. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2482. }
  2483. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2484. };
  2485. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2486. function (comName, plugName, installedCb, notInstalledCb) {
  2487. if (!isIE) {
  2488. var pluginArray = navigator.plugins;
  2489. for (var i = 0; i < pluginArray.length; i++) {
  2490. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2491. installedCb();
  2492. return;
  2493. }
  2494. }
  2495. notInstalledCb();
  2496. } else {
  2497. try {
  2498. var axo = new ActiveXObject(comName + '.' + plugName);
  2499. } catch (e) {
  2500. notInstalledCb();
  2501. return;
  2502. }
  2503. installedCb();
  2504. }
  2505. };
  2506. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2507. if (AdapterJS.WebRTCPlugin.pluginState ===
  2508. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2509. console.error("WebRTC interface has been defined already");
  2510. return;
  2511. }
  2512. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2513. AdapterJS.isDefined = function (variable) {
  2514. return variable !== null && variable !== undefined;
  2515. };
  2516. createIceServer = function (url, username, password) {
  2517. var iceServer = null;
  2518. var url_parts = url.split(':');
  2519. if (url_parts[0].indexOf('stun') === 0) {
  2520. iceServer = {
  2521. 'url' : url,
  2522. 'hasCredentials' : false
  2523. };
  2524. } else if (url_parts[0].indexOf('turn') === 0) {
  2525. iceServer = {
  2526. 'url' : url,
  2527. 'hasCredentials' : true,
  2528. 'credential' : password,
  2529. 'username' : username
  2530. };
  2531. }
  2532. return iceServer;
  2533. };
  2534. createIceServers = function (urls, username, password) {
  2535. var iceServers = [];
  2536. for (var i = 0; i < urls.length; ++i) {
  2537. iceServers.push(createIceServer(urls[i], username, password));
  2538. }
  2539. return iceServers;
  2540. };
  2541. RTCSessionDescription = function (info) {
  2542. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2543. return AdapterJS.WebRTCPlugin.plugin.
  2544. ConstructSessionDescription(info.type, info.sdp);
  2545. };
  2546. RTCPeerConnection = function (servers, constraints) {
  2547. var iceServers = null;
  2548. if (servers) {
  2549. iceServers = servers.iceServers;
  2550. for (var i = 0; i < iceServers.length; i++) {
  2551. if (iceServers[i].urls && !iceServers[i].url) {
  2552. iceServers[i].url = iceServers[i].urls;
  2553. }
  2554. iceServers[i].hasCredentials = AdapterJS.
  2555. isDefined(iceServers[i].username) &&
  2556. AdapterJS.isDefined(iceServers[i].credential);
  2557. }
  2558. }
  2559. var mandatory = (constraints && constraints.mandatory) ?
  2560. constraints.mandatory : null;
  2561. var optional = (constraints && constraints.optional) ?
  2562. constraints.optional : null;
  2563. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2564. return AdapterJS.WebRTCPlugin.plugin.
  2565. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2566. iceServers, mandatory, optional);
  2567. };
  2568. MediaStreamTrack = {};
  2569. MediaStreamTrack.getSources = function (callback) {
  2570. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2571. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2572. });
  2573. };
  2574. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2575. constraints.audio = constraints.audio || false;
  2576. constraints.video = constraints.video || false;
  2577. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2578. AdapterJS.WebRTCPlugin.plugin.
  2579. getUserMedia(constraints, successCallback, failureCallback);
  2580. });
  2581. };
  2582. window.navigator.getUserMedia = window.getUserMedia;
  2583. attachMediaStream = function (element, stream) {
  2584. if (!element || !element.parentNode) {
  2585. return;
  2586. }
  2587. var streamId
  2588. if (stream === null) {
  2589. streamId = '';
  2590. }
  2591. else {
  2592. stream.enableSoundTracks(true);
  2593. streamId = stream.id;
  2594. }
  2595. if (element.nodeName.toLowerCase() !== 'audio') {
  2596. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2597. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2598. var frag = document.createDocumentFragment();
  2599. var temp = document.createElement('div');
  2600. var classHTML = '';
  2601. if (element.className) {
  2602. classHTML = 'class="' + element.className + '" ';
  2603. } else if (element.attributes && element.attributes['class']) {
  2604. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2605. }
  2606. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2607. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2608. '<param name="pluginId" value="' + elementId + '" /> ' +
  2609. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2610. '<param name="windowless" value="true" /> ' +
  2611. '<param name="streamId" value="' + streamId + '" /> ' +
  2612. '</object>';
  2613. while (temp.firstChild) {
  2614. frag.appendChild(temp.firstChild);
  2615. }
  2616. var height = '';
  2617. var width = '';
  2618. if (element.getBoundingClientRect) {
  2619. var rectObject = element.getBoundingClientRect();
  2620. width = rectObject.width + 'px';
  2621. height = rectObject.height + 'px';
  2622. }
  2623. else if (element.width) {
  2624. width = element.width;
  2625. height = element.height;
  2626. } else {
  2627. // TODO: What scenario could bring us here?
  2628. }
  2629. element.parentNode.insertBefore(frag, element);
  2630. frag = document.getElementById(elementId);
  2631. frag.width = width;
  2632. frag.height = height;
  2633. element.parentNode.removeChild(element);
  2634. } else {
  2635. var children = element.children;
  2636. for (var i = 0; i !== children.length; ++i) {
  2637. if (children[i].name === 'streamId') {
  2638. children[i].value = streamId;
  2639. break;
  2640. }
  2641. }
  2642. element.setStreamId(streamId);
  2643. }
  2644. var newElement = document.getElementById(elementId);
  2645. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2646. if (isIE) { // on IE the event needs to be plugged manually
  2647. newElement.attachEvent('onplaying', newElement.onplaying);
  2648. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2649. newElement._TemOnClick = function (id) {
  2650. var arg = {
  2651. srcElement : document.getElementById(id)
  2652. };
  2653. newElement.onclick(arg);
  2654. };
  2655. }
  2656. return newElement;
  2657. } else {
  2658. return element;
  2659. }
  2660. };
  2661. reattachMediaStream = function (to, from) {
  2662. var stream = null;
  2663. var children = from.children;
  2664. for (var i = 0; i !== children.length; ++i) {
  2665. if (children[i].name === 'streamId') {
  2666. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2667. stream = AdapterJS.WebRTCPlugin.plugin
  2668. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2669. break;
  2670. }
  2671. }
  2672. if (stream !== null) {
  2673. return attachMediaStream(to, stream);
  2674. } else {
  2675. console.log('Could not find the stream associated with this element');
  2676. }
  2677. };
  2678. RTCIceCandidate = function (candidate) {
  2679. if (!candidate.sdpMid) {
  2680. candidate.sdpMid = '';
  2681. }
  2682. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2683. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2684. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2685. );
  2686. };
  2687. // inject plugin
  2688. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2689. AdapterJS.WebRTCPlugin.injectPlugin();
  2690. };
  2691. // This function will be called if the plugin is needed (browser different
  2692. // from Chrome or Firefox), but the plugin is not installed.
  2693. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2694. function() {
  2695. AdapterJS.addEvent(document,
  2696. 'readystatechange',
  2697. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2698. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2699. };
  2700. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2701. if (AdapterJS.options.hidePluginInstallPrompt) {
  2702. return;
  2703. }
  2704. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2705. if(downloadLink) { // if download link
  2706. var popupString;
  2707. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2708. popupString = 'This website requires you to install the ' +
  2709. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2710. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2711. ' WebRTC Plugin</a>' +
  2712. ' to work on this browser.';
  2713. } else { // no portal link, just print a generic explanation
  2714. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2715. }
  2716. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2717. } else { // no download link, just print a generic explanation
  2718. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2719. }
  2720. };
  2721. // Try to detect the plugin and act accordingly
  2722. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2723. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2724. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2725. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2726. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2727. }
  2728. (function () {
  2729. 'use strict';
  2730. var baseGetUserMedia = null;
  2731. AdapterJS.TEXT.EXTENSION = {
  2732. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2733. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2734. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2735. BUTTON_FF: 'Install Now',
  2736. BUTTON_CHROME: 'Go to Chrome Web Store'
  2737. };
  2738. var clone = function(obj) {
  2739. if (null == obj || "object" != typeof obj) return obj;
  2740. var copy = obj.constructor();
  2741. for (var attr in obj) {
  2742. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2743. }
  2744. return copy;
  2745. };
  2746. if (window.navigator.mozGetUserMedia) {
  2747. baseGetUserMedia = window.navigator.getUserMedia;
  2748. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2749. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2750. // intercepting screensharing requests
  2751. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2752. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2753. }
  2754. var updatedConstraints = clone(constraints);
  2755. //constraints.video.mediaSource = constraints.video.mediaSource;
  2756. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2757. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2758. // strange but this works anyway
  2759. var checkIfReady = setInterval(function () {
  2760. if (document.readyState === 'complete') {
  2761. clearInterval(checkIfReady);
  2762. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2763. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2764. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2765. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2766. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2767. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2768. } else {
  2769. failureCb(error);
  2770. }
  2771. });
  2772. }
  2773. }, 1);
  2774. } else { // regular GetUserMediaRequest
  2775. baseGetUserMedia(constraints, successCb, failureCb);
  2776. }
  2777. };
  2778. getUserMedia = navigator.getUserMedia;
  2779. } else if (window.navigator.webkitGetUserMedia) {
  2780. baseGetUserMedia = window.navigator.getUserMedia;
  2781. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2782. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2783. if (window.webrtcDetectedBrowser !== 'chrome') {
  2784. throw new Error('Current browser does not support screensharing');
  2785. }
  2786. // would be fine since no methods
  2787. var updatedConstraints = clone(constraints);
  2788. var chromeCallback = function(error, sourceId) {
  2789. if(!error) {
  2790. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2791. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2792. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2793. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2794. if (sourceId) {
  2795. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2796. }
  2797. delete updatedConstraints.video.mediaSource;
  2798. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2799. } else {
  2800. if (error === 'permission-denied') {
  2801. throw new Error('Permission denied for screen retrieval');
  2802. } else {
  2803. throw new Error('Failed retrieving selected screen');
  2804. }
  2805. }
  2806. };
  2807. var onIFrameCallback = function (event) {
  2808. if (!event.data) {
  2809. return;
  2810. }
  2811. if (event.data.chromeMediaSourceId) {
  2812. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2813. chromeCallback('permission-denied');
  2814. } else {
  2815. chromeCallback(null, event.data.chromeMediaSourceId);
  2816. }
  2817. }
  2818. if (event.data.chromeExtensionStatus) {
  2819. if (event.data.chromeExtensionStatus === 'not-installed') {
  2820. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2821. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2822. event.data.data, true, true);
  2823. } else {
  2824. chromeCallback(event.data.chromeExtensionStatus, null);
  2825. }
  2826. }
  2827. // this event listener is no more needed
  2828. window.removeEventListener('message', onIFrameCallback);
  2829. };
  2830. window.addEventListener('message', onIFrameCallback);
  2831. postFrameMessage({
  2832. captureSourceId: true
  2833. });
  2834. } else {
  2835. baseGetUserMedia(constraints, successCb, failureCb);
  2836. }
  2837. };
  2838. getUserMedia = navigator.getUserMedia;
  2839. } else {
  2840. baseGetUserMedia = window.navigator.getUserMedia;
  2841. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2842. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2843. // would be fine since no methods
  2844. var updatedConstraints = clone(constraints);
  2845. // wait for plugin to be ready
  2846. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2847. // check if screensharing feature is available
  2848. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2849. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2850. // set the constraints
  2851. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2852. updatedConstraints.video.optional.push({
  2853. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2854. });
  2855. delete updatedConstraints.video.mediaSource;
  2856. } else {
  2857. throw new Error('Your WebRTC plugin does not support screensharing');
  2858. }
  2859. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2860. });
  2861. } else {
  2862. baseGetUserMedia(constraints, successCb, failureCb);
  2863. }
  2864. };
  2865. getUserMedia = window.navigator.getUserMedia;
  2866. }
  2867. if (window.webrtcDetectedBrowser === 'chrome') {
  2868. var iframe = document.createElement('iframe');
  2869. iframe.onload = function() {
  2870. iframe.isLoaded = true;
  2871. };
  2872. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2873. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2874. iframe.style.display = 'none';
  2875. (document.body || document.documentElement).appendChild(iframe);
  2876. var postFrameMessage = function (object) {
  2877. object = object || {};
  2878. if (!iframe.isLoaded) {
  2879. setTimeout(function () {
  2880. iframe.contentWindow.postMessage(object, '*');
  2881. }, 100);
  2882. return;
  2883. }
  2884. iframe.contentWindow.postMessage(object, '*');
  2885. };
  2886. }
  2887. })();
  2888. },{}],16:[function(require,module,exports){
  2889. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  2890. getUserMediaWithConstraints */
  2891. /**
  2892. * Indicates that desktop stream is currently in use(for toggle purpose).
  2893. * @type {boolean}
  2894. */
  2895. var isUsingScreenStream = false;
  2896. /**
  2897. * Indicates that switch stream operation is in progress and prevent from
  2898. * triggering new events.
  2899. * @type {boolean}
  2900. */
  2901. var switchInProgress = false;
  2902. /**
  2903. * Method used to get screen sharing stream.
  2904. *
  2905. * @type {function (stream_callback, failure_callback}
  2906. */
  2907. var obtainDesktopStream = null;
  2908. /**
  2909. * Indicates whether desktop sharing extension is installed.
  2910. * @type {boolean}
  2911. */
  2912. var extInstalled = false;
  2913. /**
  2914. * Indicates whether update of desktop sharing extension is required.
  2915. * @type {boolean}
  2916. */
  2917. var extUpdateRequired = false;
  2918. var AdapterJS = require("../RTC/adapter.screenshare");
  2919. var EventEmitter = require("events");
  2920. var eventEmitter = new EventEmitter();
  2921. var DesktopSharingEventTypes
  2922. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2923. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2924. var RTCEvents = require("../../service/RTC/RTCEvents");
  2925. /**
  2926. * Method obtains desktop stream from WebRTC 'screen' source.
  2927. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  2928. */
  2929. function obtainWebRTCScreen(streamCallback, failCallback) {
  2930. APP.RTC.getUserMediaWithConstraints(
  2931. ['screen'],
  2932. streamCallback,
  2933. failCallback
  2934. );
  2935. }
  2936. /**
  2937. * Constructs inline install URL for Chrome desktop streaming extension.
  2938. * The 'chromeExtensionId' must be defined in config.js.
  2939. * @returns {string}
  2940. */
  2941. function getWebStoreInstallUrl()
  2942. {
  2943. return "https://chrome.google.com/webstore/detail/" +
  2944. config.chromeExtensionId;
  2945. }
  2946. /**
  2947. * Checks whether extension update is required.
  2948. * @param minVersion minimal required version
  2949. * @param extVersion current extension version
  2950. * @returns {boolean}
  2951. */
  2952. function isUpdateRequired(minVersion, extVersion)
  2953. {
  2954. try
  2955. {
  2956. var s1 = minVersion.split('.');
  2957. var s2 = extVersion.split('.');
  2958. var len = Math.max(s1.length, s2.length);
  2959. for (var i = 0; i < len; i++)
  2960. {
  2961. var n1 = 0,
  2962. n2 = 0;
  2963. if (i < s1.length)
  2964. n1 = parseInt(s1[i]);
  2965. if (i < s2.length)
  2966. n2 = parseInt(s2[i]);
  2967. if (isNaN(n1) || isNaN(n2))
  2968. {
  2969. return true;
  2970. }
  2971. else if (n1 !== n2)
  2972. {
  2973. return n1 > n2;
  2974. }
  2975. }
  2976. // will happen if boths version has identical numbers in
  2977. // their components (even if one of them is longer, has more components)
  2978. return false;
  2979. }
  2980. catch (e)
  2981. {
  2982. console.error("Failed to parse extension version", e);
  2983. APP.UI.messageHandler.showError("dialog.error",
  2984. "dialog.detectext");
  2985. return true;
  2986. }
  2987. }
  2988. function checkChromeExtInstalled(callback) {
  2989. if (!chrome.runtime) {
  2990. // No API, so no extension for sure
  2991. callback(false, false);
  2992. return;
  2993. }
  2994. chrome.runtime.sendMessage(
  2995. config.chromeExtensionId,
  2996. { getVersion: true },
  2997. function (response) {
  2998. if (!response || !response.version) {
  2999. // Communication failure - assume that no endpoint exists
  3000. console.warn(
  3001. "Extension not installed?: ", chrome.runtime.lastError);
  3002. callback(false, false);
  3003. return;
  3004. }
  3005. // Check installed extension version
  3006. var extVersion = response.version;
  3007. console.log('Extension version is: ' + extVersion);
  3008. var updateRequired
  3009. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  3010. callback(!updateRequired, updateRequired);
  3011. }
  3012. );
  3013. }
  3014. function doGetStreamFromExtension(streamCallback, failCallback) {
  3015. // Sends 'getStream' msg to the extension.
  3016. // Extension id must be defined in the config.
  3017. chrome.runtime.sendMessage(
  3018. config.chromeExtensionId,
  3019. { getStream: true, sources: config.desktopSharingSources },
  3020. function (response) {
  3021. if (!response) {
  3022. failCallback(chrome.runtime.lastError);
  3023. return;
  3024. }
  3025. console.log("Response from extension: " + response);
  3026. if (response.streamId) {
  3027. APP.RTC.getUserMediaWithConstraints(
  3028. ['desktop'],
  3029. function (stream) {
  3030. streamCallback(stream);
  3031. },
  3032. failCallback,
  3033. null, null, null,
  3034. response.streamId);
  3035. } else {
  3036. failCallback("Extension failed to get the stream");
  3037. }
  3038. }
  3039. );
  3040. }
  3041. /**
  3042. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  3043. * stream for returned stream token.
  3044. */
  3045. function obtainScreenFromExtension(streamCallback, failCallback) {
  3046. if (extInstalled) {
  3047. doGetStreamFromExtension(streamCallback, failCallback);
  3048. } else {
  3049. if (extUpdateRequired) {
  3050. alert(
  3051. 'Jitsi Desktop Streamer requires update. ' +
  3052. 'Changes will take effect after next Chrome restart.');
  3053. }
  3054. chrome.webstore.install(
  3055. getWebStoreInstallUrl(),
  3056. function (arg) {
  3057. console.log("Extension installed successfully", arg);
  3058. extInstalled = true;
  3059. // We need to give a moment for the endpoint to become available
  3060. window.setTimeout(function () {
  3061. doGetStreamFromExtension(streamCallback, failCallback);
  3062. }, 500);
  3063. },
  3064. function (arg) {
  3065. console.log("Failed to install the extension", arg);
  3066. failCallback(arg);
  3067. APP.UI.messageHandler.showError("dialog.error",
  3068. "dialog.failtoinstall");
  3069. }
  3070. );
  3071. }
  3072. }
  3073. /**
  3074. * Call this method to toggle desktop sharing feature.
  3075. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  3076. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  3077. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  3078. * enabled), pass any other string or nothing in order to disable this
  3079. * feature completely.
  3080. */
  3081. function setDesktopSharing(method) {
  3082. obtainDesktopStream = null;
  3083. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  3084. // care about 'method' parameter
  3085. if (RTCBrowserType.isTemasysPluginUsed()) {
  3086. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3087. console.info("Screensharing not supported by this plugin version");
  3088. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3089. console.info(
  3090. "Screensharing not available with Temasys plugin on this site");
  3091. } else {
  3092. obtainDesktopStream = obtainWebRTCScreen;
  3093. console.info("Using Temasys plugin for desktop sharing");
  3094. }
  3095. } else if (RTCBrowserType.isChrome()) {
  3096. if (method == "ext") {
  3097. if (RTCBrowserType.getChromeVersion() >= 34) {
  3098. obtainDesktopStream = obtainScreenFromExtension;
  3099. console.info("Using Chrome extension for desktop sharing");
  3100. initChromeExtension();
  3101. } else {
  3102. console.info("Chrome extension not supported until ver 34");
  3103. }
  3104. } else if (method == "webrtc") {
  3105. obtainDesktopStream = obtainWebRTCScreen;
  3106. console.info("Using Chrome WebRTC for desktop sharing");
  3107. }
  3108. }
  3109. if (!obtainDesktopStream) {
  3110. console.info("Desktop sharing disabled");
  3111. }
  3112. }
  3113. /**
  3114. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3115. * config.js to support inline installs. Host site must be selected as main
  3116. * website of published extension.
  3117. */
  3118. function initInlineInstalls()
  3119. {
  3120. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  3121. }
  3122. function initChromeExtension() {
  3123. // Initialize Chrome extension inline installs
  3124. initInlineInstalls();
  3125. // Check if extension is installed
  3126. checkChromeExtInstalled(function (installed, updateRequired) {
  3127. extInstalled = installed;
  3128. extUpdateRequired = updateRequired;
  3129. console.info(
  3130. "Chrome extension installed: " + extInstalled +
  3131. " updateRequired: " + extUpdateRequired);
  3132. });
  3133. }
  3134. function getVideoStreamFailed(error) {
  3135. console.error("Failed to obtain the stream to switch to", error);
  3136. switchInProgress = false;
  3137. isUsingScreenStream = false;
  3138. newStreamCreated(null);
  3139. }
  3140. function getDesktopStreamFailed(error) {
  3141. console.error("Failed to obtain the stream to switch to", error);
  3142. switchInProgress = false;
  3143. }
  3144. function streamSwitchDone() {
  3145. switchInProgress = false;
  3146. eventEmitter.emit(
  3147. DesktopSharingEventTypes.SWITCHING_DONE,
  3148. isUsingScreenStream);
  3149. }
  3150. function newStreamCreated(stream)
  3151. {
  3152. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  3153. stream, isUsingScreenStream, streamSwitchDone);
  3154. }
  3155. function onEndedHandler(stream) {
  3156. if (!switchInProgress && isUsingScreenStream) {
  3157. APP.desktopsharing.toggleScreenSharing();
  3158. }
  3159. //FIXME: to be verified
  3160. if (stream.removeEventListener) {
  3161. stream.removeEventListener('ended', onEndedHandler);
  3162. } else {
  3163. stream.detachEvent('ended', onEndedHandler);
  3164. }
  3165. }
  3166. // Called when RTC finishes initialization
  3167. function onWebRtcReady() {
  3168. setDesktopSharing(config.desktopSharing);
  3169. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  3170. }
  3171. module.exports = {
  3172. isUsingScreenStream: function () {
  3173. return isUsingScreenStream;
  3174. },
  3175. /**
  3176. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  3177. * and enabled.
  3178. */
  3179. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  3180. init: function () {
  3181. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  3182. },
  3183. addListener: function (listener, type)
  3184. {
  3185. eventEmitter.on(type, listener);
  3186. },
  3187. removeListener: function (listener, type) {
  3188. eventEmitter.removeListener(type, listener);
  3189. },
  3190. /*
  3191. * Toggles screen sharing.
  3192. */
  3193. toggleScreenSharing: function () {
  3194. if (switchInProgress || !obtainDesktopStream) {
  3195. console.warn("Switch in progress or no method defined");
  3196. return;
  3197. }
  3198. switchInProgress = true;
  3199. if (!isUsingScreenStream)
  3200. {
  3201. // Switch to desktop stream
  3202. obtainDesktopStream(
  3203. function (stream) {
  3204. // We now use screen stream
  3205. isUsingScreenStream = true;
  3206. // Hook 'ended' event to restore camera
  3207. // when screen stream stops
  3208. //FIXME: to be verified
  3209. if (stream.addEventListener) {
  3210. stream.addEventListener('ended', function () {
  3211. onEndedHandler(stream);
  3212. });
  3213. } else {
  3214. stream.attachEvent('ended', function () {
  3215. onEndedHandler(stream);
  3216. });
  3217. }
  3218. newStreamCreated(stream);
  3219. },
  3220. getDesktopStreamFailed);
  3221. } else {
  3222. // Disable screen stream
  3223. APP.RTC.getUserMediaWithConstraints(
  3224. ['video'],
  3225. function (stream) {
  3226. // We are now using camera stream
  3227. isUsingScreenStream = false;
  3228. newStreamCreated(stream);
  3229. },
  3230. getVideoStreamFailed, config.resolution || '360'
  3231. );
  3232. }
  3233. }
  3234. };
  3235. },{"../../service/RTC/RTCEvents":70,"../../service/desktopsharing/DesktopSharingEventTypes":74,"../RTC/RTCBrowserType":13,"../RTC/adapter.screenshare":15,"events":76}],17:[function(require,module,exports){
  3236. function supportsLocalStorage() {
  3237. try {
  3238. return 'localStorage' in window && window.localStorage !== null;
  3239. } catch (e) {
  3240. console.log("localstorage is not supported");
  3241. return false;
  3242. }
  3243. }
  3244. function generateUniqueId() {
  3245. function _p8() {
  3246. return (Math.random().toString(16) + "000000000").substr(2, 8);
  3247. }
  3248. return _p8() + _p8() + _p8() + _p8();
  3249. }
  3250. function Settings(conferenceID) {
  3251. this.email = '';
  3252. this.displayName = '';
  3253. this.userId;
  3254. this.language = null;
  3255. this.confSettings = null;
  3256. this.conferenceID = conferenceID;
  3257. if (supportsLocalStorage()) {
  3258. if(!window.localStorage.getItem(conferenceID))
  3259. this.confSettings = {};
  3260. else
  3261. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  3262. if(!this.confSettings.jitsiMeetId) {
  3263. this.confSettings.jitsiMeetId = generateUniqueId();
  3264. console.log("generated id",
  3265. this.confSettings.jitsiMeetId);
  3266. this.save();
  3267. }
  3268. this.userId = this.confSettings.jitsiMeetId || '';
  3269. this.email = this.confSettings.email || '';
  3270. this.displayName = this.confSettings.displayname || '';
  3271. this.language = this.confSettings.language;
  3272. } else {
  3273. console.log("local storage is not supported");
  3274. this.userId = generateUniqueId();
  3275. }
  3276. }
  3277. Settings.prototype.save = function () {
  3278. if(!supportsLocalStorage())
  3279. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  3280. }
  3281. Settings.prototype.setDisplayName = function (newDisplayName) {
  3282. this.displayName = newDisplayName;
  3283. if(this.confSettings != null)
  3284. this.confSettings.displayname = displayName;
  3285. this.save();
  3286. return this.displayName;
  3287. },
  3288. Settings.prototype.setEmail = function (newEmail) {
  3289. this.email = newEmail;
  3290. if(this.confSettings != null)
  3291. this.confSettings.email = newEmail;
  3292. this.save();
  3293. return this.email;
  3294. },
  3295. Settings.prototype.getSettings = function () {
  3296. return {
  3297. email: this.email,
  3298. displayName: this.displayName,
  3299. uid: this.userId,
  3300. language: this.language
  3301. };
  3302. },
  3303. Settings.prototype.setLanguage = function (lang) {
  3304. this.language = lang;
  3305. if(this.confSettings != null)
  3306. this.confSettings.language = lang;
  3307. this.save();
  3308. }
  3309. module.exports = Settings;
  3310. },{}],18:[function(require,module,exports){
  3311. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3312. var Moderator = require("./moderator");
  3313. var EventEmitter = require("events");
  3314. var parser = {
  3315. packet2JSON: function (packet, nodes) {
  3316. var self = this;
  3317. $(packet).children().each(function (index) {
  3318. var tagName = $(this).prop("tagName");
  3319. var node = {}
  3320. node["tagName"] = tagName;
  3321. node.attributes = {};
  3322. $($(this)[0].attributes).each(function( index, attr ) {
  3323. node.attributes[ attr.name ] = attr.value;
  3324. } );
  3325. var text = Strophe.getText($(this)[0]);
  3326. if(text)
  3327. node.value = text;
  3328. node.children = [];
  3329. nodes.push(node);
  3330. self.packet2JSON($(this), node.children);
  3331. })
  3332. },
  3333. JSON2packet: function (nodes, packet) {
  3334. for(var i = 0; i < nodes.length; i++)
  3335. {
  3336. var node = nodes[i];
  3337. if(!node || node === null){
  3338. continue;
  3339. }
  3340. packet.c(node.tagName, node.attributes);
  3341. if(node.value)
  3342. packet.t(node.value);
  3343. if(node.children)
  3344. this.JSON2packet(node.children, packet);
  3345. packet.up();
  3346. }
  3347. packet.up();
  3348. }
  3349. };
  3350. function ChatRoom(connection, jid, password, XMPP, options)
  3351. {
  3352. this.eventEmitter = new EventEmitter();
  3353. this.xmpp = XMPP;
  3354. this.connection = connection;
  3355. this.roomjid = Strophe.getBareJidFromJid(jid);
  3356. this.myroomjid = jid;
  3357. this.password = password;
  3358. console.info("Joined MUC as " + this.myroomjid);
  3359. this.members = {};
  3360. this.presMap = {};
  3361. this.presHandlers = {};
  3362. this.joined = false;
  3363. this.role = null;
  3364. this.focusMucJid = null;
  3365. this.bridgeIsDown = false;
  3366. this.options = options || {};
  3367. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
  3368. this.initPresenceMap();
  3369. this.session = null;
  3370. var self = this;
  3371. }
  3372. ChatRoom.prototype.initPresenceMap = function () {
  3373. this.presMap['to'] = this.myroomjid;
  3374. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  3375. this.presMap["nodes"] = [];
  3376. this.presMap["nodes"].push( {
  3377. "tagName": "user-agent",
  3378. "value": navigator.userAgent,
  3379. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  3380. });
  3381. };
  3382. ChatRoom.prototype.join = function (password) {
  3383. if(password)
  3384. this.password = password;
  3385. this.moderator.allocateConferenceFocus(function()
  3386. {
  3387. this.sendPresence();
  3388. }.bind(this));
  3389. }
  3390. ChatRoom.prototype.sendPresence = function () {
  3391. if (!this.presMap['to']) {
  3392. // Too early to send presence - not initialized
  3393. return;
  3394. }
  3395. var pres = $pres({to: this.presMap['to'] });
  3396. pres.c('x', {xmlns: this.presMap['xns']});
  3397. if (this.password) {
  3398. pres.c('password').t(this.password).up();
  3399. }
  3400. pres.up();
  3401. // Send XEP-0115 'c' stanza that contains our capabilities info
  3402. if (this.connection.caps) {
  3403. this.connection.caps.node = this.xmpp.options.clientNode;
  3404. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  3405. }
  3406. parser.JSON2packet(this.presMap.nodes, pres);
  3407. this.connection.send(pres);
  3408. };
  3409. ChatRoom.prototype.doLeave = function () {
  3410. console.log("do leave", this.myroomjid);
  3411. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  3412. this.presMap.length = 0;
  3413. this.connection.send(pres);
  3414. };
  3415. ChatRoom.prototype.createNonAnonymousRoom = function () {
  3416. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  3417. var getForm = $iq({type: 'get', to: this.roomjid})
  3418. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  3419. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3420. var self = this;
  3421. this.connection.sendIQ(getForm, function (form) {
  3422. if (!$(form).find(
  3423. '>query>x[xmlns="jabber:x:data"]' +
  3424. '>field[var="muc#roomconfig_whois"]').length) {
  3425. console.error('non-anonymous rooms not supported');
  3426. return;
  3427. }
  3428. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  3429. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3430. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3431. formSubmit.c('field', {'var': 'FORM_TYPE'})
  3432. .c('value')
  3433. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3434. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  3435. .c('value').t('anyone').up().up();
  3436. self.connection.sendIQ(formSubmit);
  3437. }, function (error) {
  3438. console.error("Error getting room configuration form");
  3439. });
  3440. };
  3441. ChatRoom.prototype.onPresence = function (pres) {
  3442. var from = pres.getAttribute('from');
  3443. // Parse roles.
  3444. var member = {};
  3445. member.show = $(pres).find('>show').text();
  3446. member.status = $(pres).find('>status').text();
  3447. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  3448. member.affiliation = tmp.attr('affiliation');
  3449. member.role = tmp.attr('role');
  3450. // Focus recognition
  3451. member.jid = tmp.attr('jid');
  3452. member.isFocus = false;
  3453. if (member.jid
  3454. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  3455. member.isFocus = true;
  3456. }
  3457. $(pres).find(">x").remove();
  3458. var nodes = [];
  3459. parser.packet2JSON(pres, nodes);
  3460. for(var i = 0; i < nodes.length; i++)
  3461. {
  3462. var node = nodes[i];
  3463. switch(node.tagName)
  3464. {
  3465. case "nick":
  3466. member.nick = node.value;
  3467. if(!member.isFocus) {
  3468. var displayName = !this.xmpp.options.displayJids
  3469. ? member.nick : Strophe.getResourceFromJid(from);
  3470. if (displayName && displayName.length > 0) {
  3471. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  3472. }
  3473. console.info("Display name: " + displayName, pres);
  3474. }
  3475. break;
  3476. case "userId":
  3477. member.id = node.value;
  3478. break;
  3479. case "email":
  3480. member.email = node.value;
  3481. break;
  3482. case "bridgeIsDown":
  3483. if(!this.bridgeIsDown) {
  3484. this.bridgeIsDown = true;
  3485. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  3486. }
  3487. break;
  3488. default :
  3489. this.processNode(node, from);
  3490. }
  3491. }
  3492. if (from == this.myroomjid) {
  3493. if (member.affiliation == 'owner')
  3494. if (this.role !== member.role) {
  3495. this.role = member.role;
  3496. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  3497. member, this.isModerator());
  3498. }
  3499. if (!this.joined) {
  3500. this.joined = true;
  3501. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  3502. }
  3503. } else if (this.members[from] === undefined) {
  3504. // new participant
  3505. this.members[from] = member;
  3506. console.log('entered', from, member);
  3507. if (member.isFocus) {
  3508. this.focusMucJid = from;
  3509. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  3510. }
  3511. else {
  3512. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  3513. }
  3514. } else {
  3515. // Presence update for existing participant
  3516. // Watch role change:
  3517. if (this.members[from].role != member.role) {
  3518. this.members[from].role = member.role;
  3519. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  3520. member.role, member.nick);
  3521. }
  3522. }
  3523. if(!member.isFocus)
  3524. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  3525. // Trigger status message update
  3526. if (member.status) {
  3527. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  3528. }
  3529. };
  3530. ChatRoom.prototype.processNode = function (node, from) {
  3531. if(this.presHandlers[node.tagName])
  3532. this.presHandlers[node.tagName](node, from);
  3533. };
  3534. ChatRoom.prototype.sendMessage = function (body, nickname) {
  3535. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3536. msg.c('body', body).up();
  3537. if (nickname) {
  3538. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  3539. }
  3540. this.connection.send(msg);
  3541. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  3542. };
  3543. ChatRoom.prototype.setSubject = function (subject) {
  3544. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  3545. msg.c('subject', subject);
  3546. this.connection.send(msg);
  3547. console.log("topic changed to " + subject);
  3548. };
  3549. ChatRoom.prototype.onParticipantLeft = function (jid) {
  3550. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  3551. this.moderator.onMucMemberLeft(jid);
  3552. };
  3553. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  3554. // room destroyed ?
  3555. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3556. '>destroy').length) {
  3557. var reason;
  3558. var reasonSelect = $(pres).find(
  3559. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  3560. '>destroy>reason');
  3561. if (reasonSelect.length) {
  3562. reason = reasonSelect.text();
  3563. }
  3564. this.xmpp.disposeConference(false);
  3565. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  3566. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  3567. return true;
  3568. }
  3569. // Status code 110 indicates that this notification is "self-presence".
  3570. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  3571. delete this.members[from];
  3572. this.onParticipantLeft(from);
  3573. }
  3574. // If the status code is 110 this means we're leaving and we would like
  3575. // to remove everyone else from our view, so we trigger the event.
  3576. else if (Object.keys(this.members).length > 1) {
  3577. for (var i in this.members) {
  3578. var member = this.members[i];
  3579. delete this.members[i];
  3580. this.onParticipantLeft(member);
  3581. }
  3582. }
  3583. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  3584. if (this.myroomjid === from) {
  3585. this.xmpp.disposeConference(false);
  3586. this.eventEmitter.emit(XMPPEvents.KICKED);
  3587. }
  3588. }
  3589. };
  3590. ChatRoom.prototype.onMessage = function (msg, from) {
  3591. var nick =
  3592. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  3593. .text() ||
  3594. Strophe.getResourceFromJid(from);
  3595. var txt = $(msg).find('>body').text();
  3596. var type = msg.getAttribute("type");
  3597. if (type == "error") {
  3598. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  3599. $(msg).find('>text').text(), txt);
  3600. return true;
  3601. }
  3602. var subject = $(msg).find('>subject');
  3603. if (subject.length) {
  3604. var subjectText = subject.text();
  3605. if (subjectText || subjectText == "") {
  3606. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  3607. console.log("Subject is changed to " + subjectText);
  3608. }
  3609. }
  3610. // xep-0203 delay
  3611. var stamp = $(msg).find('>delay').attr('stamp');
  3612. if (!stamp) {
  3613. // or xep-0091 delay, UTC timestamp
  3614. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  3615. if (stamp) {
  3616. // the format is CCYYMMDDThh:mm:ss
  3617. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  3618. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  3619. }
  3620. }
  3621. if (txt) {
  3622. console.log('chat', nick, txt);
  3623. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  3624. from, nick, txt, this.myroomjid, stamp);
  3625. }
  3626. }
  3627. ChatRoom.prototype.onPresenceError = function (pres, from) {
  3628. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3629. console.log('on password required', from);
  3630. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  3631. } else if ($(pres).find(
  3632. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  3633. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  3634. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  3635. // enter the room by replying with 'not-authorized'. This would
  3636. // result in reconnection from authorized domain.
  3637. // We're either missing Jicofo/Prosody config for anonymous
  3638. // domains or something is wrong.
  3639. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  3640. } else {
  3641. console.warn('onPresError ', pres);
  3642. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3643. }
  3644. } else {
  3645. console.warn('onPresError ', pres);
  3646. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  3647. }
  3648. };
  3649. ChatRoom.prototype.kick = function (jid) {
  3650. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  3651. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  3652. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  3653. .c('reason').t('You have been kicked.').up().up().up();
  3654. this.connection.sendIQ(
  3655. kickIQ,
  3656. function (result) {
  3657. console.log('Kick participant with jid: ', jid, result);
  3658. },
  3659. function (error) {
  3660. console.log('Kick participant error: ', error);
  3661. });
  3662. };
  3663. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  3664. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  3665. var ob = this;
  3666. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  3667. function (res) {
  3668. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  3669. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  3670. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  3671. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  3672. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  3673. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  3674. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  3675. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  3676. ob.connection.sendIQ(formsubmit,
  3677. onSuccess,
  3678. onError);
  3679. } else {
  3680. onNotSupported();
  3681. }
  3682. }, onError);
  3683. };
  3684. ChatRoom.prototype.addToPresence = function (key, values) {
  3685. values.tagName = key;
  3686. this.presMap["nodes"].push(values);
  3687. };
  3688. ChatRoom.prototype.removeFromPresence = function (key) {
  3689. for(var i = 0; i < this.presMap.nodes.length; i++)
  3690. {
  3691. if(key === this.presMap.nodes[i].tagName)
  3692. this.presMap.nodes.splice(i, 1);
  3693. }
  3694. };
  3695. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  3696. this.presHandlers[name] = handler;
  3697. }
  3698. ChatRoom.prototype.removePresenceListener = function (name) {
  3699. delete this.presHandlers[name];
  3700. }
  3701. ChatRoom.prototype.isModerator = function (jid) {
  3702. return this.role === 'moderator';
  3703. };
  3704. ChatRoom.prototype.getMemberRole = function (peerJid) {
  3705. if (this.members[peerJid]) {
  3706. return this.members[peerJid].role;
  3707. }
  3708. return null;
  3709. };
  3710. ChatRoom.prototype.setJingleSession = function(session){
  3711. this.session = session;
  3712. this.session.room = this;
  3713. };
  3714. ChatRoom.prototype.removeStream = function (stream) {
  3715. if(!this.session)
  3716. return;
  3717. this.session.peerconnection.removeStream(stream)
  3718. }
  3719. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  3720. if(this.session) {
  3721. // FIXME: will block switchInProgress on true value in case of exception
  3722. this.session.switchStreams(stream, oldStream, callback, isAudio);
  3723. } else {
  3724. // We are done immediately
  3725. console.warn("No conference handler or conference not started yet");
  3726. callback();
  3727. }
  3728. };
  3729. ChatRoom.prototype.addStream = function (stream, callback) {
  3730. if(this.session) {
  3731. // FIXME: will block switchInProgress on true value in case of exception
  3732. this.session.addStream(stream, callback);
  3733. } else {
  3734. // We are done immediately
  3735. console.warn("No conference handler or conference not started yet");
  3736. callback();
  3737. }
  3738. }
  3739. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  3740. var self = this;
  3741. var localCallback = function (mute) {
  3742. self.sendVideoInfoPresence(mute);
  3743. return callback(mute);
  3744. };
  3745. if(this.session)
  3746. {
  3747. this.session.setVideoMute(
  3748. mute, localCallback, options);
  3749. }
  3750. else {
  3751. localCallback(mute);
  3752. }
  3753. };
  3754. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  3755. //This will be for remote streams only
  3756. // if (this.forceMuted && !mute) {
  3757. // console.info("Asking focus for unmute");
  3758. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  3759. // // FIXME: wait for result before resetting muted status
  3760. // this.forceMuted = false;
  3761. // }
  3762. return this.sendAudioInfoPresence(mute, callback);;
  3763. };
  3764. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  3765. this.addToPresence("audiomuted",
  3766. {attributes:
  3767. {"audions": "http://jitsi.org/jitmeet/audio"},
  3768. value: mute.toString()});
  3769. }
  3770. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  3771. this.addAudioInfoToPresence(mute);
  3772. if(this.connection) {
  3773. this.sendPresence();
  3774. }
  3775. callback();
  3776. };
  3777. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  3778. this.addToPresence("videomuted",
  3779. {attributes:
  3780. {"videons": "http://jitsi.org/jitmeet/video"},
  3781. value: mute.toString()});
  3782. }
  3783. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  3784. this.addVideoInfoToPresence(mute);
  3785. if(!this.connection)
  3786. return;
  3787. this.sendPresence();
  3788. };
  3789. ChatRoom.prototype.addListener = function(type, listener) {
  3790. this.eventEmitter.on(type, listener);
  3791. };
  3792. ChatRoom.prototype.removeListener = function (type, listener) {
  3793. this.eventEmitter.removeListener(type, listener);
  3794. };
  3795. ChatRoom.prototype.fireRemoteStreamEvent = function(data, sid, thessrc) {
  3796. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  3797. }
  3798. ChatRoom.prototype.addLocalStreams = function (localStreams) {
  3799. this.session.addLocalStreams(localStreams);
  3800. }
  3801. module.exports = ChatRoom;
  3802. },{"../../service/xmpp/XMPPEvents":75,"./moderator":26,"events":76}],19:[function(require,module,exports){
  3803. /*
  3804. * JingleSession provides an API to manage a single Jingle session. We will
  3805. * have different implementations depending on the underlying interface used
  3806. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  3807. */
  3808. function JingleSession(me, sid, connection, service, eventEmitter) {
  3809. /**
  3810. * Our JID.
  3811. */
  3812. this.me = me;
  3813. /**
  3814. * The Jingle session identifier.
  3815. */
  3816. this.sid = sid;
  3817. /**
  3818. * The XMPP connection.
  3819. */
  3820. this.connection = connection;
  3821. /**
  3822. * The XMPP service.
  3823. */
  3824. this.service = service;
  3825. /**
  3826. * The event emitter.
  3827. */
  3828. this.eventEmitter = eventEmitter;
  3829. /**
  3830. * Whether to use dripping or not. Dripping is sending trickle candidates
  3831. * not one-by-one.
  3832. * Note: currently we do not support 'false'.
  3833. */
  3834. this.usedrip = true;
  3835. /**
  3836. * When dripping is used, stores ICE candidates which are to be sent.
  3837. */
  3838. this.drip_container = [];
  3839. // Media constraints. Is this WebRTC only?
  3840. this.media_constraints = null;
  3841. // ICE servers config (RTCConfiguration?).
  3842. this.ice_config = {};
  3843. // The chat room instance associated with the session.
  3844. this.room = null;
  3845. }
  3846. /**
  3847. * Prepares this object to initiate a session.
  3848. * @param peerjid the JID of the remote peer.
  3849. * @param isInitiator whether we will be the Jingle initiator.
  3850. * @param media_constraints
  3851. * @param ice_config
  3852. */
  3853. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  3854. media_constraints, ice_config) {
  3855. this.media_constraints = media_constraints;
  3856. this.ice_config = ice_config;
  3857. if (this.state !== null) {
  3858. console.error('attempt to initiate on session ' + this.sid +
  3859. 'in state ' + this.state);
  3860. return;
  3861. }
  3862. this.state = 'pending';
  3863. this.initiator = isInitiator ? this.me : peerjid;
  3864. this.responder = !isInitiator ? this.me : peerjid;
  3865. this.peerjid = peerjid;
  3866. this.doInitialize();
  3867. };
  3868. /**
  3869. * Finishes initialization.
  3870. */
  3871. JingleSession.prototype.doInitialize = function() {};
  3872. /**
  3873. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  3874. * Note: currently only used on transport-info
  3875. */
  3876. JingleSession.prototype.addIceCandidates = function(contents) {};
  3877. /**
  3878. * Handles an 'add-source' event.
  3879. *
  3880. * @param contents an array of Jingle 'content' elements.
  3881. */
  3882. JingleSession.prototype.addSources = function(contents) {};
  3883. /**
  3884. * Handles a 'remove-source' event.
  3885. *
  3886. * @param contents an array of Jingle 'content' elements.
  3887. */
  3888. JingleSession.prototype.removeSources = function(contents) {};
  3889. /**
  3890. * Terminates this Jingle session (stops sending media and closes the streams?)
  3891. */
  3892. JingleSession.prototype.terminate = function() {};
  3893. /**
  3894. * Sends a Jingle session-terminate message to the peer and terminates the
  3895. * session.
  3896. * @param reason
  3897. * @param text
  3898. */
  3899. JingleSession.prototype.sendTerminate = function(reason, text) {};
  3900. /**
  3901. * Handles an offer from the remote peer (prepares to accept a session).
  3902. * @param jingle the 'jingle' XML element.
  3903. */
  3904. JingleSession.prototype.setOffer = function(jingle) {};
  3905. /**
  3906. * Handles an answer from the remote peer (prepares to accept a session).
  3907. * @param jingle the 'jingle' XML element.
  3908. */
  3909. JingleSession.prototype.setAnswer = function(jingle) {};
  3910. module.exports = JingleSession;
  3911. },{}],20:[function(require,module,exports){
  3912. /* jshint -W117 */
  3913. var JingleSession = require("./JingleSession");
  3914. var TraceablePeerConnection = require("./TraceablePeerConnection");
  3915. var SDPDiffer = require("./SDPDiffer");
  3916. var SDPUtil = require("./SDPUtil");
  3917. var SDP = require("./SDP");
  3918. var async = require("async");
  3919. var transform = require("sdp-transform");
  3920. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3921. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3922. var SSRCReplacement = require("./LocalSSRCReplacement");
  3923. var RTC = require("../RTC/RTC");
  3924. // Jingle stuff
  3925. function JingleSessionPC(me, sid, connection, service, eventEmitter) {
  3926. JingleSession.call(this, me, sid, connection, service, eventEmitter);
  3927. this.initiator = null;
  3928. this.responder = null;
  3929. this.peerjid = null;
  3930. this.state = null;
  3931. this.localSDP = null;
  3932. this.remoteSDP = null;
  3933. this.relayedStreams = [];
  3934. this.usetrickle = true;
  3935. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  3936. this.hadstuncandidate = false;
  3937. this.hadturncandidate = false;
  3938. this.lasticecandidate = false;
  3939. this.statsinterval = null;
  3940. this.reason = null;
  3941. this.addssrc = [];
  3942. this.removessrc = [];
  3943. this.pendingop = null;
  3944. this.switchstreams = false;
  3945. this.wait = true;
  3946. this.localStreamsSSRC = null;
  3947. this.ssrcOwners = {};
  3948. this.ssrcVideoTypes = {};
  3949. this.eventEmitter = eventEmitter;
  3950. /**
  3951. * The indicator which determines whether the (local) video has been muted
  3952. * in response to a user command in contrast to an automatic decision made
  3953. * by the application logic.
  3954. */
  3955. this.videoMuteByUser = false;
  3956. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  3957. // We start with the queue paused. We resume it when the signaling state is
  3958. // stable and the ice connection state is connected.
  3959. this.modifySourcesQueue.pause();
  3960. }
  3961. JingleSessionPC.prototype = JingleSession.prototype;
  3962. JingleSessionPC.prototype.constructor = JingleSessionPC;
  3963. JingleSessionPC.prototype.setOffer = function(offer) {
  3964. this.setRemoteDescription(offer, 'offer');
  3965. };
  3966. JingleSessionPC.prototype.setAnswer = function(answer) {
  3967. this.setRemoteDescription(answer, 'answer');
  3968. };
  3969. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  3970. var signalingState = this.peerconnection.signalingState;
  3971. var iceConnectionState = this.peerconnection.iceConnectionState;
  3972. console.debug(signalingState + " + " + iceConnectionState);
  3973. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  3974. this.modifySourcesQueue.resume();
  3975. } else {
  3976. this.modifySourcesQueue.pause();
  3977. }
  3978. };
  3979. JingleSessionPC.prototype.doInitialize = function () {
  3980. var self = this;
  3981. this.hadstuncandidate = false;
  3982. this.hadturncandidate = false;
  3983. this.lasticecandidate = false;
  3984. this.isreconnect = false;
  3985. this.peerconnection = new TraceablePeerConnection(
  3986. this.connection.jingle.ice_config,
  3987. RTC.getPCConstraints(),
  3988. this);
  3989. this.peerconnection.onicecandidate = function (event) {
  3990. self.sendIceCandidate(event.candidate);
  3991. };
  3992. this.peerconnection.onaddstream = function (event) {
  3993. if (event.stream.id !== 'default') {
  3994. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  3995. self.remoteStreamAdded(event);
  3996. } else {
  3997. // This is a recvonly stream. Clients that implement Unified Plan,
  3998. // such as Firefox use recvonly "streams/channels/tracks" for
  3999. // receiving remote stream/tracks, as opposed to Plan B where there
  4000. // are only 3 channels: audio, video and data.
  4001. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  4002. }
  4003. };
  4004. this.peerconnection.onremovestream = function (event) {
  4005. // Remove the stream from remoteStreams
  4006. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  4007. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  4008. };
  4009. this.peerconnection.onsignalingstatechange = function (event) {
  4010. console.debug("signaling state11");
  4011. if (!(self && self.peerconnection)) return;
  4012. console.debug("signaling state222");
  4013. self.updateModifySourcesQueue();
  4014. };
  4015. /**
  4016. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  4017. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  4018. * RTCPeerConnection.iceConnectionState changes.
  4019. *
  4020. * @param event the event containing information about the change
  4021. */
  4022. this.peerconnection.oniceconnectionstatechange = function (event) {
  4023. console.debug("ice state11");
  4024. if (!(self && self.peerconnection)) return;
  4025. console.debug("ice state222");
  4026. self.updateModifySourcesQueue();
  4027. switch (self.peerconnection.iceConnectionState) {
  4028. case 'connected':
  4029. // Informs interested parties that the connection has been restored.
  4030. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  4031. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  4032. self.isreconnect = false;
  4033. break;
  4034. case 'disconnected':
  4035. self.isreconnect = true;
  4036. // Informs interested parties that the connection has been interrupted.
  4037. if (self.peerconnection.signalingState === 'stable')
  4038. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  4039. break;
  4040. case 'failed':
  4041. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4042. break;
  4043. }
  4044. onIceConnectionStateChange(self.sid, self);
  4045. };
  4046. this.peerconnection.onnegotiationneeded = function (event) {
  4047. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  4048. };
  4049. this.relayedStreams.forEach(function(stream) {
  4050. self.peerconnection.addStream(stream);
  4051. });
  4052. };
  4053. JingleSessionPC.prototype.addLocalStreams = function (localStreams) {
  4054. var self = this;
  4055. // add any local and relayed stream
  4056. localStreams.forEach(function(stream) {
  4057. self.peerconnection.addStream(stream.getOriginalStream());
  4058. });
  4059. }
  4060. function onIceConnectionStateChange(sid, session) {
  4061. switch (session.peerconnection.iceConnectionState) {
  4062. case 'checking':
  4063. session.timeChecking = (new Date()).getTime();
  4064. session.firstconnect = true;
  4065. break;
  4066. case 'completed': // on caller side
  4067. case 'connected':
  4068. if (session.firstconnect) {
  4069. session.firstconnect = false;
  4070. var metadata = {};
  4071. metadata.setupTime
  4072. = (new Date()).getTime() - session.timeChecking;
  4073. session.peerconnection.getStats(function (res) {
  4074. if(res && res.result) {
  4075. res.result().forEach(function (report) {
  4076. if (report.type == 'googCandidatePair' &&
  4077. report.stat('googActiveConnection') == 'true') {
  4078. metadata.localCandidateType
  4079. = report.stat('googLocalCandidateType');
  4080. metadata.remoteCandidateType
  4081. = report.stat('googRemoteCandidateType');
  4082. // log pair as well so we can get nice pie
  4083. // charts
  4084. metadata.candidatePair
  4085. = report.stat('googLocalCandidateType') +
  4086. ';' +
  4087. report.stat('googRemoteCandidateType');
  4088. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  4089. {
  4090. metadata.ipv6 = true;
  4091. }
  4092. }
  4093. });
  4094. }
  4095. });
  4096. }
  4097. break;
  4098. }
  4099. }
  4100. JingleSessionPC.prototype.accept = function () {
  4101. this.state = 'active';
  4102. var pranswer = this.peerconnection.localDescription;
  4103. if (!pranswer || pranswer.type != 'pranswer') {
  4104. return;
  4105. }
  4106. console.log('going from pranswer to answer');
  4107. if (this.usetrickle) {
  4108. // remove candidates already sent from session-accept
  4109. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  4110. for (var i = 0; i < lines.length; i++) {
  4111. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  4112. }
  4113. }
  4114. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  4115. // FIXME: change any inactive to sendrecv or whatever they were originally
  4116. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  4117. }
  4118. var prsdp = new SDP(pranswer.sdp);
  4119. var accept = $iq({to: this.peerjid,
  4120. type: 'set'})
  4121. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4122. action: 'session-accept',
  4123. initiator: this.initiator,
  4124. responder: this.responder,
  4125. sid: this.sid });
  4126. // FIXME why do we generate session-accept in 3 different places ?
  4127. prsdp.toJingle(
  4128. accept,
  4129. this.initiator == this.me ? 'initiator' : 'responder',
  4130. this.localStreamsSSRC);
  4131. var sdp = this.peerconnection.localDescription.sdp;
  4132. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  4133. // FIXME: change any inactive to sendrecv or whatever they were originally
  4134. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  4135. }
  4136. var self = this;
  4137. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  4138. function () {
  4139. //console.log('setLocalDescription success');
  4140. self.setLocalDescription();
  4141. SSRCReplacement.processSessionInit(accept);
  4142. self.connection.sendIQ(accept,
  4143. function () {
  4144. var ack = {};
  4145. ack.source = 'answer';
  4146. $(document).trigger('ack.jingle', [self.sid, ack]);
  4147. },
  4148. function (stanza) {
  4149. var error = ($(stanza).find('error').length) ? {
  4150. code: $(stanza).find('error').attr('code'),
  4151. reason: $(stanza).find('error :first')[0].tagName
  4152. }:{};
  4153. error.source = 'answer';
  4154. JingleSessionPC.onJingleError(self.sid, error);
  4155. },
  4156. 10000);
  4157. },
  4158. function (e) {
  4159. console.error('setLocalDescription failed', e);
  4160. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4161. }
  4162. );
  4163. };
  4164. JingleSessionPC.prototype.terminate = function (reason) {
  4165. this.state = 'ended';
  4166. this.reason = reason;
  4167. this.peerconnection.close();
  4168. if (this.statsinterval !== null) {
  4169. window.clearInterval(this.statsinterval);
  4170. this.statsinterval = null;
  4171. }
  4172. };
  4173. JingleSessionPC.prototype.active = function () {
  4174. return this.state == 'active';
  4175. };
  4176. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  4177. var self = this;
  4178. if (candidate && !this.lasticecandidate) {
  4179. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  4180. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  4181. if (!(ice && jcand)) {
  4182. console.error('failed to get ice && jcand');
  4183. return;
  4184. }
  4185. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4186. if (jcand.type === 'srflx') {
  4187. this.hadstuncandidate = true;
  4188. } else if (jcand.type === 'relay') {
  4189. this.hadturncandidate = true;
  4190. }
  4191. if (this.usetrickle) {
  4192. if (this.usedrip) {
  4193. if (this.drip_container.length === 0) {
  4194. // start 20ms callout
  4195. window.setTimeout(function () {
  4196. if (self.drip_container.length === 0) return;
  4197. self.sendIceCandidates(self.drip_container);
  4198. self.drip_container = [];
  4199. }, 20);
  4200. }
  4201. this.drip_container.push(candidate);
  4202. return;
  4203. } else {
  4204. self.sendIceCandidate([candidate]);
  4205. }
  4206. }
  4207. } else {
  4208. //console.log('sendIceCandidate: last candidate.');
  4209. if (!this.usetrickle) {
  4210. //console.log('should send full offer now...');
  4211. //FIXME why do we generate session-accept in 3 different places ?
  4212. var init = $iq({to: this.peerjid,
  4213. type: 'set'})
  4214. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4215. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  4216. initiator: this.initiator,
  4217. sid: this.sid});
  4218. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  4219. var sendJingle = function (ssrc) {
  4220. if(!ssrc)
  4221. ssrc = {};
  4222. self.localSDP.toJingle(
  4223. init,
  4224. self.initiator == self.me ? 'initiator' : 'responder',
  4225. ssrc);
  4226. SSRCReplacement.processSessionInit(init);
  4227. self.connection.sendIQ(init,
  4228. function () {
  4229. //console.log('session initiate ack');
  4230. var ack = {};
  4231. ack.source = 'offer';
  4232. $(document).trigger('ack.jingle', [self.sid, ack]);
  4233. },
  4234. function (stanza) {
  4235. self.state = 'error';
  4236. self.peerconnection.close();
  4237. var error = ($(stanza).find('error').length) ? {
  4238. code: $(stanza).find('error').attr('code'),
  4239. reason: $(stanza).find('error :first')[0].tagName,
  4240. }:{};
  4241. error.source = 'offer';
  4242. JingleSessionPC.onJingleError(self.sid, error);
  4243. },
  4244. 10000);
  4245. };
  4246. sendJingle();
  4247. }
  4248. this.lasticecandidate = true;
  4249. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  4250. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  4251. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  4252. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  4253. }
  4254. }
  4255. };
  4256. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  4257. console.log('sendIceCandidates', candidates);
  4258. var cand = $iq({to: this.peerjid, type: 'set'})
  4259. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4260. action: 'transport-info',
  4261. initiator: this.initiator,
  4262. sid: this.sid});
  4263. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  4264. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  4265. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  4266. if (cands.length > 0) {
  4267. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  4268. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4269. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  4270. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  4271. }).c('transport', ice);
  4272. for (var i = 0; i < cands.length; i++) {
  4273. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  4274. }
  4275. // add fingerprint
  4276. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  4277. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  4278. tmp.required = true;
  4279. cand.c(
  4280. 'fingerprint',
  4281. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  4282. .t(tmp.fingerprint);
  4283. delete tmp.fingerprint;
  4284. cand.attrs(tmp);
  4285. cand.up();
  4286. }
  4287. cand.up(); // transport
  4288. cand.up(); // content
  4289. }
  4290. }
  4291. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  4292. //console.log('was this the last candidate', this.lasticecandidate);
  4293. this.connection.sendIQ(cand,
  4294. function () {
  4295. var ack = {};
  4296. ack.source = 'transportinfo';
  4297. $(document).trigger('ack.jingle', [this.sid, ack]);
  4298. },
  4299. function (stanza) {
  4300. var error = ($(stanza).find('error').length) ? {
  4301. code: $(stanza).find('error').attr('code'),
  4302. reason: $(stanza).find('error :first')[0].tagName,
  4303. }:{};
  4304. error.source = 'transportinfo';
  4305. JingleSessionPC.onJingleError(this.sid, error);
  4306. },
  4307. 10000);
  4308. };
  4309. JingleSessionPC.prototype.sendOffer = function () {
  4310. //console.log('sendOffer...');
  4311. var self = this;
  4312. this.peerconnection.createOffer(function (sdp) {
  4313. self.createdOffer(sdp);
  4314. },
  4315. function (e) {
  4316. console.error('createOffer failed', e);
  4317. },
  4318. this.media_constraints
  4319. );
  4320. };
  4321. // FIXME createdOffer is never used in jitsi-meet
  4322. JingleSessionPC.prototype.createdOffer = function (sdp) {
  4323. //console.log('createdOffer', sdp);
  4324. var self = this;
  4325. this.localSDP = new SDP(sdp.sdp);
  4326. //this.localSDP.mangle();
  4327. var sendJingle = function () {
  4328. var init = $iq({to: this.peerjid,
  4329. type: 'set'})
  4330. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4331. action: 'session-initiate',
  4332. initiator: this.initiator,
  4333. sid: this.sid});
  4334. self.localSDP.toJingle(
  4335. init,
  4336. this.initiator == this.me ? 'initiator' : 'responder',
  4337. this.localStreamsSSRC);
  4338. SSRCReplacement.processSessionInit(init);
  4339. self.connection.sendIQ(init,
  4340. function () {
  4341. var ack = {};
  4342. ack.source = 'offer';
  4343. $(document).trigger('ack.jingle', [self.sid, ack]);
  4344. },
  4345. function (stanza) {
  4346. self.state = 'error';
  4347. self.peerconnection.close();
  4348. var error = ($(stanza).find('error').length) ? {
  4349. code: $(stanza).find('error').attr('code'),
  4350. reason: $(stanza).find('error :first')[0].tagName,
  4351. }:{};
  4352. error.source = 'offer';
  4353. JingleSessionPC.onJingleError(self.sid, error);
  4354. },
  4355. 10000);
  4356. }
  4357. sdp.sdp = this.localSDP.raw;
  4358. this.peerconnection.setLocalDescription(sdp,
  4359. function () {
  4360. if(self.usetrickle)
  4361. {
  4362. sendJingle();
  4363. }
  4364. self.setLocalDescription();
  4365. //console.log('setLocalDescription success');
  4366. },
  4367. function (e) {
  4368. console.error('setLocalDescription failed', e);
  4369. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4370. }
  4371. );
  4372. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  4373. for (var i = 0; i < cands.length; i++) {
  4374. var cand = SDPUtil.parse_icecandidate(cands[i]);
  4375. if (cand.type == 'srflx') {
  4376. this.hadstuncandidate = true;
  4377. } else if (cand.type == 'relay') {
  4378. this.hadturncandidate = true;
  4379. }
  4380. }
  4381. };
  4382. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  4383. var self = this;
  4384. $(contents).each(function (idx, content) {
  4385. var name = $(content).attr('name');
  4386. var mediaType = this.getAttribute('name');
  4387. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  4388. ssrcs.each(function () {
  4389. var ssrc = this.getAttribute('ssrc');
  4390. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  4391. function () {
  4392. var owner = this.getAttribute('owner');
  4393. self.ssrcOwners[ssrc] = owner;
  4394. }
  4395. );
  4396. });
  4397. });
  4398. };
  4399. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  4400. return this.ssrcOwners[ssrc];
  4401. };
  4402. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  4403. //console.log('setting remote description... ', desctype);
  4404. this.remoteSDP = new SDP('');
  4405. this.remoteSDP.fromJingle(elem);
  4406. this.readSsrcInfo($(elem).find(">content"));
  4407. if (this.peerconnection.remoteDescription !== null) {
  4408. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  4409. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  4410. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  4411. for (var i = 0; i < pranswer.media.length; i++) {
  4412. // make sure we have ice ufrag and pwd
  4413. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  4414. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  4415. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  4416. } else {
  4417. console.warn('no ice ufrag?');
  4418. }
  4419. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  4420. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  4421. } else {
  4422. console.warn('no ice pwd?');
  4423. }
  4424. }
  4425. // copy over candidates
  4426. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  4427. for (var j = 0; j < lines.length; j++) {
  4428. this.remoteSDP.media[i] += lines[j] + '\r\n';
  4429. }
  4430. }
  4431. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  4432. }
  4433. }
  4434. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  4435. this.peerconnection.setRemoteDescription(remotedesc,
  4436. function () {
  4437. //console.log('setRemoteDescription success');
  4438. },
  4439. function (e) {
  4440. console.error('setRemoteDescription error', e);
  4441. JingleSessionPC.onJingleFatalError(self, e);
  4442. }
  4443. );
  4444. };
  4445. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  4446. var self = this;
  4447. if (this.peerconnection.signalingState == 'closed') {
  4448. return;
  4449. }
  4450. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  4451. console.log('trickle ice candidate arriving before session accept...');
  4452. // create a PRANSWER for setRemoteDescription
  4453. if (!this.remoteSDP) {
  4454. var cobbled = 'v=0\r\n' +
  4455. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  4456. 's=-\r\n' +
  4457. 't=0 0\r\n';
  4458. // first, take some things from the local description
  4459. for (var i = 0; i < this.localSDP.media.length; i++) {
  4460. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  4461. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  4462. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  4463. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  4464. }
  4465. cobbled += 'a=inactive\r\n';
  4466. }
  4467. this.remoteSDP = new SDP(cobbled);
  4468. }
  4469. // then add things like ice and dtls from remote candidate
  4470. elem.each(function () {
  4471. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  4472. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4473. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4474. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  4475. var tmp = $(this).find('transport');
  4476. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  4477. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  4478. tmp = $(this).find('transport>fingerprint');
  4479. if (tmp.length) {
  4480. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  4481. } else {
  4482. console.log('no dtls fingerprint (webrtc issue #1718?)');
  4483. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  4484. }
  4485. break;
  4486. }
  4487. }
  4488. }
  4489. });
  4490. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  4491. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  4492. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  4493. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  4494. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  4495. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  4496. }).length == this.remoteSDP.media.length;
  4497. if (iscomplete) {
  4498. console.log('setting pranswer');
  4499. try {
  4500. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  4501. function() {
  4502. },
  4503. function(e) {
  4504. console.log('setRemoteDescription pranswer failed', e.toString());
  4505. });
  4506. } catch (e) {
  4507. console.error('setting pranswer failed', e);
  4508. }
  4509. } else {
  4510. //console.log('not yet setting pranswer');
  4511. }
  4512. }
  4513. // operate on each content element
  4514. elem.each(function () {
  4515. // would love to deactivate this, but firefox still requires it
  4516. var idx = -1;
  4517. var i;
  4518. for (i = 0; i < self.remoteSDP.media.length; i++) {
  4519. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4520. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4521. idx = i;
  4522. break;
  4523. }
  4524. }
  4525. if (idx == -1) { // fall back to localdescription
  4526. for (i = 0; i < self.localSDP.media.length; i++) {
  4527. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  4528. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  4529. idx = i;
  4530. break;
  4531. }
  4532. }
  4533. }
  4534. var name = $(this).attr('name');
  4535. // TODO: check ice-pwd and ice-ufrag?
  4536. $(this).find('transport>candidate').each(function () {
  4537. var line, candidate;
  4538. line = SDPUtil.candidateFromJingle(this);
  4539. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  4540. sdpMid: name,
  4541. candidate: line});
  4542. try {
  4543. self.peerconnection.addIceCandidate(candidate);
  4544. } catch (e) {
  4545. console.error('addIceCandidate failed', e.toString(), line);
  4546. }
  4547. });
  4548. });
  4549. };
  4550. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  4551. //console.log('createAnswer', provisional);
  4552. var self = this;
  4553. this.peerconnection.createAnswer(
  4554. function (sdp) {
  4555. self.createdAnswer(sdp, provisional);
  4556. },
  4557. function (e) {
  4558. console.error('createAnswer failed', e);
  4559. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4560. },
  4561. this.media_constraints
  4562. );
  4563. };
  4564. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  4565. //console.log('createAnswer callback');
  4566. var self = this;
  4567. this.localSDP = new SDP(sdp.sdp);
  4568. //this.localSDP.mangle();
  4569. this.usepranswer = provisional === true;
  4570. if (this.usetrickle) {
  4571. if (this.usepranswer) {
  4572. sdp.type = 'pranswer';
  4573. for (var i = 0; i < this.localSDP.media.length; i++) {
  4574. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  4575. }
  4576. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  4577. }
  4578. }
  4579. var self = this;
  4580. var sendJingle = function (ssrcs) {
  4581. // FIXME why do we generate session-accept in 3 different places ?
  4582. var accept = $iq({to: self.peerjid,
  4583. type: 'set'})
  4584. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4585. action: 'session-accept',
  4586. initiator: self.initiator,
  4587. responder: self.responder,
  4588. sid: self.sid });
  4589. self.localSDP.toJingle(
  4590. accept,
  4591. self.initiator == self.me ? 'initiator' : 'responder',
  4592. ssrcs);
  4593. SSRCReplacement.processSessionInit(accept);
  4594. self.connection.sendIQ(accept,
  4595. function () {
  4596. var ack = {};
  4597. ack.source = 'answer';
  4598. $(document).trigger('ack.jingle', [self.sid, ack]);
  4599. },
  4600. function (stanza) {
  4601. var error = ($(stanza).find('error').length) ? {
  4602. code: $(stanza).find('error').attr('code'),
  4603. reason: $(stanza).find('error :first')[0].tagName,
  4604. }:{};
  4605. error.source = 'answer';
  4606. JingleSessionPC.onJingleError(self.sid, error);
  4607. },
  4608. 10000);
  4609. }
  4610. sdp.sdp = this.localSDP.raw;
  4611. this.peerconnection.setLocalDescription(sdp,
  4612. function () {
  4613. //console.log('setLocalDescription success');
  4614. if (self.usetrickle && !self.usepranswer) {
  4615. sendJingle();
  4616. }
  4617. self.setLocalDescription();
  4618. },
  4619. function (e) {
  4620. console.error('setLocalDescription failed', e);
  4621. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4622. }
  4623. );
  4624. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  4625. for (var j = 0; j < cands.length; j++) {
  4626. var cand = SDPUtil.parse_icecandidate(cands[j]);
  4627. if (cand.type == 'srflx') {
  4628. this.hadstuncandidate = true;
  4629. } else if (cand.type == 'relay') {
  4630. this.hadturncandidate = true;
  4631. }
  4632. }
  4633. };
  4634. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  4635. var self = this,
  4636. term = $iq({to: this.peerjid,
  4637. type: 'set'})
  4638. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4639. action: 'session-terminate',
  4640. initiator: this.initiator,
  4641. sid: this.sid})
  4642. .c('reason')
  4643. .c(reason || 'success');
  4644. if (text) {
  4645. term.up().c('text').t(text);
  4646. }
  4647. this.connection.sendIQ(term,
  4648. function () {
  4649. self.peerconnection.close();
  4650. self.peerconnection = null;
  4651. self.terminate();
  4652. var ack = {};
  4653. ack.source = 'terminate';
  4654. $(document).trigger('ack.jingle', [self.sid, ack]);
  4655. },
  4656. function (stanza) {
  4657. var error = ($(stanza).find('error').length) ? {
  4658. code: $(stanza).find('error').attr('code'),
  4659. reason: $(stanza).find('error :first')[0].tagName,
  4660. }:{};
  4661. $(document).trigger('ack.jingle', [self.sid, error]);
  4662. },
  4663. 10000);
  4664. if (this.statsinterval !== null) {
  4665. window.clearInterval(this.statsinterval);
  4666. this.statsinterval = null;
  4667. }
  4668. };
  4669. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  4670. var self = this;
  4671. // FIXME: dirty waiting
  4672. if (!this.peerconnection.localDescription)
  4673. {
  4674. console.warn("addSource - localDescription not ready yet")
  4675. setTimeout(function()
  4676. {
  4677. self.addSource(elem, fromJid);
  4678. },
  4679. 200
  4680. );
  4681. return;
  4682. }
  4683. console.log('addssrc', new Date().getTime());
  4684. console.log('ice', this.peerconnection.iceConnectionState);
  4685. this.readSsrcInfo(elem);
  4686. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  4687. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  4688. $(elem).each(function (idx, content) {
  4689. var name = $(content).attr('name');
  4690. var lines = '';
  4691. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  4692. var semantics = this.getAttribute('semantics');
  4693. var ssrcs = $(this).find('>source').map(function () {
  4694. return this.getAttribute('ssrc');
  4695. }).get();
  4696. if (ssrcs.length != 0) {
  4697. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  4698. }
  4699. });
  4700. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  4701. tmp.each(function () {
  4702. var ssrc = $(this).attr('ssrc');
  4703. if(mySdp.containsSSRC(ssrc)){
  4704. /**
  4705. * This happens when multiple participants change their streams at the same time and
  4706. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  4707. * addssrc are scheduled for update IQ. See
  4708. */
  4709. console.warn("Got add stream request for my own ssrc: "+ssrc);
  4710. return;
  4711. }
  4712. if (sdp.containsSSRC(ssrc)) {
  4713. console.warn("Source-add request for existing SSRC: " + ssrc);
  4714. return;
  4715. }
  4716. $(this).find('>parameter').each(function () {
  4717. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  4718. if ($(this).attr('value') && $(this).attr('value').length)
  4719. lines += ':' + $(this).attr('value');
  4720. lines += '\r\n';
  4721. });
  4722. });
  4723. sdp.media.forEach(function(media, idx) {
  4724. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  4725. return;
  4726. sdp.media[idx] += lines;
  4727. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  4728. self.addssrc[idx] += lines;
  4729. });
  4730. sdp.raw = sdp.session + sdp.media.join('');
  4731. });
  4732. this.modifySourcesQueue.push(function() {
  4733. // When a source is added and if this is FF, a new channel is allocated
  4734. // for receiving the added source. We need to diffuse the SSRC of this
  4735. // new recvonly channel to the rest of the peers.
  4736. console.log('modify sources done');
  4737. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  4738. console.log("SDPs", mySdp, newSdp);
  4739. self.notifyMySSRCUpdate(mySdp, newSdp);
  4740. });
  4741. };
  4742. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  4743. var self = this;
  4744. // FIXME: dirty waiting
  4745. if (!this.peerconnection.localDescription)
  4746. {
  4747. console.warn("removeSource - localDescription not ready yet")
  4748. setTimeout(function()
  4749. {
  4750. self.removeSource(elem, fromJid);
  4751. },
  4752. 200
  4753. );
  4754. return;
  4755. }
  4756. console.log('removessrc', new Date().getTime());
  4757. console.log('ice', this.peerconnection.iceConnectionState);
  4758. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  4759. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  4760. $(elem).each(function (idx, content) {
  4761. var name = $(content).attr('name');
  4762. var lines = '';
  4763. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  4764. var semantics = this.getAttribute('semantics');
  4765. var ssrcs = $(this).find('>source').map(function () {
  4766. return this.getAttribute('ssrc');
  4767. }).get();
  4768. if (ssrcs.length != 0) {
  4769. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  4770. }
  4771. });
  4772. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  4773. tmp.each(function () {
  4774. var ssrc = $(this).attr('ssrc');
  4775. // This should never happen, but can be useful for bug detection
  4776. if(mySdp.containsSSRC(ssrc)){
  4777. console.error("Got remove stream request for my own ssrc: "+ssrc);
  4778. return;
  4779. }
  4780. $(this).find('>parameter').each(function () {
  4781. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  4782. if ($(this).attr('value') && $(this).attr('value').length)
  4783. lines += ':' + $(this).attr('value');
  4784. lines += '\r\n';
  4785. });
  4786. });
  4787. sdp.media.forEach(function(media, idx) {
  4788. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  4789. return;
  4790. sdp.media[idx] += lines;
  4791. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  4792. self.removessrc[idx] += lines;
  4793. });
  4794. sdp.raw = sdp.session + sdp.media.join('');
  4795. });
  4796. this.modifySourcesQueue.push(function() {
  4797. // When a source is removed and if this is FF, the recvonly channel that
  4798. // receives the remote stream is deactivated . We need to diffuse the
  4799. // recvonly SSRC removal to the rest of the peers.
  4800. console.log('modify sources done');
  4801. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  4802. console.log("SDPs", mySdp, newSdp);
  4803. self.notifyMySSRCUpdate(mySdp, newSdp);
  4804. });
  4805. };
  4806. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  4807. var self = this;
  4808. if (this.peerconnection.signalingState == 'closed') return;
  4809. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  4810. // There is nothing to do since scheduled job might have been executed by another succeeding call
  4811. this.setLocalDescription();
  4812. if(successCallback){
  4813. successCallback();
  4814. }
  4815. queueCallback();
  4816. return;
  4817. }
  4818. // Reset switch streams flag
  4819. this.switchstreams = false;
  4820. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  4821. // add sources
  4822. this.addssrc.forEach(function(lines, idx) {
  4823. sdp.media[idx] += lines;
  4824. });
  4825. this.addssrc = [];
  4826. // remove sources
  4827. this.removessrc.forEach(function(lines, idx) {
  4828. lines = lines.split('\r\n');
  4829. lines.pop(); // remove empty last element;
  4830. lines.forEach(function(line) {
  4831. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  4832. });
  4833. });
  4834. this.removessrc = [];
  4835. sdp.raw = sdp.session + sdp.media.join('');
  4836. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  4837. function() {
  4838. if(self.signalingState == 'closed') {
  4839. console.error("createAnswer attempt on closed state");
  4840. queueCallback("createAnswer attempt on closed state");
  4841. return;
  4842. }
  4843. self.peerconnection.createAnswer(
  4844. function(modifiedAnswer) {
  4845. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  4846. if (self.pendingop !== null) {
  4847. var sdp = new SDP(modifiedAnswer.sdp);
  4848. if (sdp.media.length > 1) {
  4849. switch(self.pendingop) {
  4850. case 'mute':
  4851. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  4852. break;
  4853. case 'unmute':
  4854. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  4855. break;
  4856. }
  4857. sdp.raw = sdp.session + sdp.media.join('');
  4858. modifiedAnswer.sdp = sdp.raw;
  4859. }
  4860. self.pendingop = null;
  4861. }
  4862. // FIXME: pushing down an answer while ice connection state
  4863. // is still checking is bad...
  4864. //console.log(self.peerconnection.iceConnectionState);
  4865. // trying to work around another chrome bug
  4866. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  4867. self.peerconnection.setLocalDescription(modifiedAnswer,
  4868. function() {
  4869. //console.log('modified setLocalDescription ok');
  4870. self.setLocalDescription();
  4871. if(successCallback){
  4872. successCallback();
  4873. }
  4874. queueCallback();
  4875. },
  4876. function(error) {
  4877. console.error('modified setLocalDescription failed', error);
  4878. queueCallback(error);
  4879. }
  4880. );
  4881. },
  4882. function(error) {
  4883. console.error('modified answer failed', error);
  4884. queueCallback(error);
  4885. }
  4886. );
  4887. },
  4888. function(error) {
  4889. console.error('modify failed', error);
  4890. queueCallback(error);
  4891. }
  4892. );
  4893. };
  4894. /**
  4895. * Switches video streams.
  4896. * @param new_stream new stream that will be used as video of this session.
  4897. * @param oldStream old video stream of this session.
  4898. * @param success_callback callback executed after successful stream switch.
  4899. */
  4900. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  4901. var self = this;
  4902. // Remember SDP to figure out added/removed SSRCs
  4903. var oldSdp = null;
  4904. if(self.peerconnection) {
  4905. if(self.peerconnection.localDescription) {
  4906. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  4907. }
  4908. self.peerconnection.removeStream(oldStream, true);
  4909. if(new_stream)
  4910. self.peerconnection.addStream(new_stream);
  4911. }
  4912. // Conference is not active
  4913. if(!oldSdp || !self.peerconnection) {
  4914. success_callback();
  4915. return;
  4916. }
  4917. self.switchstreams = true;
  4918. self.modifySourcesQueue.push(function() {
  4919. console.log('modify sources done');
  4920. success_callback();
  4921. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  4922. console.log("SDPs", oldSdp, newSdp);
  4923. self.notifyMySSRCUpdate(oldSdp, newSdp);
  4924. });
  4925. };
  4926. /**
  4927. * Adds streams.
  4928. * @param stream new stream that will be added.
  4929. * @param success_callback callback executed after successful stream addition.
  4930. */
  4931. JingleSessionPC.prototype.addStream = function (stream, callback) {
  4932. // Remember SDP to figure out added/removed SSRCs
  4933. var oldSdp = null;
  4934. if(this.peerconnection) {
  4935. if(this.peerconnection.localDescription) {
  4936. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  4937. }
  4938. if(stream)
  4939. this.peerconnection.addStream(stream);
  4940. }
  4941. // Conference is not active
  4942. if(!oldSdp || !this.peerconnection) {
  4943. callback();
  4944. return;
  4945. }
  4946. self.modifySourcesQueue.push(function() {
  4947. console.log('modify sources done');
  4948. callback();
  4949. var newSdp = new SDP(this.peerconnection.localDescription.sdp);
  4950. console.log("SDPs", oldSdp, newSdp);
  4951. this.notifyMySSRCUpdate(oldSdp, newSdp);
  4952. });
  4953. }
  4954. /**
  4955. * Figures out added/removed ssrcs and send update IQs.
  4956. * @param old_sdp SDP object for old description.
  4957. * @param new_sdp SDP object for new description.
  4958. */
  4959. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  4960. if (!(this.peerconnection.signalingState == 'stable' &&
  4961. this.peerconnection.iceConnectionState == 'connected')){
  4962. console.log("Too early to send updates");
  4963. return;
  4964. }
  4965. // send source-remove IQ.
  4966. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  4967. var remove = $iq({to: this.peerjid, type: 'set'})
  4968. .c('jingle', {
  4969. xmlns: 'urn:xmpp:jingle:1',
  4970. action: 'source-remove',
  4971. initiator: this.initiator,
  4972. sid: this.sid
  4973. }
  4974. );
  4975. var removed = sdpDiffer.toJingle(remove);
  4976. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  4977. // it in the current form
  4978. if (removed)
  4979. remove = SSRCReplacement.processSourceRemove(remove);
  4980. if (removed && remove) {
  4981. console.info("Sending source-remove", remove);
  4982. this.connection.sendIQ(remove,
  4983. function (res) {
  4984. console.info('got remove result', res);
  4985. },
  4986. function (err) {
  4987. console.error('got remove error', err);
  4988. }
  4989. );
  4990. } else {
  4991. console.log('removal not necessary');
  4992. }
  4993. // send source-add IQ.
  4994. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  4995. var add = $iq({to: this.peerjid, type: 'set'})
  4996. .c('jingle', {
  4997. xmlns: 'urn:xmpp:jingle:1',
  4998. action: 'source-add',
  4999. initiator: this.initiator,
  5000. sid: this.sid
  5001. }
  5002. );
  5003. var added = sdpDiffer.toJingle(add);
  5004. // Let 'source-add' IQ through the hack and see if we're allowed to send
  5005. // it in the current form
  5006. if (added)
  5007. add = SSRCReplacement.processSourceAdd(add);
  5008. if (added && add) {
  5009. console.info("Sending source-add", add);
  5010. this.connection.sendIQ(add,
  5011. function (res) {
  5012. console.info('got add result', res);
  5013. },
  5014. function (err) {
  5015. console.error('got add error', err);
  5016. }
  5017. );
  5018. } else {
  5019. console.log('addition not necessary');
  5020. }
  5021. };
  5022. /**
  5023. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  5024. *
  5025. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  5026. * tracks; otherwise, <tt>false</tt>
  5027. * @param callback a function to be invoked with <tt>mute</tt> after all video
  5028. * tracks have been enabled/disabled. The function may, optionally, return
  5029. * another function which is to be invoked after the whole mute/unmute operation
  5030. * has completed successfully.
  5031. * @param options an object which specifies optional arguments such as the
  5032. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  5033. * specifies whether the method was initiated in response to a user command (in
  5034. * contrast to an automatic decision made by the application logic)
  5035. */
  5036. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  5037. var byUser;
  5038. if (options) {
  5039. byUser = options.byUser;
  5040. if (typeof byUser === 'undefined') {
  5041. byUser = true;
  5042. }
  5043. } else {
  5044. byUser = true;
  5045. }
  5046. // The user's command to mute the (local) video takes precedence over any
  5047. // automatic decision made by the application logic.
  5048. if (byUser) {
  5049. this.videoMuteByUser = mute;
  5050. } else if (this.videoMuteByUser) {
  5051. return;
  5052. }
  5053. this.hardMuteVideo(mute);
  5054. var self = this;
  5055. var oldSdp = null;
  5056. if(self.peerconnection) {
  5057. if(self.peerconnection.localDescription) {
  5058. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  5059. }
  5060. }
  5061. this.modifySourcesQueue.push(function() {
  5062. console.log('modify sources done');
  5063. callback(mute);
  5064. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  5065. console.log("SDPs", oldSdp, newSdp);
  5066. self.notifyMySSRCUpdate(oldSdp, newSdp);
  5067. });
  5068. };
  5069. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  5070. this.pendingop = muted ? 'mute' : 'unmute';
  5071. };
  5072. JingleSessionPC.prototype.sendMute = function (muted, content) {
  5073. var info = $iq({to: this.peerjid,
  5074. type: 'set'})
  5075. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5076. action: 'session-info',
  5077. initiator: this.initiator,
  5078. sid: this.sid });
  5079. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  5080. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  5081. if (content) {
  5082. info.attrs({'name': content});
  5083. }
  5084. this.connection.send(info);
  5085. };
  5086. JingleSessionPC.prototype.sendRinging = function () {
  5087. var info = $iq({to: this.peerjid,
  5088. type: 'set'})
  5089. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  5090. action: 'session-info',
  5091. initiator: this.initiator,
  5092. sid: this.sid });
  5093. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  5094. this.connection.send(info);
  5095. };
  5096. JingleSessionPC.prototype.getStats = function (interval) {
  5097. var self = this;
  5098. var recv = {audio: 0, video: 0};
  5099. var lost = {audio: 0, video: 0};
  5100. var lastrecv = {audio: 0, video: 0};
  5101. var lastlost = {audio: 0, video: 0};
  5102. var loss = {audio: 0, video: 0};
  5103. var delta = {audio: 0, video: 0};
  5104. this.statsinterval = window.setInterval(function () {
  5105. if (self && self.peerconnection && self.peerconnection.getStats) {
  5106. self.peerconnection.getStats(function (stats) {
  5107. var results = stats.result();
  5108. // TODO: there are so much statistics you can get from this..
  5109. for (var i = 0; i < results.length; ++i) {
  5110. if (results[i].type == 'ssrc') {
  5111. var packetsrecv = results[i].stat('packetsReceived');
  5112. var packetslost = results[i].stat('packetsLost');
  5113. if (packetsrecv && packetslost) {
  5114. packetsrecv = parseInt(packetsrecv, 10);
  5115. packetslost = parseInt(packetslost, 10);
  5116. if (results[i].stat('googFrameRateReceived')) {
  5117. lastlost.video = lost.video;
  5118. lastrecv.video = recv.video;
  5119. recv.video = packetsrecv;
  5120. lost.video = packetslost;
  5121. } else {
  5122. lastlost.audio = lost.audio;
  5123. lastrecv.audio = recv.audio;
  5124. recv.audio = packetsrecv;
  5125. lost.audio = packetslost;
  5126. }
  5127. }
  5128. }
  5129. }
  5130. delta.audio = recv.audio - lastrecv.audio;
  5131. delta.video = recv.video - lastrecv.video;
  5132. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  5133. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  5134. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  5135. });
  5136. }
  5137. }, interval || 3000);
  5138. return this.statsinterval;
  5139. };
  5140. JingleSessionPC.onJingleError = function (session, error)
  5141. {
  5142. console.error("Jingle error", error);
  5143. }
  5144. JingleSessionPC.onJingleFatalError = function (session, error)
  5145. {
  5146. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  5147. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  5148. }
  5149. JingleSessionPC.prototype.setLocalDescription = function () {
  5150. var self = this;
  5151. var newssrcs = [];
  5152. var session = transform.parse(this.peerconnection.localDescription.sdp);
  5153. session.media.forEach(function (media) {
  5154. if (media.ssrcs != null && media.ssrcs.length > 0) {
  5155. // TODO(gp) maybe exclude FID streams?
  5156. media.ssrcs.forEach(function (ssrc) {
  5157. if (ssrc.attribute !== 'cname') {
  5158. return;
  5159. }
  5160. newssrcs.push({
  5161. 'ssrc': ssrc.id,
  5162. 'type': media.type
  5163. });
  5164. });
  5165. }
  5166. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  5167. {
  5168. newssrcs.push({
  5169. 'ssrc': self.localStreamsSSRC[media.type],
  5170. 'type': media.type
  5171. });
  5172. }
  5173. });
  5174. console.log('new ssrcs', newssrcs);
  5175. // Bind us as local SSRCs owner
  5176. if (newssrcs.length > 0) {
  5177. for (var i = 1; i <= newssrcs.length; i ++) {
  5178. var ssrc = newssrcs[i-1].ssrc;
  5179. var myJid = self.connection.emuc.myroomjid;
  5180. self.ssrcOwners[ssrc] = myJid;
  5181. }
  5182. }
  5183. }
  5184. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  5185. function sendKeyframe(pc) {
  5186. console.log('sendkeyframe', pc.iceConnectionState);
  5187. if (pc.iceConnectionState !== 'connected') return; // safe...
  5188. var self = this;
  5189. pc.setRemoteDescription(
  5190. pc.remoteDescription,
  5191. function () {
  5192. pc.createAnswer(
  5193. function (modifiedAnswer) {
  5194. pc.setLocalDescription(
  5195. modifiedAnswer,
  5196. function () {
  5197. // noop
  5198. },
  5199. function (error) {
  5200. console.log('triggerKeyframe setLocalDescription failed', error);
  5201. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  5202. }
  5203. );
  5204. },
  5205. function (error) {
  5206. console.log('triggerKeyframe createAnswer failed', error);
  5207. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  5208. }
  5209. );
  5210. },
  5211. function (error) {
  5212. console.log('triggerKeyframe setRemoteDescription failed', error);
  5213. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  5214. }
  5215. );
  5216. }
  5217. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  5218. var self = this;
  5219. var thessrc;
  5220. var streamId = RTC.getStreamID(data.stream);
  5221. // look up an associated JID for a stream id
  5222. if (!streamId) {
  5223. console.error("No stream ID for", data.stream);
  5224. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  5225. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  5226. var ssrclines
  5227. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  5228. ssrclines = ssrclines.filter(function (line) {
  5229. // NOTE(gp) previously we filtered on the mslabel, but that property
  5230. // is not always present.
  5231. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  5232. if (RTCBrowserType.isTemasysPluginUsed()) {
  5233. return ((line.indexOf('mslabel:' + streamId) !== -1));
  5234. } else {
  5235. return ((line.indexOf('msid:' + streamId) !== -1));
  5236. }
  5237. });
  5238. if (ssrclines.length) {
  5239. thessrc = ssrclines[0].substring(7).split(' ')[0];
  5240. if (!self.ssrcOwners[thessrc]) {
  5241. console.error("No SSRC owner known for: " + thessrc);
  5242. return;
  5243. }
  5244. data.peerjid = self.ssrcOwners[thessrc];
  5245. console.log('associated jid', self.ssrcOwners[thessrc]);
  5246. } else {
  5247. console.error("No SSRC lines for ", streamId);
  5248. }
  5249. }
  5250. this.room.fireRemoteStreamEvent(data, this.sid, thessrc);
  5251. var isVideo = data.stream.getVideoTracks().length > 0;
  5252. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  5253. if (isVideo &&
  5254. data.peerjid && this.peerjid === data.peerjid &&
  5255. data.stream.getVideoTracks().length === 0 &&
  5256. RTC.localVideo.getTracks().length > 0) {
  5257. window.setTimeout(function () {
  5258. sendKeyframe(self.peerconnection);
  5259. }, 3000);
  5260. }
  5261. }
  5262. module.exports = JingleSessionPC;
  5263. },{"../../service/xmpp/XMPPEvents":75,"../RTC/RTC":12,"../RTC/RTCBrowserType":13,"./JingleSession":19,"./LocalSSRCReplacement":21,"./SDP":22,"./SDPDiffer":23,"./SDPUtil":24,"./TraceablePeerConnection":25,"async":33,"sdp-transform":66}],21:[function(require,module,exports){
  5264. /* global $ */
  5265. /*
  5266. Here we do modifications of local video SSRCs. There are 2 situations we have
  5267. to handle:
  5268. 1. We generate SSRC for local recvonly video stream. This is the case when we
  5269. have no local camera and it is not generated automatically, but SSRC=1 is
  5270. used implicitly. If that happens RTCP packets will be dropped by the JVB
  5271. and we won't be able to request video key frames correctly.
  5272. 2. A hack to re-use SSRC of the first video stream for any new stream created
  5273. in future. It turned out that Chrome may keep on using the SSRC of removed
  5274. video stream in RTCP even though a new one has been created. So we just
  5275. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  5276. notifications are blocked once first video SSRC is advertised to the focus.
  5277. What this hack does:
  5278. 1. Stores the SSRC of the first video stream created by
  5279. a) scanning Jingle session-accept/session-invite for existing video SSRC
  5280. b) watching for 'source-add' for new video stream if it has not been
  5281. created in step a)
  5282. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  5283. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  5284. returned to the other parts of the application.
  5285. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  5286. blocks those notifications. This makes Jicofo and all participants think
  5287. that it exists all the time even if the video stream has been removed or
  5288. replaced locally. Thanks to that there is no additional signaling activity
  5289. on video mute or when switching to the desktop stream.
  5290. */
  5291. var SDP = require('./SDP');
  5292. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5293. /**
  5294. * The hack is enabled on all browsers except FF by default
  5295. * FIXME finish the hack once removeStream method is implemented in FF
  5296. * @type {boolean}
  5297. */
  5298. var isEnabled = !RTCBrowserType.isFirefox();
  5299. /**
  5300. * Stored SSRC of local video stream.
  5301. */
  5302. var localVideoSSRC;
  5303. /**
  5304. * SSRC used for recvonly video stream when we have no local camera.
  5305. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  5306. * instead of 1.
  5307. */
  5308. var localRecvOnlySSRC;
  5309. /**
  5310. * cname for <tt>localRecvOnlySSRC</tt>
  5311. */
  5312. var localRecvOnlyCName;
  5313. /**
  5314. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  5315. * from given Jingle IQ.
  5316. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  5317. * @param actionName display name of the action which will be printed in log
  5318. * messages.
  5319. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  5320. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  5321. * other SSRCs left to be signaled after removing it.
  5322. */
  5323. var filterOutSource = function (modifyIq, actionName) {
  5324. var modifyIqTree = $(modifyIq.tree());
  5325. if (!localVideoSSRC)
  5326. return modifyIqTree[0];
  5327. var videoSSRC = modifyIqTree.find(
  5328. '>jingle>content[name="video"]' +
  5329. '>description>source[ssrc="' + localVideoSSRC + '"]');
  5330. if (!videoSSRC.length) {
  5331. return modifyIqTree[0];
  5332. }
  5333. console.info(
  5334. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  5335. videoSSRC.remove();
  5336. // Check if any sources still left to be added/removed
  5337. if (modifyIqTree.find('>jingle>content>description>source').length) {
  5338. return modifyIqTree[0];
  5339. } else {
  5340. return null;
  5341. }
  5342. };
  5343. /**
  5344. * Scans given Jingle IQ for video SSRC and stores it.
  5345. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  5346. */
  5347. var storeLocalVideoSSRC = function (jingleIq) {
  5348. var videoSSRCs =
  5349. $(jingleIq.tree())
  5350. .find('>jingle>content[name="video"]>description>source');
  5351. videoSSRCs.each(function (idx, ssrcElem) {
  5352. if (localVideoSSRC)
  5353. return;
  5354. // We consider SSRC real only if it has msid attribute
  5355. // recvonly streams in FF do not have it as well as local SSRCs
  5356. // we generate for recvonly streams in Chrome
  5357. var ssrSel = $(ssrcElem);
  5358. var msid = ssrSel.find('>parameter[name="msid"]');
  5359. if (msid.length) {
  5360. var ssrcVal = ssrSel.attr('ssrc');
  5361. if (ssrcVal) {
  5362. localVideoSSRC = ssrcVal;
  5363. console.info('Stored local video SSRC' +
  5364. ' for future re-use: ' + localVideoSSRC);
  5365. }
  5366. }
  5367. });
  5368. };
  5369. /**
  5370. * Generates new SSRC for local video recvonly stream.
  5371. * FIXME what about eventual SSRC collision ?
  5372. */
  5373. function generateRecvonlySSRC() {
  5374. //
  5375. localRecvOnlySSRC =
  5376. Math.random().toString(10).substring(2, 11);
  5377. localRecvOnlyCName =
  5378. Math.random().toString(36).substring(2);
  5379. console.info(
  5380. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  5381. ", cname: " + localRecvOnlyCName);
  5382. }
  5383. var LocalSSRCReplacement = {
  5384. /**
  5385. * Method must be called before 'session-initiate' or 'session-invite' is
  5386. * sent. Scans the IQ for local video SSRC and stores it if detected.
  5387. *
  5388. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  5389. * which will be scanned for local video SSRC.
  5390. */
  5391. processSessionInit: function (sessionInit) {
  5392. if (!isEnabled)
  5393. return;
  5394. if (localVideoSSRC) {
  5395. console.error("Local SSRC stored already: " + localVideoSSRC);
  5396. return;
  5397. }
  5398. storeLocalVideoSSRC(sessionInit);
  5399. },
  5400. /**
  5401. * If we have local video SSRC stored searched given
  5402. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  5403. * with the stored one.
  5404. * @param localDescription local description object that will have local
  5405. * video SSRC replaced with the stored one
  5406. * @returns modified <tt>localDescription</tt> object.
  5407. */
  5408. mungeLocalVideoSSRC: function (localDescription) {
  5409. if (!isEnabled)
  5410. return localDescription;
  5411. if (!localDescription) {
  5412. console.warn("localDescription is null or undefined");
  5413. return localDescription;
  5414. }
  5415. // IF we have local video SSRC stored make sure it is replaced
  5416. // with old SSRC
  5417. if (localVideoSSRC) {
  5418. var newSdp = new SDP(localDescription.sdp);
  5419. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  5420. !newSdp.containsSSRC(localVideoSSRC)) {
  5421. // Get new video SSRC
  5422. var map = newSdp.getMediaSsrcMap();
  5423. var videoPart = map[1];
  5424. var videoSSRCs = videoPart.ssrcs;
  5425. var newSSRC = Object.keys(videoSSRCs)[0];
  5426. console.info(
  5427. "Replacing new video SSRC: " + newSSRC +
  5428. " with " + localVideoSSRC);
  5429. localDescription.sdp =
  5430. newSdp.raw.replace(
  5431. new RegExp('a=ssrc:' + newSSRC, 'g'),
  5432. 'a=ssrc:' + localVideoSSRC);
  5433. }
  5434. } else {
  5435. // Make sure we have any SSRC for recvonly video stream
  5436. var sdp = new SDP(localDescription.sdp);
  5437. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  5438. sdp.media[1].indexOf('a=recvonly') !== -1) {
  5439. if (!localRecvOnlySSRC) {
  5440. generateRecvonlySSRC();
  5441. }
  5442. console.info('No SSRC in video recvonly stream' +
  5443. ' - adding SSRC: ' + localRecvOnlySSRC);
  5444. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  5445. ' cname:' + localRecvOnlyCName + '\r\n';
  5446. localDescription.sdp = sdp.session + sdp.media.join('');
  5447. }
  5448. }
  5449. return localDescription;
  5450. },
  5451. /**
  5452. * Method must be called before 'source-add' notification is sent. In case
  5453. * we have local video SSRC advertised already it will be removed from the
  5454. * notification. If no other SSRCs are described by given IQ null will be
  5455. * returned which means that there is no point in sending the notification.
  5456. * @param sourceAdd 'source-add' Jingle IQ to be processed
  5457. * @returns modified 'source-add' IQ which can be sent to the focus or
  5458. * <tt>null</tt> if no notification shall be sent. It is no longer
  5459. * a Strophe IQ Builder instance, but DOM element tree.
  5460. */
  5461. processSourceAdd: function (sourceAdd) {
  5462. if (!isEnabled)
  5463. return sourceAdd;
  5464. if (!localVideoSSRC) {
  5465. // Store local SSRC if available
  5466. storeLocalVideoSSRC(sourceAdd);
  5467. return sourceAdd;
  5468. } else {
  5469. return filterOutSource(sourceAdd, 'source-add');
  5470. }
  5471. },
  5472. /**
  5473. * Method must be called before 'source-remove' notification is sent.
  5474. * Removes local video SSRC from the notification. If there are no other
  5475. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  5476. * means that there is no point in sending the notification.
  5477. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  5478. * @returns modified 'source-remove' IQ which can be sent to the focus or
  5479. * <tt>null</tt> if no notification shall be sent. It is no longer
  5480. * a Strophe IQ Builder instance, but DOM element tree.
  5481. */
  5482. processSourceRemove: function (sourceRemove) {
  5483. if (!isEnabled)
  5484. return sourceRemove;
  5485. return filterOutSource(sourceRemove, 'source-remove');
  5486. },
  5487. /**
  5488. * Turns the hack on or off
  5489. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  5490. * to disable it
  5491. */
  5492. setEnabled: function (enabled) {
  5493. isEnabled = enabled;
  5494. }
  5495. };
  5496. module.exports = LocalSSRCReplacement;
  5497. },{"../RTC/RTCBrowserType":13,"./SDP":22}],22:[function(require,module,exports){
  5498. /* jshint -W117 */
  5499. var SDPUtil = require("./SDPUtil");
  5500. // SDP STUFF
  5501. function SDP(sdp) {
  5502. this.media = sdp.split('\r\nm=');
  5503. for (var i = 1; i < this.media.length; i++) {
  5504. this.media[i] = 'm=' + this.media[i];
  5505. if (i != this.media.length - 1) {
  5506. this.media[i] += '\r\n';
  5507. }
  5508. }
  5509. this.session = this.media.shift() + '\r\n';
  5510. this.raw = this.session + this.media.join('');
  5511. }
  5512. /**
  5513. * Returns map of MediaChannel mapped per channel idx.
  5514. */
  5515. SDP.prototype.getMediaSsrcMap = function() {
  5516. var self = this;
  5517. var media_ssrcs = {};
  5518. var tmp;
  5519. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  5520. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  5521. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  5522. var media = {
  5523. mediaindex: mediaindex,
  5524. mid: mid,
  5525. ssrcs: {},
  5526. ssrcGroups: []
  5527. };
  5528. media_ssrcs[mediaindex] = media;
  5529. tmp.forEach(function (line) {
  5530. var linessrc = line.substring(7).split(' ')[0];
  5531. // allocate new ChannelSsrc
  5532. if(!media.ssrcs[linessrc]) {
  5533. media.ssrcs[linessrc] = {
  5534. ssrc: linessrc,
  5535. lines: []
  5536. };
  5537. }
  5538. media.ssrcs[linessrc].lines.push(line);
  5539. });
  5540. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  5541. tmp.forEach(function(line){
  5542. var semantics = line.substr(0, idx).substr(13);
  5543. var ssrcs = line.substr(14 + semantics.length).split(' ');
  5544. if (ssrcs.length != 0) {
  5545. media.ssrcGroups.push({
  5546. semantics: semantics,
  5547. ssrcs: ssrcs
  5548. });
  5549. }
  5550. });
  5551. }
  5552. return media_ssrcs;
  5553. };
  5554. /**
  5555. * Returns <tt>true</tt> if this SDP contains given SSRC.
  5556. * @param ssrc the ssrc to check.
  5557. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  5558. */
  5559. SDP.prototype.containsSSRC = function(ssrc) {
  5560. var medias = this.getMediaSsrcMap();
  5561. var contains = false;
  5562. Object.keys(medias).forEach(function(mediaindex){
  5563. var media = medias[mediaindex];
  5564. //console.log("Check", channel, ssrc);
  5565. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  5566. contains = true;
  5567. }
  5568. });
  5569. return contains;
  5570. };
  5571. // remove iSAC and CN from SDP
  5572. SDP.prototype.mangle = function () {
  5573. var i, j, mline, lines, rtpmap, newdesc;
  5574. for (i = 0; i < this.media.length; i++) {
  5575. lines = this.media[i].split('\r\n');
  5576. lines.pop(); // remove empty last element
  5577. mline = SDPUtil.parse_mline(lines.shift());
  5578. if (mline.media != 'audio')
  5579. continue;
  5580. newdesc = '';
  5581. mline.fmt.length = 0;
  5582. for (j = 0; j < lines.length; j++) {
  5583. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  5584. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  5585. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  5586. continue;
  5587. mline.fmt.push(rtpmap.id);
  5588. newdesc += lines[j] + '\r\n';
  5589. } else {
  5590. newdesc += lines[j] + '\r\n';
  5591. }
  5592. }
  5593. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  5594. this.media[i] += newdesc;
  5595. }
  5596. this.raw = this.session + this.media.join('');
  5597. };
  5598. // remove lines matching prefix from session section
  5599. SDP.prototype.removeSessionLines = function(prefix) {
  5600. var self = this;
  5601. var lines = SDPUtil.find_lines(this.session, prefix);
  5602. lines.forEach(function(line) {
  5603. self.session = self.session.replace(line + '\r\n', '');
  5604. });
  5605. this.raw = this.session + this.media.join('');
  5606. return lines;
  5607. }
  5608. // remove lines matching prefix from a media section specified by mediaindex
  5609. // TODO: non-numeric mediaindex could match mid
  5610. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  5611. var self = this;
  5612. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  5613. lines.forEach(function(line) {
  5614. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  5615. });
  5616. this.raw = this.session + this.media.join('');
  5617. return lines;
  5618. }
  5619. // add content's to a jingle element
  5620. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  5621. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  5622. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  5623. var self = this;
  5624. // new bundle plan
  5625. if (SDPUtil.find_line(this.session, 'a=group:')) {
  5626. lines = SDPUtil.find_lines(this.session, 'a=group:');
  5627. for (i = 0; i < lines.length; i++) {
  5628. tmp = lines[i].split(' ');
  5629. var semantics = tmp.shift().substr(8);
  5630. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  5631. for (j = 0; j < tmp.length; j++) {
  5632. elem.c('content', {name: tmp[j]}).up();
  5633. }
  5634. elem.up();
  5635. }
  5636. }
  5637. for (i = 0; i < this.media.length; i++) {
  5638. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  5639. if (!(mline.media === 'audio' ||
  5640. mline.media === 'video' ||
  5641. mline.media === 'application'))
  5642. {
  5643. continue;
  5644. }
  5645. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  5646. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  5647. } else {
  5648. if(ssrcs && ssrcs[mline.media])
  5649. {
  5650. ssrc = ssrcs[mline.media];
  5651. }
  5652. else
  5653. ssrc = false;
  5654. }
  5655. elem.c('content', {creator: thecreator, name: mline.media});
  5656. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  5657. // prefer identifier from a=mid if present
  5658. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  5659. elem.attrs({ name: mid });
  5660. }
  5661. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  5662. {
  5663. elem.c('description',
  5664. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  5665. media: mline.media });
  5666. if (ssrc) {
  5667. elem.attrs({ssrc: ssrc});
  5668. }
  5669. for (j = 0; j < mline.fmt.length; j++) {
  5670. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  5671. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  5672. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  5673. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  5674. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  5675. for (k = 0; k < tmp.length; k++) {
  5676. elem.c('parameter', tmp[k]).up();
  5677. }
  5678. }
  5679. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  5680. elem.up();
  5681. }
  5682. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  5683. elem.c('encryption', {required: 1});
  5684. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  5685. crypto.forEach(function(line) {
  5686. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  5687. });
  5688. elem.up(); // end of encryption
  5689. }
  5690. if (ssrc) {
  5691. // new style mapping
  5692. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5693. // FIXME: group by ssrc and support multiple different ssrcs
  5694. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  5695. if(ssrclines.length > 0) {
  5696. ssrclines.forEach(function (line) {
  5697. idx = line.indexOf(' ');
  5698. var linessrc = line.substr(0, idx).substr(7);
  5699. if (linessrc != ssrc) {
  5700. elem.up();
  5701. ssrc = linessrc;
  5702. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5703. }
  5704. var kv = line.substr(idx + 1);
  5705. elem.c('parameter');
  5706. if (kv.indexOf(':') == -1) {
  5707. elem.attrs({ name: kv });
  5708. } else {
  5709. var k = kv.split(':', 2)[0];
  5710. elem.attrs({ name: k });
  5711. var v = kv.split(':', 2)[1];
  5712. v = SDPUtil.filter_special_chars(v);
  5713. elem.attrs({ value: v });
  5714. }
  5715. elem.up();
  5716. });
  5717. }
  5718. else
  5719. {
  5720. elem.up();
  5721. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5722. elem.c('parameter');
  5723. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  5724. elem.up();
  5725. var msid = null;
  5726. if(mline.media == "audio")
  5727. {
  5728. msid = APP.RTC.localAudio.getId();
  5729. }
  5730. else
  5731. {
  5732. msid = APP.RTC.localVideo.getId();
  5733. }
  5734. if(msid != null)
  5735. {
  5736. msid = SDPUtil.filter_special_chars(msid);
  5737. elem.c('parameter');
  5738. elem.attrs({name: "msid", value:msid});
  5739. elem.up();
  5740. elem.c('parameter');
  5741. elem.attrs({name: "mslabel", value:msid});
  5742. elem.up();
  5743. elem.c('parameter');
  5744. elem.attrs({name: "label", value:msid});
  5745. elem.up();
  5746. }
  5747. }
  5748. elem.up();
  5749. // XEP-0339 handle ssrc-group attributes
  5750. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  5751. ssrc_group_lines.forEach(function(line) {
  5752. idx = line.indexOf(' ');
  5753. var semantics = line.substr(0, idx).substr(13);
  5754. var ssrcs = line.substr(14 + semantics.length).split(' ');
  5755. if (ssrcs.length != 0) {
  5756. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5757. ssrcs.forEach(function(ssrc) {
  5758. elem.c('source', { ssrc: ssrc })
  5759. .up();
  5760. });
  5761. elem.up();
  5762. }
  5763. });
  5764. }
  5765. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  5766. elem.c('rtcp-mux').up();
  5767. }
  5768. // XEP-0293 -- map a=rtcp-fb:*
  5769. this.RtcpFbToJingle(i, elem, '*');
  5770. // XEP-0294
  5771. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  5772. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  5773. for (j = 0; j < lines.length; j++) {
  5774. tmp = SDPUtil.parse_extmap(lines[j]);
  5775. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  5776. uri: tmp.uri,
  5777. id: tmp.value });
  5778. if (tmp.hasOwnProperty('direction')) {
  5779. switch (tmp.direction) {
  5780. case 'sendonly':
  5781. elem.attrs({senders: 'responder'});
  5782. break;
  5783. case 'recvonly':
  5784. elem.attrs({senders: 'initiator'});
  5785. break;
  5786. case 'sendrecv':
  5787. elem.attrs({senders: 'both'});
  5788. break;
  5789. case 'inactive':
  5790. elem.attrs({senders: 'none'});
  5791. break;
  5792. }
  5793. }
  5794. // TODO: handle params
  5795. elem.up();
  5796. }
  5797. }
  5798. elem.up(); // end of description
  5799. }
  5800. // map ice-ufrag/pwd, dtls fingerprint, candidates
  5801. this.TransportToJingle(i, elem);
  5802. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  5803. elem.attrs({senders: 'both'});
  5804. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  5805. elem.attrs({senders: 'initiator'});
  5806. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  5807. elem.attrs({senders: 'responder'});
  5808. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  5809. elem.attrs({senders: 'none'});
  5810. }
  5811. if (mline.port == '0') {
  5812. // estos hack to reject an m-line
  5813. elem.attrs({senders: 'rejected'});
  5814. }
  5815. elem.up(); // end of content
  5816. }
  5817. elem.up();
  5818. return elem;
  5819. };
  5820. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  5821. var i = mediaindex;
  5822. var tmp;
  5823. var self = this;
  5824. elem.c('transport');
  5825. // XEP-0343 DTLS/SCTP
  5826. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  5827. {
  5828. var sctpmap = SDPUtil.find_line(
  5829. this.media[i], 'a=sctpmap:', self.session);
  5830. if (sctpmap)
  5831. {
  5832. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  5833. elem.c('sctpmap',
  5834. {
  5835. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  5836. number: sctpAttrs[0], /* SCTP port */
  5837. protocol: sctpAttrs[1], /* protocol */
  5838. });
  5839. // Optional stream count attribute
  5840. if (sctpAttrs.length > 2)
  5841. elem.attrs({ streams: sctpAttrs[2]});
  5842. elem.up();
  5843. }
  5844. }
  5845. // XEP-0320
  5846. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  5847. fingerprints.forEach(function(line) {
  5848. tmp = SDPUtil.parse_fingerprint(line);
  5849. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  5850. elem.c('fingerprint').t(tmp.fingerprint);
  5851. delete tmp.fingerprint;
  5852. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  5853. if (line) {
  5854. tmp.setup = line.substr(8);
  5855. }
  5856. elem.attrs(tmp);
  5857. elem.up(); // end of fingerprint
  5858. });
  5859. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  5860. if (tmp) {
  5861. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  5862. elem.attrs(tmp);
  5863. // XEP-0176
  5864. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  5865. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  5866. lines.forEach(function (line) {
  5867. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  5868. });
  5869. }
  5870. }
  5871. elem.up(); // end of transport
  5872. }
  5873. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  5874. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  5875. lines.forEach(function (line) {
  5876. var tmp = SDPUtil.parse_rtcpfb(line);
  5877. if (tmp.type == 'trr-int') {
  5878. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  5879. elem.up();
  5880. } else {
  5881. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  5882. if (tmp.params.length > 0) {
  5883. elem.attrs({'subtype': tmp.params[0]});
  5884. }
  5885. elem.up();
  5886. }
  5887. });
  5888. };
  5889. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  5890. var media = '';
  5891. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  5892. if (tmp.length) {
  5893. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  5894. if (tmp.attr('value')) {
  5895. media += tmp.attr('value');
  5896. } else {
  5897. media += '0';
  5898. }
  5899. media += '\r\n';
  5900. }
  5901. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  5902. tmp.each(function () {
  5903. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  5904. if ($(this).attr('subtype')) {
  5905. media += ' ' + $(this).attr('subtype');
  5906. }
  5907. media += '\r\n';
  5908. });
  5909. return media;
  5910. };
  5911. // construct an SDP from a jingle stanza
  5912. SDP.prototype.fromJingle = function (jingle) {
  5913. var self = this;
  5914. this.raw = 'v=0\r\n' +
  5915. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  5916. 's=-\r\n' +
  5917. 't=0 0\r\n';
  5918. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  5919. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  5920. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  5921. var contents = $(group).find('>content').map(function (idx, content) {
  5922. return content.getAttribute('name');
  5923. }).get();
  5924. if (contents.length > 0) {
  5925. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  5926. }
  5927. });
  5928. }
  5929. this.session = this.raw;
  5930. jingle.find('>content').each(function () {
  5931. var m = self.jingle2media($(this));
  5932. self.media.push(m);
  5933. });
  5934. // reconstruct msid-semantic -- apparently not necessary
  5935. /*
  5936. var msid = SDPUtil.parse_ssrc(this.raw);
  5937. if (msid.hasOwnProperty('mslabel')) {
  5938. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  5939. }
  5940. */
  5941. this.raw = this.session + this.media.join('');
  5942. };
  5943. // translate a jingle content element into an an SDP media part
  5944. SDP.prototype.jingle2media = function (content) {
  5945. var media = '',
  5946. desc = content.find('description'),
  5947. ssrc = desc.attr('ssrc'),
  5948. self = this,
  5949. tmp;
  5950. var sctp = content.find(
  5951. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  5952. tmp = { media: desc.attr('media') };
  5953. tmp.port = '1';
  5954. if (content.attr('senders') == 'rejected') {
  5955. // estos hack to reject an m-line.
  5956. tmp.port = '0';
  5957. }
  5958. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  5959. if (sctp.length)
  5960. tmp.proto = 'DTLS/SCTP';
  5961. else
  5962. tmp.proto = 'RTP/SAVPF';
  5963. } else {
  5964. tmp.proto = 'RTP/AVPF';
  5965. }
  5966. if (!sctp.length)
  5967. {
  5968. tmp.fmt = desc.find('payload-type').map(
  5969. function () { return this.getAttribute('id'); }).get();
  5970. media += SDPUtil.build_mline(tmp) + '\r\n';
  5971. }
  5972. else
  5973. {
  5974. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  5975. media += 'a=sctpmap:' + sctp.attr('number') +
  5976. ' ' + sctp.attr('protocol');
  5977. var streamCount = sctp.attr('streams');
  5978. if (streamCount)
  5979. media += ' ' + streamCount + '\r\n';
  5980. else
  5981. media += '\r\n';
  5982. }
  5983. media += 'c=IN IP4 0.0.0.0\r\n';
  5984. if (!sctp.length)
  5985. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  5986. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  5987. if (tmp.length) {
  5988. if (tmp.attr('ufrag')) {
  5989. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  5990. }
  5991. if (tmp.attr('pwd')) {
  5992. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  5993. }
  5994. tmp.find('>fingerprint').each(function () {
  5995. // FIXME: check namespace at some point
  5996. media += 'a=fingerprint:' + this.getAttribute('hash');
  5997. media += ' ' + $(this).text();
  5998. media += '\r\n';
  5999. if (this.getAttribute('setup')) {
  6000. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  6001. }
  6002. });
  6003. }
  6004. switch (content.attr('senders')) {
  6005. case 'initiator':
  6006. media += 'a=sendonly\r\n';
  6007. break;
  6008. case 'responder':
  6009. media += 'a=recvonly\r\n';
  6010. break;
  6011. case 'none':
  6012. media += 'a=inactive\r\n';
  6013. break;
  6014. case 'both':
  6015. media += 'a=sendrecv\r\n';
  6016. break;
  6017. }
  6018. media += 'a=mid:' + content.attr('name') + '\r\n';
  6019. // <description><rtcp-mux/></description>
  6020. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  6021. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  6022. if (desc.find('rtcp-mux').length) {
  6023. media += 'a=rtcp-mux\r\n';
  6024. }
  6025. if (desc.find('encryption').length) {
  6026. desc.find('encryption>crypto').each(function () {
  6027. media += 'a=crypto:' + this.getAttribute('tag');
  6028. media += ' ' + this.getAttribute('crypto-suite');
  6029. media += ' ' + this.getAttribute('key-params');
  6030. if (this.getAttribute('session-params')) {
  6031. media += ' ' + this.getAttribute('session-params');
  6032. }
  6033. media += '\r\n';
  6034. });
  6035. }
  6036. desc.find('payload-type').each(function () {
  6037. media += SDPUtil.build_rtpmap(this) + '\r\n';
  6038. if ($(this).find('>parameter').length) {
  6039. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  6040. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  6041. media += '\r\n';
  6042. }
  6043. // xep-0293
  6044. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  6045. });
  6046. // xep-0293
  6047. media += self.RtcpFbFromJingle(desc, '*');
  6048. // xep-0294
  6049. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  6050. tmp.each(function () {
  6051. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  6052. });
  6053. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  6054. media += SDPUtil.candidateFromJingle(this);
  6055. });
  6056. // XEP-0339 handle ssrc-group attributes
  6057. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  6058. var semantics = this.getAttribute('semantics');
  6059. var ssrcs = $(this).find('>source').map(function() {
  6060. return this.getAttribute('ssrc');
  6061. }).get();
  6062. if (ssrcs.length != 0) {
  6063. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  6064. }
  6065. });
  6066. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  6067. tmp.each(function () {
  6068. var ssrc = this.getAttribute('ssrc');
  6069. $(this).find('>parameter').each(function () {
  6070. var name = this.getAttribute('name');
  6071. var value = this.getAttribute('value');
  6072. value = SDPUtil.filter_special_chars(value);
  6073. media += 'a=ssrc:' + ssrc + ' ' + name;
  6074. if (value && value.length)
  6075. media += ':' + value;
  6076. media += '\r\n';
  6077. });
  6078. });
  6079. return media;
  6080. };
  6081. module.exports = SDP;
  6082. },{"./SDPUtil":24}],23:[function(require,module,exports){
  6083. var SDPUtil = require("./SDPUtil");
  6084. function SDPDiffer(mySDP, otherSDP) {
  6085. this.mySDP = mySDP;
  6086. this.otherSDP = otherSDP;
  6087. }
  6088. /**
  6089. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  6090. * @param otherSdp the other SDP to check ssrc with.
  6091. */
  6092. SDPDiffer.prototype.getNewMedia = function() {
  6093. // this could be useful in Array.prototype.
  6094. function arrayEquals(array) {
  6095. // if the other array is a falsy value, return
  6096. if (!array)
  6097. return false;
  6098. // compare lengths - can save a lot of time
  6099. if (this.length != array.length)
  6100. return false;
  6101. for (var i = 0, l=this.length; i < l; i++) {
  6102. // Check if we have nested arrays
  6103. if (this[i] instanceof Array && array[i] instanceof Array) {
  6104. // recurse into the nested arrays
  6105. if (!this[i].equals(array[i]))
  6106. return false;
  6107. }
  6108. else if (this[i] != array[i]) {
  6109. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  6110. return false;
  6111. }
  6112. }
  6113. return true;
  6114. }
  6115. var myMedias = this.mySDP.getMediaSsrcMap();
  6116. var othersMedias = this.otherSDP.getMediaSsrcMap();
  6117. var newMedia = {};
  6118. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  6119. var myMedia = myMedias[othersMediaIdx];
  6120. var othersMedia = othersMedias[othersMediaIdx];
  6121. if(!myMedia && othersMedia) {
  6122. // Add whole channel
  6123. newMedia[othersMediaIdx] = othersMedia;
  6124. return;
  6125. }
  6126. // Look for new ssrcs accross the channel
  6127. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  6128. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  6129. // Allocate channel if we've found ssrc that doesn't exist in our channel
  6130. if(!newMedia[othersMediaIdx]){
  6131. newMedia[othersMediaIdx] = {
  6132. mediaindex: othersMedia.mediaindex,
  6133. mid: othersMedia.mid,
  6134. ssrcs: {},
  6135. ssrcGroups: []
  6136. };
  6137. }
  6138. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  6139. }
  6140. });
  6141. // Look for new ssrc groups across the channels
  6142. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  6143. // try to match the other ssrc-group with an ssrc-group of ours
  6144. var matched = false;
  6145. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  6146. var mySsrcGroup = myMedia.ssrcGroups[i];
  6147. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  6148. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  6149. matched = true;
  6150. break;
  6151. }
  6152. }
  6153. if (!matched) {
  6154. // Allocate channel if we've found an ssrc-group that doesn't
  6155. // exist in our channel
  6156. if(!newMedia[othersMediaIdx]){
  6157. newMedia[othersMediaIdx] = {
  6158. mediaindex: othersMedia.mediaindex,
  6159. mid: othersMedia.mid,
  6160. ssrcs: {},
  6161. ssrcGroups: []
  6162. };
  6163. }
  6164. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  6165. }
  6166. });
  6167. });
  6168. return newMedia;
  6169. };
  6170. /**
  6171. * Sends SSRC update IQ.
  6172. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  6173. * @param sid session identifier that will be put into the IQ.
  6174. * @param initiator initiator identifier.
  6175. * @param toJid destination Jid
  6176. * @param isAdd indicates if this is remove or add operation.
  6177. */
  6178. SDPDiffer.prototype.toJingle = function(modify) {
  6179. var sdpMediaSsrcs = this.getNewMedia();
  6180. var self = this;
  6181. // FIXME: only announce video ssrcs since we mix audio and dont need
  6182. // the audio ssrcs therefore
  6183. var modified = false;
  6184. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  6185. modified = true;
  6186. var media = sdpMediaSsrcs[mediaindex];
  6187. modify.c('content', {name: media.mid});
  6188. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  6189. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  6190. // generate sources from lines
  6191. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  6192. var mediaSsrc = media.ssrcs[ssrcNum];
  6193. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  6194. modify.attrs({ssrc: mediaSsrc.ssrc});
  6195. // iterate over ssrc lines
  6196. mediaSsrc.lines.forEach(function (line) {
  6197. var idx = line.indexOf(' ');
  6198. var kv = line.substr(idx + 1);
  6199. modify.c('parameter');
  6200. if (kv.indexOf(':') == -1) {
  6201. modify.attrs({ name: kv });
  6202. } else {
  6203. var nv = kv.split(':', 2);
  6204. var name = nv[0];
  6205. var value = SDPUtil.filter_special_chars(nv[1]);
  6206. modify.attrs({ name: name });
  6207. modify.attrs({ value: value });
  6208. }
  6209. modify.up(); // end of parameter
  6210. });
  6211. modify.up(); // end of source
  6212. });
  6213. // generate source groups from lines
  6214. media.ssrcGroups.forEach(function(ssrcGroup) {
  6215. if (ssrcGroup.ssrcs.length != 0) {
  6216. modify.c('ssrc-group', {
  6217. semantics: ssrcGroup.semantics,
  6218. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  6219. });
  6220. ssrcGroup.ssrcs.forEach(function (ssrc) {
  6221. modify.c('source', { ssrc: ssrc })
  6222. .up(); // end of source
  6223. });
  6224. modify.up(); // end of ssrc-group
  6225. }
  6226. });
  6227. modify.up(); // end of description
  6228. modify.up(); // end of content
  6229. });
  6230. return modified;
  6231. };
  6232. module.exports = SDPDiffer;
  6233. },{"./SDPUtil":24}],24:[function(require,module,exports){
  6234. SDPUtil = {
  6235. filter_special_chars: function (text) {
  6236. return text.replace(/[\\\/\{,\}\+]/g, "");
  6237. },
  6238. iceparams: function (mediadesc, sessiondesc) {
  6239. var data = null;
  6240. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  6241. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  6242. data = {
  6243. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  6244. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  6245. };
  6246. }
  6247. return data;
  6248. },
  6249. parse_iceufrag: function (line) {
  6250. return line.substring(12);
  6251. },
  6252. build_iceufrag: function (frag) {
  6253. return 'a=ice-ufrag:' + frag;
  6254. },
  6255. parse_icepwd: function (line) {
  6256. return line.substring(10);
  6257. },
  6258. build_icepwd: function (pwd) {
  6259. return 'a=ice-pwd:' + pwd;
  6260. },
  6261. parse_mid: function (line) {
  6262. return line.substring(6);
  6263. },
  6264. parse_mline: function (line) {
  6265. var parts = line.substring(2).split(' '),
  6266. data = {};
  6267. data.media = parts.shift();
  6268. data.port = parts.shift();
  6269. data.proto = parts.shift();
  6270. if (parts[parts.length - 1] === '') { // trailing whitespace
  6271. parts.pop();
  6272. }
  6273. data.fmt = parts;
  6274. return data;
  6275. },
  6276. build_mline: function (mline) {
  6277. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  6278. },
  6279. parse_rtpmap: function (line) {
  6280. var parts = line.substring(9).split(' '),
  6281. data = {};
  6282. data.id = parts.shift();
  6283. parts = parts[0].split('/');
  6284. data.name = parts.shift();
  6285. data.clockrate = parts.shift();
  6286. data.channels = parts.length ? parts.shift() : '1';
  6287. return data;
  6288. },
  6289. /**
  6290. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  6291. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  6292. * @returns [SCTP port number, protocol, streams]
  6293. */
  6294. parse_sctpmap: function (line)
  6295. {
  6296. var parts = line.substring(10).split(' ');
  6297. var sctpPort = parts[0];
  6298. var protocol = parts[1];
  6299. // Stream count is optional
  6300. var streamCount = parts.length > 2 ? parts[2] : null;
  6301. return [sctpPort, protocol, streamCount];// SCTP port
  6302. },
  6303. build_rtpmap: function (el) {
  6304. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  6305. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  6306. line += '/' + el.getAttribute('channels');
  6307. }
  6308. return line;
  6309. },
  6310. parse_crypto: function (line) {
  6311. var parts = line.substring(9).split(' '),
  6312. data = {};
  6313. data.tag = parts.shift();
  6314. data['crypto-suite'] = parts.shift();
  6315. data['key-params'] = parts.shift();
  6316. if (parts.length) {
  6317. data['session-params'] = parts.join(' ');
  6318. }
  6319. return data;
  6320. },
  6321. parse_fingerprint: function (line) { // RFC 4572
  6322. var parts = line.substring(14).split(' '),
  6323. data = {};
  6324. data.hash = parts.shift();
  6325. data.fingerprint = parts.shift();
  6326. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  6327. return data;
  6328. },
  6329. parse_fmtp: function (line) {
  6330. var parts = line.split(' '),
  6331. i, key, value,
  6332. data = [];
  6333. parts.shift();
  6334. parts = parts.join(' ').split(';');
  6335. for (i = 0; i < parts.length; i++) {
  6336. key = parts[i].split('=')[0];
  6337. while (key.length && key[0] == ' ') {
  6338. key = key.substring(1);
  6339. }
  6340. value = parts[i].split('=')[1];
  6341. if (key && value) {
  6342. data.push({name: key, value: value});
  6343. } else if (key) {
  6344. // rfc 4733 (DTMF) style stuff
  6345. data.push({name: '', value: key});
  6346. }
  6347. }
  6348. return data;
  6349. },
  6350. parse_icecandidate: function (line) {
  6351. var candidate = {},
  6352. elems = line.split(' ');
  6353. candidate.foundation = elems[0].substring(12);
  6354. candidate.component = elems[1];
  6355. candidate.protocol = elems[2].toLowerCase();
  6356. candidate.priority = elems[3];
  6357. candidate.ip = elems[4];
  6358. candidate.port = elems[5];
  6359. // elems[6] => "typ"
  6360. candidate.type = elems[7];
  6361. candidate.generation = 0; // default value, may be overwritten below
  6362. for (var i = 8; i < elems.length; i += 2) {
  6363. switch (elems[i]) {
  6364. case 'raddr':
  6365. candidate['rel-addr'] = elems[i + 1];
  6366. break;
  6367. case 'rport':
  6368. candidate['rel-port'] = elems[i + 1];
  6369. break;
  6370. case 'generation':
  6371. candidate.generation = elems[i + 1];
  6372. break;
  6373. case 'tcptype':
  6374. candidate.tcptype = elems[i + 1];
  6375. break;
  6376. default: // TODO
  6377. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  6378. }
  6379. }
  6380. candidate.network = '1';
  6381. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  6382. return candidate;
  6383. },
  6384. build_icecandidate: function (cand) {
  6385. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  6386. line += ' ';
  6387. switch (cand.type) {
  6388. case 'srflx':
  6389. case 'prflx':
  6390. case 'relay':
  6391. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  6392. line += 'raddr';
  6393. line += ' ';
  6394. line += cand['rel-addr'];
  6395. line += ' ';
  6396. line += 'rport';
  6397. line += ' ';
  6398. line += cand['rel-port'];
  6399. line += ' ';
  6400. }
  6401. break;
  6402. }
  6403. if (cand.hasOwnAttribute('tcptype')) {
  6404. line += 'tcptype';
  6405. line += ' ';
  6406. line += cand.tcptype;
  6407. line += ' ';
  6408. }
  6409. line += 'generation';
  6410. line += ' ';
  6411. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  6412. return line;
  6413. },
  6414. parse_ssrc: function (desc) {
  6415. // proprietary mapping of a=ssrc lines
  6416. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  6417. // and parse according to that
  6418. var lines = desc.split('\r\n'),
  6419. data = {};
  6420. for (var i = 0; i < lines.length; i++) {
  6421. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  6422. var idx = lines[i].indexOf(' ');
  6423. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  6424. }
  6425. }
  6426. return data;
  6427. },
  6428. parse_rtcpfb: function (line) {
  6429. var parts = line.substr(10).split(' ');
  6430. var data = {};
  6431. data.pt = parts.shift();
  6432. data.type = parts.shift();
  6433. data.params = parts;
  6434. return data;
  6435. },
  6436. parse_extmap: function (line) {
  6437. var parts = line.substr(9).split(' ');
  6438. var data = {};
  6439. data.value = parts.shift();
  6440. if (data.value.indexOf('/') != -1) {
  6441. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  6442. data.value = data.value.substr(0, data.value.indexOf('/'));
  6443. } else {
  6444. data.direction = 'both';
  6445. }
  6446. data.uri = parts.shift();
  6447. data.params = parts;
  6448. return data;
  6449. },
  6450. find_line: function (haystack, needle, sessionpart) {
  6451. var lines = haystack.split('\r\n');
  6452. for (var i = 0; i < lines.length; i++) {
  6453. if (lines[i].substring(0, needle.length) == needle) {
  6454. return lines[i];
  6455. }
  6456. }
  6457. if (!sessionpart) {
  6458. return false;
  6459. }
  6460. // search session part
  6461. lines = sessionpart.split('\r\n');
  6462. for (var j = 0; j < lines.length; j++) {
  6463. if (lines[j].substring(0, needle.length) == needle) {
  6464. return lines[j];
  6465. }
  6466. }
  6467. return false;
  6468. },
  6469. find_lines: function (haystack, needle, sessionpart) {
  6470. var lines = haystack.split('\r\n'),
  6471. needles = [];
  6472. for (var i = 0; i < lines.length; i++) {
  6473. if (lines[i].substring(0, needle.length) == needle)
  6474. needles.push(lines[i]);
  6475. }
  6476. if (needles.length || !sessionpart) {
  6477. return needles;
  6478. }
  6479. // search session part
  6480. lines = sessionpart.split('\r\n');
  6481. for (var j = 0; j < lines.length; j++) {
  6482. if (lines[j].substring(0, needle.length) == needle) {
  6483. needles.push(lines[j]);
  6484. }
  6485. }
  6486. return needles;
  6487. },
  6488. candidateToJingle: function (line) {
  6489. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  6490. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  6491. if (line.indexOf('candidate:') === 0) {
  6492. line = 'a=' + line;
  6493. } else if (line.substring(0, 12) != 'a=candidate:') {
  6494. console.log('parseCandidate called with a line that is not a candidate line');
  6495. console.log(line);
  6496. return null;
  6497. }
  6498. if (line.substring(line.length - 2) == '\r\n') // chomp it
  6499. line = line.substring(0, line.length - 2);
  6500. var candidate = {},
  6501. elems = line.split(' '),
  6502. i;
  6503. if (elems[6] != 'typ') {
  6504. console.log('did not find typ in the right place');
  6505. console.log(line);
  6506. return null;
  6507. }
  6508. candidate.foundation = elems[0].substring(12);
  6509. candidate.component = elems[1];
  6510. candidate.protocol = elems[2].toLowerCase();
  6511. candidate.priority = elems[3];
  6512. candidate.ip = elems[4];
  6513. candidate.port = elems[5];
  6514. // elems[6] => "typ"
  6515. candidate.type = elems[7];
  6516. candidate.generation = '0'; // default, may be overwritten below
  6517. for (i = 8; i < elems.length; i += 2) {
  6518. switch (elems[i]) {
  6519. case 'raddr':
  6520. candidate['rel-addr'] = elems[i + 1];
  6521. break;
  6522. case 'rport':
  6523. candidate['rel-port'] = elems[i + 1];
  6524. break;
  6525. case 'generation':
  6526. candidate.generation = elems[i + 1];
  6527. break;
  6528. case 'tcptype':
  6529. candidate.tcptype = elems[i + 1];
  6530. break;
  6531. default: // TODO
  6532. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  6533. }
  6534. }
  6535. candidate.network = '1';
  6536. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  6537. return candidate;
  6538. },
  6539. candidateFromJingle: function (cand) {
  6540. var line = 'a=candidate:';
  6541. line += cand.getAttribute('foundation');
  6542. line += ' ';
  6543. line += cand.getAttribute('component');
  6544. line += ' ';
  6545. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  6546. line += ' ';
  6547. line += cand.getAttribute('priority');
  6548. line += ' ';
  6549. line += cand.getAttribute('ip');
  6550. line += ' ';
  6551. line += cand.getAttribute('port');
  6552. line += ' ';
  6553. line += 'typ';
  6554. line += ' ' + cand.getAttribute('type');
  6555. line += ' ';
  6556. switch (cand.getAttribute('type')) {
  6557. case 'srflx':
  6558. case 'prflx':
  6559. case 'relay':
  6560. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  6561. line += 'raddr';
  6562. line += ' ';
  6563. line += cand.getAttribute('rel-addr');
  6564. line += ' ';
  6565. line += 'rport';
  6566. line += ' ';
  6567. line += cand.getAttribute('rel-port');
  6568. line += ' ';
  6569. }
  6570. break;
  6571. }
  6572. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  6573. line += 'tcptype';
  6574. line += ' ';
  6575. line += cand.getAttribute('tcptype');
  6576. line += ' ';
  6577. }
  6578. line += 'generation';
  6579. line += ' ';
  6580. line += cand.getAttribute('generation') || '0';
  6581. return line + '\r\n';
  6582. }
  6583. };
  6584. module.exports = SDPUtil;
  6585. },{}],25:[function(require,module,exports){
  6586. var RTC = require('../RTC/RTC');
  6587. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  6588. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6589. var SSRCReplacement = require("./LocalSSRCReplacement");
  6590. function TraceablePeerConnection(ice_config, constraints, session) {
  6591. var self = this;
  6592. this.session = session;
  6593. var RTCPeerConnectionType = null;
  6594. if (RTCBrowserType.isFirefox()) {
  6595. RTCPeerConnectionType = mozRTCPeerConnection;
  6596. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  6597. RTCPeerConnectionType = RTCPeerConnection;
  6598. } else {
  6599. RTCPeerConnectionType = webkitRTCPeerConnection;
  6600. }
  6601. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  6602. this.updateLog = [];
  6603. this.stats = {};
  6604. this.statsinterval = null;
  6605. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  6606. var Interop = require('sdp-interop').Interop;
  6607. this.interop = new Interop();
  6608. var Simulcast = require('sdp-simulcast');
  6609. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  6610. // override as desired
  6611. this.trace = function (what, info) {
  6612. /*console.warn('WTRACE', what, info);
  6613. if (info && RTCBrowserType.isIExplorer()) {
  6614. if (info.length > 1024) {
  6615. console.warn('WTRACE', what, info.substr(1024));
  6616. }
  6617. if (info.length > 2048) {
  6618. console.warn('WTRACE', what, info.substr(2048));
  6619. }
  6620. }*/
  6621. self.updateLog.push({
  6622. time: new Date(),
  6623. type: what,
  6624. value: info || ""
  6625. });
  6626. };
  6627. this.onicecandidate = null;
  6628. this.peerconnection.onicecandidate = function (event) {
  6629. // FIXME: this causes stack overflow with Temasys Plugin
  6630. if (!RTCBrowserType.isTemasysPluginUsed())
  6631. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  6632. if (self.onicecandidate !== null) {
  6633. self.onicecandidate(event);
  6634. }
  6635. };
  6636. this.onaddstream = null;
  6637. this.peerconnection.onaddstream = function (event) {
  6638. self.trace('onaddstream', event.stream.id);
  6639. if (self.onaddstream !== null) {
  6640. self.onaddstream(event);
  6641. }
  6642. };
  6643. this.onremovestream = null;
  6644. this.peerconnection.onremovestream = function (event) {
  6645. self.trace('onremovestream', event.stream.id);
  6646. if (self.onremovestream !== null) {
  6647. self.onremovestream(event);
  6648. }
  6649. };
  6650. this.onsignalingstatechange = null;
  6651. this.peerconnection.onsignalingstatechange = function (event) {
  6652. self.trace('onsignalingstatechange', self.signalingState);
  6653. if (self.onsignalingstatechange !== null) {
  6654. self.onsignalingstatechange(event);
  6655. }
  6656. };
  6657. this.oniceconnectionstatechange = null;
  6658. this.peerconnection.oniceconnectionstatechange = function (event) {
  6659. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  6660. if (self.oniceconnectionstatechange !== null) {
  6661. self.oniceconnectionstatechange(event);
  6662. }
  6663. };
  6664. this.onnegotiationneeded = null;
  6665. this.peerconnection.onnegotiationneeded = function (event) {
  6666. self.trace('onnegotiationneeded');
  6667. if (self.onnegotiationneeded !== null) {
  6668. self.onnegotiationneeded(event);
  6669. }
  6670. };
  6671. self.ondatachannel = null;
  6672. this.peerconnection.ondatachannel = function (event) {
  6673. self.trace('ondatachannel', event);
  6674. if (self.ondatachannel !== null) {
  6675. self.ondatachannel(event);
  6676. }
  6677. };
  6678. // XXX: do all non-firefox browsers which we support also support this?
  6679. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  6680. this.statsinterval = window.setInterval(function() {
  6681. self.peerconnection.getStats(function(stats) {
  6682. var results = stats.result();
  6683. var now = new Date();
  6684. for (var i = 0; i < results.length; ++i) {
  6685. results[i].names().forEach(function (name) {
  6686. var id = results[i].id + '-' + name;
  6687. if (!self.stats[id]) {
  6688. self.stats[id] = {
  6689. startTime: now,
  6690. endTime: now,
  6691. values: [],
  6692. times: []
  6693. };
  6694. }
  6695. self.stats[id].values.push(results[i].stat(name));
  6696. self.stats[id].times.push(now.getTime());
  6697. if (self.stats[id].values.length > self.maxstats) {
  6698. self.stats[id].values.shift();
  6699. self.stats[id].times.shift();
  6700. }
  6701. self.stats[id].endTime = now;
  6702. });
  6703. }
  6704. });
  6705. }, 1000);
  6706. }
  6707. }
  6708. /**
  6709. * Returns a string representation of a SessionDescription object.
  6710. */
  6711. var dumpSDP = function(description) {
  6712. if (typeof description === 'undefined' || description == null) {
  6713. return '';
  6714. }
  6715. return 'type: ' + description.type + '\r\n' + description.sdp;
  6716. };
  6717. /**
  6718. * Takes a SessionDescription object and returns a "normalized" version.
  6719. * Currently it only takes care of ordering the a=ssrc lines.
  6720. */
  6721. var normalizePlanB = function(desc) {
  6722. if (typeof desc !== 'object' || desc === null ||
  6723. typeof desc.sdp !== 'string') {
  6724. console.warn('An empty description was passed as an argument.');
  6725. return desc;
  6726. }
  6727. var transform = require('sdp-transform');
  6728. var session = transform.parse(desc.sdp);
  6729. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  6730. Array.isArray(session.media)) {
  6731. session.media.forEach(function (mLine) {
  6732. // Chrome appears to be picky about the order in which a=ssrc lines
  6733. // are listed in an m-line when rtx is enabled (and thus there are
  6734. // a=ssrc-group lines with FID semantics). Specifically if we have
  6735. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  6736. // the "a=ssrc:S1" lines, SRD fails.
  6737. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  6738. // first.
  6739. var firstSsrcs = [];
  6740. var newSsrcLines = [];
  6741. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  6742. mLine.ssrcGroups.forEach(function (group) {
  6743. if (typeof group.semantics !== 'undefined' &&
  6744. group.semantics === 'FID') {
  6745. if (typeof group.ssrcs !== 'undefined') {
  6746. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  6747. }
  6748. }
  6749. });
  6750. }
  6751. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  6752. for (var i = 0; i<mLine.ssrcs.length; i++){
  6753. if (typeof mLine.ssrcs[i] === 'object'
  6754. && typeof mLine.ssrcs[i].id !== 'undefined'
  6755. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  6756. newSsrcLines.push(mLine.ssrcs[i]);
  6757. delete mLine.ssrcs[i];
  6758. }
  6759. }
  6760. for (var i = 0; i<mLine.ssrcs.length; i++){
  6761. if (typeof mLine.ssrcs[i] !== 'undefined') {
  6762. newSsrcLines.push(mLine.ssrcs[i]);
  6763. }
  6764. }
  6765. mLine.ssrcs = newSsrcLines;
  6766. }
  6767. });
  6768. }
  6769. var resStr = transform.write(session);
  6770. return new RTCSessionDescription({
  6771. type: desc.type,
  6772. sdp: resStr
  6773. });
  6774. };
  6775. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  6776. TraceablePeerConnection.prototype.__defineGetter__(
  6777. 'signalingState',
  6778. function() { return this.peerconnection.signalingState; });
  6779. TraceablePeerConnection.prototype.__defineGetter__(
  6780. 'iceConnectionState',
  6781. function() { return this.peerconnection.iceConnectionState; });
  6782. TraceablePeerConnection.prototype.__defineGetter__(
  6783. 'localDescription',
  6784. function() {
  6785. var desc = this.peerconnection.localDescription;
  6786. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  6787. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  6788. // if we're running on FF, transform to Plan B first.
  6789. if (RTCBrowserType.usesUnifiedPlan()) {
  6790. desc = this.interop.toPlanB(desc);
  6791. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  6792. }
  6793. return desc;
  6794. });
  6795. TraceablePeerConnection.prototype.__defineGetter__(
  6796. 'remoteDescription',
  6797. function() {
  6798. var desc = this.peerconnection.remoteDescription;
  6799. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  6800. // if we're running on FF, transform to Plan B first.
  6801. if (RTCBrowserType.usesUnifiedPlan()) {
  6802. desc = this.interop.toPlanB(desc);
  6803. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  6804. }
  6805. return desc;
  6806. });
  6807. }
  6808. TraceablePeerConnection.prototype.addStream = function (stream) {
  6809. this.trace('addStream', stream.id);
  6810. try
  6811. {
  6812. this.peerconnection.addStream(stream);
  6813. }
  6814. catch (e)
  6815. {
  6816. console.error(e);
  6817. }
  6818. };
  6819. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  6820. this.trace('removeStream', stream.id);
  6821. if(stopStreams) {
  6822. stream.getAudioTracks().forEach(function (track) {
  6823. // stop() not supported with IE
  6824. if (track.stop) {
  6825. track.stop();
  6826. }
  6827. });
  6828. stream.getVideoTracks().forEach(function (track) {
  6829. // stop() not supported with IE
  6830. if (track.stop) {
  6831. track.stop();
  6832. }
  6833. });
  6834. if (stream.stop) {
  6835. stream.stop();
  6836. }
  6837. }
  6838. try {
  6839. // FF doesn't support this yet.
  6840. if (this.peerconnection.removeStream)
  6841. this.peerconnection.removeStream(stream);
  6842. } catch (e) {
  6843. console.error(e);
  6844. }
  6845. };
  6846. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  6847. this.trace('createDataChannel', label, opts);
  6848. return this.peerconnection.createDataChannel(label, opts);
  6849. };
  6850. TraceablePeerConnection.prototype.setLocalDescription
  6851. = function (description, successCallback, failureCallback) {
  6852. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  6853. // if we're running on FF, transform to Plan A first.
  6854. if (RTCBrowserType.usesUnifiedPlan()) {
  6855. description = this.interop.toUnifiedPlan(description);
  6856. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  6857. }
  6858. var self = this;
  6859. this.peerconnection.setLocalDescription(description,
  6860. function () {
  6861. self.trace('setLocalDescriptionOnSuccess');
  6862. successCallback();
  6863. },
  6864. function (err) {
  6865. self.trace('setLocalDescriptionOnFailure', err);
  6866. failureCallback(err);
  6867. }
  6868. );
  6869. /*
  6870. if (this.statsinterval === null && this.maxstats > 0) {
  6871. // start gathering stats
  6872. }
  6873. */
  6874. };
  6875. TraceablePeerConnection.prototype.setRemoteDescription
  6876. = function (description, successCallback, failureCallback) {
  6877. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  6878. // TODO the focus should squeze or explode the remote simulcast
  6879. description = this.simulcast.mungeRemoteDescription(description);
  6880. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  6881. // if we're running on FF, transform to Plan A first.
  6882. if (RTCBrowserType.usesUnifiedPlan()) {
  6883. description = this.interop.toUnifiedPlan(description);
  6884. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  6885. }
  6886. if (RTCBrowserType.usesPlanB()) {
  6887. description = normalizePlanB(description);
  6888. }
  6889. var self = this;
  6890. this.peerconnection.setRemoteDescription(description,
  6891. function () {
  6892. self.trace('setRemoteDescriptionOnSuccess');
  6893. successCallback();
  6894. },
  6895. function (err) {
  6896. self.trace('setRemoteDescriptionOnFailure', err);
  6897. failureCallback(err);
  6898. }
  6899. );
  6900. /*
  6901. if (this.statsinterval === null && this.maxstats > 0) {
  6902. // start gathering stats
  6903. }
  6904. */
  6905. };
  6906. TraceablePeerConnection.prototype.close = function () {
  6907. this.trace('stop');
  6908. if (this.statsinterval !== null) {
  6909. window.clearInterval(this.statsinterval);
  6910. this.statsinterval = null;
  6911. }
  6912. this.peerconnection.close();
  6913. };
  6914. TraceablePeerConnection.prototype.createOffer
  6915. = function (successCallback, failureCallback, constraints) {
  6916. var self = this;
  6917. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  6918. this.peerconnection.createOffer(
  6919. function (offer) {
  6920. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  6921. // NOTE this is not tested because in meet the focus generates the
  6922. // offer.
  6923. // if we're running on FF, transform to Plan B first.
  6924. if (RTCBrowserType.usesUnifiedPlan()) {
  6925. offer = self.interop.toPlanB(offer);
  6926. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  6927. }
  6928. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  6929. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  6930. offer = self.simulcast.mungeLocalDescription(offer);
  6931. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  6932. }
  6933. successCallback(offer);
  6934. },
  6935. function(err) {
  6936. self.trace('createOfferOnFailure', err);
  6937. failureCallback(err);
  6938. },
  6939. constraints
  6940. );
  6941. };
  6942. TraceablePeerConnection.prototype.createAnswer
  6943. = function (successCallback, failureCallback, constraints) {
  6944. var self = this;
  6945. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  6946. this.peerconnection.createAnswer(
  6947. function (answer) {
  6948. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  6949. // if we're running on FF, transform to Plan A first.
  6950. if (RTCBrowserType.usesUnifiedPlan()) {
  6951. answer = self.interop.toPlanB(answer);
  6952. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  6953. }
  6954. // munge local video SSRC
  6955. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  6956. if (self.session.room.options.enableSimulcast && self.simulcast.isSupported()) {
  6957. answer = self.simulcast.mungeLocalDescription(answer);
  6958. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  6959. }
  6960. successCallback(answer);
  6961. },
  6962. function(err) {
  6963. self.trace('createAnswerOnFailure', err);
  6964. failureCallback(err);
  6965. },
  6966. constraints
  6967. );
  6968. };
  6969. TraceablePeerConnection.prototype.addIceCandidate
  6970. = function (candidate, successCallback, failureCallback) {
  6971. //var self = this;
  6972. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  6973. this.peerconnection.addIceCandidate(candidate);
  6974. /* maybe later
  6975. this.peerconnection.addIceCandidate(candidate,
  6976. function () {
  6977. self.trace('addIceCandidateOnSuccess');
  6978. successCallback();
  6979. },
  6980. function (err) {
  6981. self.trace('addIceCandidateOnFailure', err);
  6982. failureCallback(err);
  6983. }
  6984. );
  6985. */
  6986. };
  6987. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  6988. // TODO: Is this the correct way to handle Opera, Temasys?
  6989. if (RTCBrowserType.isFirefox()) {
  6990. // ignore for now...
  6991. if(!errback)
  6992. errback = function () {};
  6993. this.peerconnection.getStats(null, callback, errback);
  6994. } else {
  6995. this.peerconnection.getStats(callback);
  6996. }
  6997. };
  6998. module.exports = TraceablePeerConnection;
  6999. },{"../../service/xmpp/XMPPEvents":75,"../RTC/RTC":12,"../RTC/RTCBrowserType.js":13,"./LocalSSRCReplacement":21,"sdp-interop":52,"sdp-simulcast":59,"sdp-transform":66}],26:[function(require,module,exports){
  7000. /* global $, $iq, APP, config, messageHandler,
  7001. roomName, sessionTerminated, Strophe, Util */
  7002. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7003. var Settings = require("../settings/Settings");
  7004. var AuthenticationEvents
  7005. = require("../../service/authentication/AuthenticationEvents");
  7006. function createExpBackoffTimer(step) {
  7007. var count = 1;
  7008. return function (reset) {
  7009. // Reset call
  7010. if (reset) {
  7011. count = 1;
  7012. return;
  7013. }
  7014. // Calculate next timeout
  7015. var timeout = Math.pow(2, count - 1);
  7016. count += 1;
  7017. return timeout * step;
  7018. };
  7019. }
  7020. function Moderator(roomName, xmpp, emitter) {
  7021. this.roomName = roomName;
  7022. this.xmppService = xmpp;
  7023. this.getNextTimeout = createExpBackoffTimer(1000);
  7024. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  7025. // External authentication stuff
  7026. this.externalAuthEnabled = false;
  7027. this.settings = new Settings(roomName);
  7028. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  7029. // it will be enabled automatically if focus detects the component through
  7030. // service discovery.
  7031. this.sipGatewayEnabled = this.xmppService.options.hosts.call_control !== undefined;
  7032. this.eventEmitter = emitter;
  7033. this.connection = this.xmppService.connection;
  7034. this.focusUserJid;
  7035. //FIXME:
  7036. // Message listener that talks to POPUP window
  7037. function listener(event) {
  7038. if (event.data && event.data.sessionId) {
  7039. if (event.origin !== window.location.origin) {
  7040. console.warn("Ignoring sessionId from different origin: " +
  7041. event.origin);
  7042. return;
  7043. }
  7044. localStorage.setItem('sessionId', event.data.sessionId);
  7045. // After popup is closed we will authenticate
  7046. }
  7047. }
  7048. // Register
  7049. if (window.addEventListener) {
  7050. window.addEventListener("message", listener, false);
  7051. } else {
  7052. window.attachEvent("onmessage", listener);
  7053. }
  7054. }
  7055. Moderator.prototype.isExternalAuthEnabled = function () {
  7056. return this.externalAuthEnabled;
  7057. };
  7058. Moderator.prototype.isSipGatewayEnabled = function () {
  7059. return this.sipGatewayEnabled;
  7060. };
  7061. Moderator.prototype.onMucMemberLeft = function (jid) {
  7062. console.info("Someone left is it focus ? " + jid);
  7063. var resource = Strophe.getResourceFromJid(jid);
  7064. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  7065. console.info(
  7066. "Focus has left the room - leaving conference");
  7067. //hangUp();
  7068. // We'd rather reload to have everything re-initialized
  7069. //FIXME: show some message before reload
  7070. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  7071. }
  7072. };
  7073. Moderator.prototype.setFocusUserJid = function (focusJid) {
  7074. if (!this.focusUserJid) {
  7075. this.focusUserJid = focusJid;
  7076. console.info("Focus jid set to: " + this.focusUserJid);
  7077. }
  7078. };
  7079. Moderator.prototype.getFocusUserJid = function () {
  7080. return this.focusUserJid;
  7081. };
  7082. Moderator.prototype.getFocusComponent = function () {
  7083. // Get focus component address
  7084. var focusComponent = this.xmppService.options.hosts.focus;
  7085. // If not specified use default: 'focus.domain'
  7086. if (!focusComponent) {
  7087. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  7088. }
  7089. return focusComponent;
  7090. };
  7091. Moderator.prototype.createConferenceIq = function () {
  7092. // Generate create conference IQ
  7093. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  7094. // Session Id used for authentication
  7095. var sessionId = localStorage.getItem('sessionId');
  7096. var machineUID = this.settings.getSettings().uid;
  7097. console.info(
  7098. "Session ID: " + sessionId + " machine UID: " + machineUID);
  7099. elem.c('conference', {
  7100. xmlns: 'http://jitsi.org/protocol/focus',
  7101. room: this.roomName,
  7102. 'machine-uid': machineUID
  7103. });
  7104. if (sessionId) {
  7105. elem.attrs({ 'session-id': sessionId});
  7106. }
  7107. if (this.xmppService.options.hosts.bridge !== undefined) {
  7108. elem.c(
  7109. 'property',
  7110. {name: 'bridge',value: this.xmppService.options.hosts.bridge})
  7111. .up();
  7112. }
  7113. // Tell the focus we have Jigasi configured
  7114. if (this.xmppService.options.hosts.call_control !== undefined) {
  7115. elem.c(
  7116. 'property',
  7117. {name: 'call_control',value: this.xmppService.options.hosts.call_control})
  7118. .up();
  7119. }
  7120. if (this.xmppService.options.channelLastN !== undefined) {
  7121. elem.c(
  7122. 'property',
  7123. {name: 'channelLastN',value: this.xmppService.options.channelLastN})
  7124. .up();
  7125. }
  7126. if (this.xmppService.options.adaptiveLastN !== undefined) {
  7127. elem.c(
  7128. 'property',
  7129. {name: 'adaptiveLastN',value: this.xmppService.options.adaptiveLastN})
  7130. .up();
  7131. }
  7132. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  7133. elem.c(
  7134. 'property',
  7135. {name: 'adaptiveSimulcast',value: this.xmppService.options.adaptiveSimulcast})
  7136. .up();
  7137. }
  7138. if (this.xmppService.options.openSctp !== undefined) {
  7139. elem.c(
  7140. 'property',
  7141. {name: 'openSctp',value: this.xmppService.options.openSctp})
  7142. .up();
  7143. }
  7144. if(this.xmppService.options.startAudioMuted !== undefined)
  7145. {
  7146. elem.c(
  7147. 'property',
  7148. {name: 'startAudioMuted',value: this.xmppService.options.startAudioMuted})
  7149. .up();
  7150. }
  7151. if(this.xmppService.options.startVideoMuted !== undefined)
  7152. {
  7153. elem.c(
  7154. 'property',
  7155. {name: 'startVideoMuted',value: this.xmppService.options.startVideoMuted})
  7156. .up();
  7157. }
  7158. elem.c(
  7159. 'property',
  7160. {name: 'simulcastMode',value: 'rewriting'})
  7161. .up();
  7162. elem.up();
  7163. return elem;
  7164. };
  7165. Moderator.prototype.parseSessionId = function (resultIq) {
  7166. var sessionId = $(resultIq).find('conference').attr('session-id');
  7167. if (sessionId) {
  7168. console.info('Received sessionId: ' + sessionId);
  7169. localStorage.setItem('sessionId', sessionId);
  7170. }
  7171. };
  7172. Moderator.prototype.parseConfigOptions = function (resultIq) {
  7173. this.setFocusUserJid(
  7174. $(resultIq).find('conference').attr('focusjid'));
  7175. var authenticationEnabled
  7176. = $(resultIq).find(
  7177. '>conference>property' +
  7178. '[name=\'authentication\'][value=\'true\']').length > 0;
  7179. console.info("Authentication enabled: " + authenticationEnabled);
  7180. this.externalAuthEnabled = $(resultIq).find(
  7181. '>conference>property' +
  7182. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  7183. console.info('External authentication enabled: ' + this.externalAuthEnabled);
  7184. if (!this.externalAuthEnabled) {
  7185. // We expect to receive sessionId in 'internal' authentication mode
  7186. this.parseSessionId(resultIq);
  7187. }
  7188. var authIdentity = $(resultIq).find('>conference').attr('identity');
  7189. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  7190. authenticationEnabled, authIdentity);
  7191. // Check if focus has auto-detected Jigasi component(this will be also
  7192. // included if we have passed our host from the config)
  7193. if ($(resultIq).find(
  7194. '>conference>property' +
  7195. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  7196. this.sipGatewayEnabled = true;
  7197. }
  7198. console.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  7199. };
  7200. // FIXME = we need to show the fact that we're waiting for the focus
  7201. // to the user(or that focus is not available)
  7202. Moderator.prototype.allocateConferenceFocus = function ( callback) {
  7203. // Try to use focus user JID from the config
  7204. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  7205. // Send create conference IQ
  7206. var iq = this.createConferenceIq();
  7207. var self = this;
  7208. this.connection.sendIQ(
  7209. iq,
  7210. function (result) {
  7211. // Setup config options
  7212. self.parseConfigOptions(result);
  7213. if ('true' === $(result).find('conference').attr('ready')) {
  7214. // Reset both timers
  7215. self.getNextTimeout(true);
  7216. self.getNextErrorTimeout(true);
  7217. // Exec callback
  7218. callback();
  7219. } else {
  7220. var waitMs = self.getNextTimeout();
  7221. console.info("Waiting for the focus... " + waitMs);
  7222. // Reset error timeout
  7223. self.getNextErrorTimeout(true);
  7224. window.setTimeout(
  7225. function () {
  7226. self.allocateConferenceFocus(callback);
  7227. }, waitMs);
  7228. }
  7229. },
  7230. function (error) {
  7231. // Invalid session ? remove and try again
  7232. // without session ID to get a new one
  7233. var invalidSession
  7234. = $(error).find('>error>session-invalid').length;
  7235. if (invalidSession) {
  7236. console.info("Session expired! - removing");
  7237. localStorage.removeItem("sessionId");
  7238. }
  7239. if ($(error).find('>error>graceful-shutdown').length) {
  7240. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  7241. return;
  7242. }
  7243. // Check for error returned by the reservation system
  7244. var reservationErr = $(error).find('>error>reservation-error');
  7245. if (reservationErr.length) {
  7246. // Trigger error event
  7247. var errorCode = reservationErr.attr('error-code');
  7248. var errorMsg;
  7249. if ($(error).find('>error>text')) {
  7250. errorMsg = $(error).find('>error>text').text();
  7251. }
  7252. self.eventEmitter.emit(
  7253. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  7254. return;
  7255. }
  7256. // Not authorized to create new room
  7257. if ($(error).find('>error>not-authorized').length) {
  7258. console.warn("Unauthorized to start the conference", error);
  7259. var toDomain
  7260. = Strophe.getDomainFromJid(error.getAttribute('to'));
  7261. if (toDomain !== this.xmppService.options.hosts.anonymousdomain) {
  7262. //FIXME: "is external" should come either from
  7263. // the focus or config.js
  7264. self.externalAuthEnabled = true;
  7265. }
  7266. self.eventEmitter.emit(
  7267. XMPPEvents.AUTHENTICATION_REQUIRED,
  7268. function () {
  7269. self.allocateConferenceFocus(
  7270. callback);
  7271. });
  7272. return;
  7273. }
  7274. var waitMs = self.getNextErrorTimeout();
  7275. console.error("Focus error, retry after " + waitMs, error);
  7276. // Show message
  7277. var focusComponent = self.getFocusComponent();
  7278. var retrySec = waitMs / 1000;
  7279. //FIXME: message is duplicated ?
  7280. // Do not show in case of session invalid
  7281. // which means just a retry
  7282. if (!invalidSession) {
  7283. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  7284. focusComponent, retrySec);
  7285. }
  7286. // Reset response timeout
  7287. self.getNextTimeout(true);
  7288. window.setTimeout(
  7289. function () {
  7290. self.allocateConferenceFocus(callback);
  7291. }, waitMs);
  7292. }
  7293. );
  7294. };
  7295. Moderator.prototype.getLoginUrl = function (urlCallback) {
  7296. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  7297. iq.c('login-url', {
  7298. xmlns: 'http://jitsi.org/protocol/focus',
  7299. room: this.roomName,
  7300. 'machine-uid': this.settings.getSettings().uid
  7301. });
  7302. this.connection.sendIQ(
  7303. iq,
  7304. function (result) {
  7305. var url = $(result).find('login-url').attr('url');
  7306. url = url = decodeURIComponent(url);
  7307. if (url) {
  7308. console.info("Got auth url: " + url);
  7309. urlCallback(url);
  7310. } else {
  7311. console.error(
  7312. "Failed to get auth url from the focus", result);
  7313. }
  7314. },
  7315. function (error) {
  7316. console.error("Get auth url error", error);
  7317. }
  7318. );
  7319. };
  7320. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  7321. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  7322. iq.c('login-url', {
  7323. xmlns: 'http://jitsi.org/protocol/focus',
  7324. room: this.roomName,
  7325. 'machine-uid': this.settings.getSettings().uid,
  7326. popup: true
  7327. });
  7328. this.connection.sendIQ(
  7329. iq,
  7330. function (result) {
  7331. var url = $(result).find('login-url').attr('url');
  7332. url = url = decodeURIComponent(url);
  7333. if (url) {
  7334. console.info("Got POPUP auth url: " + url);
  7335. urlCallback(url);
  7336. } else {
  7337. console.error(
  7338. "Failed to get POPUP auth url from the focus", result);
  7339. }
  7340. },
  7341. function (error) {
  7342. console.error('Get POPUP auth url error', error);
  7343. }
  7344. );
  7345. };
  7346. Moderator.prototype.logout = function (callback) {
  7347. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  7348. var sessionId = localStorage.getItem('sessionId');
  7349. if (!sessionId) {
  7350. callback();
  7351. return;
  7352. }
  7353. iq.c('logout', {
  7354. xmlns: 'http://jitsi.org/protocol/focus',
  7355. 'session-id': sessionId
  7356. });
  7357. this.connection.sendIQ(
  7358. iq,
  7359. function (result) {
  7360. var logoutUrl = $(result).find('logout').attr('logout-url');
  7361. if (logoutUrl) {
  7362. logoutUrl = decodeURIComponent(logoutUrl);
  7363. }
  7364. console.info("Log out OK, url: " + logoutUrl, result);
  7365. localStorage.removeItem('sessionId');
  7366. callback(logoutUrl);
  7367. },
  7368. function (error) {
  7369. console.error("Logout error", error);
  7370. }
  7371. );
  7372. };
  7373. module.exports = Moderator;
  7374. },{"../../service/authentication/AuthenticationEvents":73,"../../service/xmpp/XMPPEvents":75,"../settings/Settings":17}],27:[function(require,module,exports){
  7375. /* jshint -W117 */
  7376. /* a simple MUC connection plugin
  7377. * can only handle a single MUC room
  7378. */
  7379. var ChatRoom = require("./ChatRoom");
  7380. module.exports = function(XMPP) {
  7381. Strophe.addConnectionPlugin('emuc', {
  7382. connection: null,
  7383. rooms: {},//map with the rooms
  7384. init: function (conn) {
  7385. this.connection = conn;
  7386. // add handlers (just once)
  7387. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  7388. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  7389. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  7390. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  7391. },
  7392. createRoom: function (jid, password, options) {
  7393. var roomJid = Strophe.getBareJidFromJid(jid);
  7394. if (this.rooms[roomJid]) {
  7395. console.error("You are already in the room!");
  7396. return;
  7397. }
  7398. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
  7399. return this.rooms[roomJid];
  7400. },
  7401. doLeave: function (jid) {
  7402. this.rooms[jid].doLeave();
  7403. delete this.rooms[jid];
  7404. },
  7405. onPresence: function (pres) {
  7406. var from = pres.getAttribute('from');
  7407. // What is this for? A workaround for something?
  7408. if (pres.getAttribute('type')) {
  7409. return true;
  7410. }
  7411. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7412. if(!room)
  7413. return;
  7414. // Parse status.
  7415. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  7416. room.createNonAnonymousRoom();
  7417. }
  7418. room.onPresence(pres);
  7419. return true;
  7420. },
  7421. onPresenceUnavailable: function (pres) {
  7422. var from = pres.getAttribute('from');
  7423. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7424. if(!room)
  7425. return;
  7426. room.onPresenceUnavailable(pres, from);
  7427. return true;
  7428. },
  7429. onPresenceError: function (pres) {
  7430. var from = pres.getAttribute('from');
  7431. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7432. if(!room)
  7433. return;
  7434. room.onPresenceError(pres, from);
  7435. return true;
  7436. },
  7437. onMessage: function (msg) {
  7438. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  7439. var from = msg.getAttribute('from');
  7440. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7441. if(!room)
  7442. return;
  7443. room.onMessage(msg, from);
  7444. return true;
  7445. },
  7446. setJingleSession: function (from, session) {
  7447. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  7448. if(!room)
  7449. return;
  7450. room.setJingleSession(session);
  7451. }
  7452. });
  7453. };
  7454. },{"./ChatRoom":18}],28:[function(require,module,exports){
  7455. /* jshint -W117 */
  7456. var JingleSession = require("./JingleSessionPC");
  7457. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7458. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7459. module.exports = function(XMPP, eventEmitter) {
  7460. Strophe.addConnectionPlugin('jingle', {
  7461. connection: null,
  7462. sessions: {},
  7463. jid2session: {},
  7464. ice_config: {iceServers: []},
  7465. media_constraints: {
  7466. mandatory: {
  7467. 'OfferToReceiveAudio': true,
  7468. 'OfferToReceiveVideo': true
  7469. }
  7470. // MozDontOfferDataChannel: true when this is firefox
  7471. },
  7472. init: function (conn) {
  7473. this.connection = conn;
  7474. if (this.connection.disco) {
  7475. // http://xmpp.org/extensions/xep-0167.html#support
  7476. // http://xmpp.org/extensions/xep-0176.html#support
  7477. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  7478. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  7479. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  7480. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  7481. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  7482. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  7483. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  7484. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  7485. || RTCBrowserType.isTemasysPluginUsed()) {
  7486. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  7487. }
  7488. // this is dealt with by SDP O/A so we don't need to announce this
  7489. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  7490. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  7491. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  7492. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  7493. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  7494. }
  7495. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  7496. },
  7497. onJingle: function (iq) {
  7498. var sid = $(iq).find('jingle').attr('sid');
  7499. var action = $(iq).find('jingle').attr('action');
  7500. var fromJid = iq.getAttribute('from');
  7501. // send ack first
  7502. var ack = $iq({type: 'result',
  7503. to: fromJid,
  7504. id: iq.getAttribute('id')
  7505. });
  7506. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  7507. var sess = this.sessions[sid];
  7508. if ('session-initiate' != action) {
  7509. if (sess === null) {
  7510. ack.type = 'error';
  7511. ack.c('error', {type: 'cancel'})
  7512. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  7513. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  7514. this.connection.send(ack);
  7515. return true;
  7516. }
  7517. // local jid is not checked
  7518. if (fromJid != sess.peerjid) {
  7519. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  7520. ack.type = 'error';
  7521. ack.c('error', {type: 'cancel'})
  7522. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  7523. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  7524. this.connection.send(ack);
  7525. return true;
  7526. }
  7527. } else if (sess !== undefined) {
  7528. // existing session with same session id
  7529. // this might be out-of-order if the sess.peerjid is the same as from
  7530. ack.type = 'error';
  7531. ack.c('error', {type: 'cancel'})
  7532. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  7533. console.warn('duplicate session id', sid);
  7534. this.connection.send(ack);
  7535. return true;
  7536. }
  7537. // FIXME: check for a defined action
  7538. this.connection.send(ack);
  7539. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  7540. switch (action) {
  7541. case 'session-initiate':
  7542. var startMuted = $(iq).find('jingle>startmuted');
  7543. if (startMuted && startMuted.length > 0) {
  7544. var audioMuted = startMuted.attr("audio");
  7545. var videoMuted = startMuted.attr("video");
  7546. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  7547. audioMuted === "true", videoMuted === "true");
  7548. }
  7549. sess = new JingleSession(
  7550. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  7551. this.connection, XMPP, eventEmitter);
  7552. // configure session
  7553. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  7554. this.connection.emuc.setJingleSession(fromBareJid, sess);
  7555. sess.media_constraints = this.media_constraints;
  7556. sess.ice_config = this.ice_config;
  7557. sess.initialize(fromJid, false);
  7558. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  7559. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  7560. sess.setOffer($(iq).find('>jingle'));
  7561. this.sessions[sess.sid] = sess;
  7562. this.jid2session[sess.peerjid] = sess;
  7563. // the callback should either
  7564. // .sendAnswer and .accept
  7565. // or .sendTerminate -- not necessarily synchronous
  7566. sess.sendAnswer();
  7567. sess.accept();
  7568. break;
  7569. case 'session-accept':
  7570. sess.setAnswer($(iq).find('>jingle'));
  7571. sess.accept();
  7572. break;
  7573. case 'session-terminate':
  7574. // If this is not the focus sending the terminate, we have
  7575. // nothing more to do here.
  7576. if (Object.keys(this.sessions).length < 1
  7577. || !(this.sessions[Object.keys(this.sessions)[0]]
  7578. instanceof JingleSession))
  7579. {
  7580. break;
  7581. }
  7582. console.log('terminating...', sess.sid);
  7583. sess.terminate();
  7584. this.terminate(sess.sid);
  7585. if ($(iq).find('>jingle>reason').length) {
  7586. $(document).trigger('callterminated.jingle', [
  7587. sess.sid,
  7588. sess.peerjid,
  7589. $(iq).find('>jingle>reason>:first')[0].tagName,
  7590. $(iq).find('>jingle>reason>text').text()
  7591. ]);
  7592. } else {
  7593. $(document).trigger('callterminated.jingle',
  7594. [sess.sid, sess.peerjid]);
  7595. }
  7596. break;
  7597. case 'transport-info':
  7598. sess.addIceCandidate($(iq).find('>jingle>content'));
  7599. break;
  7600. case 'session-info':
  7601. var affected;
  7602. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7603. $(document).trigger('ringing.jingle', [sess.sid]);
  7604. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7605. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  7606. $(document).trigger('mute.jingle', [sess.sid, affected]);
  7607. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  7608. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  7609. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  7610. }
  7611. break;
  7612. case 'addsource': // FIXME: proprietary, un-jingleish
  7613. case 'source-add': // FIXME: proprietary
  7614. sess.addSource($(iq).find('>jingle>content'), fromJid);
  7615. break;
  7616. case 'removesource': // FIXME: proprietary, un-jingleish
  7617. case 'source-remove': // FIXME: proprietary
  7618. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  7619. break;
  7620. default:
  7621. console.warn('jingle action not implemented', action);
  7622. break;
  7623. }
  7624. return true;
  7625. },
  7626. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  7627. if (sid === null || sid === undefined) {
  7628. for (sid in this.sessions) {
  7629. if (this.sessions[sid].state != 'ended') {
  7630. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  7631. this.sessions[sid].terminate();
  7632. }
  7633. delete this.jid2session[this.sessions[sid].peerjid];
  7634. delete this.sessions[sid];
  7635. }
  7636. } else if (this.sessions.hasOwnProperty(sid)) {
  7637. if (this.sessions[sid].state != 'ended') {
  7638. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  7639. this.sessions[sid].terminate();
  7640. }
  7641. delete this.jid2session[this.sessions[sid].peerjid];
  7642. delete this.sessions[sid];
  7643. }
  7644. },
  7645. getStunAndTurnCredentials: function () {
  7646. // get stun and turn configuration from server via xep-0215
  7647. // uses time-limited credentials as described in
  7648. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  7649. //
  7650. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  7651. // for a prosody module which implements this
  7652. //
  7653. // currently, this doesn't work with updateIce and therefore credentials with a long
  7654. // validity have to be fetched before creating the peerconnection
  7655. // TODO: implement refresh via updateIce as described in
  7656. // https://code.google.com/p/webrtc/issues/detail?id=1650
  7657. var self = this;
  7658. this.connection.sendIQ(
  7659. $iq({type: 'get', to: this.connection.domain})
  7660. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  7661. function (res) {
  7662. var iceservers = [];
  7663. $(res).find('>services>service').each(function (idx, el) {
  7664. el = $(el);
  7665. var dict = {};
  7666. var type = el.attr('type');
  7667. switch (type) {
  7668. case 'stun':
  7669. dict.url = 'stun:' + el.attr('host');
  7670. if (el.attr('port')) {
  7671. dict.url += ':' + el.attr('port');
  7672. }
  7673. iceservers.push(dict);
  7674. break;
  7675. case 'turn':
  7676. case 'turns':
  7677. dict.url = type + ':';
  7678. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  7679. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  7680. dict.url += el.attr('username') + '@';
  7681. } else {
  7682. dict.username = el.attr('username'); // only works in M28
  7683. }
  7684. }
  7685. dict.url += el.attr('host');
  7686. if (el.attr('port') && el.attr('port') != '3478') {
  7687. dict.url += ':' + el.attr('port');
  7688. }
  7689. if (el.attr('transport') && el.attr('transport') != 'udp') {
  7690. dict.url += '?transport=' + el.attr('transport');
  7691. }
  7692. if (el.attr('password')) {
  7693. dict.credential = el.attr('password');
  7694. }
  7695. iceservers.push(dict);
  7696. break;
  7697. }
  7698. });
  7699. self.ice_config.iceServers = iceservers;
  7700. },
  7701. function (err) {
  7702. console.warn('getting turn credentials failed', err);
  7703. console.warn('is mod_turncredentials or similar installed?');
  7704. }
  7705. );
  7706. // implement push?
  7707. },
  7708. /**
  7709. * Returns the data saved in 'updateLog' in a format to be logged.
  7710. */
  7711. getLog: function () {
  7712. var data = {};
  7713. var self = this;
  7714. Object.keys(this.sessions).forEach(function (sid) {
  7715. var session = self.sessions[sid];
  7716. if (session.peerconnection && session.peerconnection.updateLog) {
  7717. // FIXME: should probably be a .dump call
  7718. data["jingle_" + session.sid] = {
  7719. updateLog: session.peerconnection.updateLog,
  7720. stats: session.peerconnection.stats,
  7721. url: window.location.href
  7722. };
  7723. }
  7724. });
  7725. return data;
  7726. }
  7727. });
  7728. };
  7729. },{"../../service/xmpp/XMPPEvents":75,"../RTC/RTCBrowserType":13,"./JingleSessionPC":20}],29:[function(require,module,exports){
  7730. /* global Strophe */
  7731. module.exports = function () {
  7732. Strophe.addConnectionPlugin('logger', {
  7733. // logs raw stanzas and makes them available for download as JSON
  7734. connection: null,
  7735. log: [],
  7736. init: function (conn) {
  7737. this.connection = conn;
  7738. this.connection.rawInput = this.log_incoming.bind(this);
  7739. this.connection.rawOutput = this.log_outgoing.bind(this);
  7740. },
  7741. log_incoming: function (stanza) {
  7742. this.log.push([new Date().getTime(), 'incoming', stanza]);
  7743. },
  7744. log_outgoing: function (stanza) {
  7745. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  7746. }
  7747. });
  7748. };
  7749. },{}],30:[function(require,module,exports){
  7750. /* jshint -W117 */
  7751. module.exports = function() {
  7752. Strophe.addConnectionPlugin('rayo',
  7753. {
  7754. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  7755. connection: null,
  7756. init: function (conn) {
  7757. this.connection = conn;
  7758. if (this.connection.disco) {
  7759. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  7760. }
  7761. this.connection.addHandler(
  7762. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  7763. },
  7764. onRayo: function (iq) {
  7765. console.info("Rayo IQ", iq);
  7766. },
  7767. dial: function (to, from, roomName, roomPass) {
  7768. var self = this;
  7769. var req = $iq(
  7770. {
  7771. type: 'set',
  7772. to: this.connection.emuc.focusMucJid
  7773. }
  7774. );
  7775. req.c('dial',
  7776. {
  7777. xmlns: this.RAYO_XMLNS,
  7778. to: to,
  7779. from: from
  7780. });
  7781. req.c('header',
  7782. {
  7783. name: 'JvbRoomName',
  7784. value: roomName
  7785. }).up();
  7786. if (roomPass !== null && roomPass.length) {
  7787. req.c('header',
  7788. {
  7789. name: 'JvbRoomPassword',
  7790. value: roomPass
  7791. }).up();
  7792. }
  7793. this.connection.sendIQ(
  7794. req,
  7795. function (result) {
  7796. console.info('Dial result ', result);
  7797. var resource = $(result).find('ref').attr('uri');
  7798. this.call_resource = resource.substr('xmpp:'.length);
  7799. console.info(
  7800. "Received call resource: " + this.call_resource);
  7801. },
  7802. function (error) {
  7803. console.info('Dial error ', error);
  7804. }
  7805. );
  7806. },
  7807. hang_up: function () {
  7808. if (!this.call_resource) {
  7809. console.warn("No call in progress");
  7810. return;
  7811. }
  7812. var self = this;
  7813. var req = $iq(
  7814. {
  7815. type: 'set',
  7816. to: this.call_resource
  7817. }
  7818. );
  7819. req.c('hangup',
  7820. {
  7821. xmlns: this.RAYO_XMLNS
  7822. });
  7823. this.connection.sendIQ(
  7824. req,
  7825. function (result) {
  7826. console.info('Hangup result ', result);
  7827. self.call_resource = null;
  7828. },
  7829. function (error) {
  7830. console.info('Hangup error ', error);
  7831. self.call_resource = null;
  7832. }
  7833. );
  7834. }
  7835. }
  7836. );
  7837. };
  7838. },{}],31:[function(require,module,exports){
  7839. /**
  7840. * Strophe logger implementation. Logs from level WARN and above.
  7841. */
  7842. module.exports = function () {
  7843. Strophe.log = function (level, msg) {
  7844. switch (level) {
  7845. case Strophe.LogLevel.WARN:
  7846. console.warn("Strophe: " + msg);
  7847. break;
  7848. case Strophe.LogLevel.ERROR:
  7849. case Strophe.LogLevel.FATAL:
  7850. console.error("Strophe: " + msg);
  7851. break;
  7852. }
  7853. };
  7854. Strophe.getStatusString = function (status) {
  7855. switch (status) {
  7856. case Strophe.Status.ERROR:
  7857. return "ERROR";
  7858. case Strophe.Status.CONNECTING:
  7859. return "CONNECTING";
  7860. case Strophe.Status.CONNFAIL:
  7861. return "CONNFAIL";
  7862. case Strophe.Status.AUTHENTICATING:
  7863. return "AUTHENTICATING";
  7864. case Strophe.Status.AUTHFAIL:
  7865. return "AUTHFAIL";
  7866. case Strophe.Status.CONNECTED:
  7867. return "CONNECTED";
  7868. case Strophe.Status.DISCONNECTED:
  7869. return "DISCONNECTED";
  7870. case Strophe.Status.DISCONNECTING:
  7871. return "DISCONNECTING";
  7872. case Strophe.Status.ATTACHED:
  7873. return "ATTACHED";
  7874. default:
  7875. return "unknown";
  7876. }
  7877. };
  7878. };
  7879. },{}],32:[function(require,module,exports){
  7880. /* global $, APP, config, Strophe*/
  7881. var EventEmitter = require("events");
  7882. var Pako = require("pako");
  7883. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  7884. var RTCEvents = require("../../service/RTC/RTCEvents");
  7885. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7886. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  7887. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  7888. var RTC = require("../RTC/RTC");
  7889. var authenticatedUser = false;
  7890. function createConnection(bosh) {
  7891. bosh = bosh || '/http-bind';
  7892. return new Strophe.Connection(bosh);
  7893. };
  7894. //!!!!!!!!!! FIXME: ...
  7895. function initStrophePlugins(XMPP)
  7896. {
  7897. require("./strophe.emuc")(XMPP);
  7898. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  7899. // require("./strophe.moderate")(XMPP, eventEmitter);
  7900. require("./strophe.util")();
  7901. require("./strophe.rayo")();
  7902. require("./strophe.logger")();
  7903. }
  7904. //!!!!!!!!!! FIXME: ...
  7905. ///**
  7906. // * If given <tt>localStream</tt> is video one this method will advertise it's
  7907. // * video type in MUC presence.
  7908. // * @param localStream new or modified <tt>LocalStream</tt>.
  7909. // */
  7910. //function broadcastLocalVideoType(localStream) {
  7911. // if (localStream.videoType)
  7912. // XMPP.addToPresence('videoType', localStream.videoType);
  7913. //}
  7914. //
  7915. //function registerListeners() {
  7916. // RTC.addStreamListener(
  7917. // broadcastLocalVideoType,
  7918. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  7919. // );
  7920. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  7921. // XMPP.addToPresence("devices", devices);
  7922. // });
  7923. //}
  7924. function XMPP(options) {
  7925. this.eventEmitter = new EventEmitter();
  7926. this.connection = null;
  7927. this.disconnectInProgress = false;
  7928. this.forceMuted = false;
  7929. this.options = options;
  7930. initStrophePlugins(this);
  7931. // registerListeners();
  7932. this.connection = createConnection(options.bosh);
  7933. }
  7934. XMPP.prototype.getConnection = function(){ return connection; };
  7935. XMPP.prototype._connect = function (jid, password) {
  7936. var self = this;
  7937. // connection.connect() starts the connection process.
  7938. //
  7939. // As the connection process proceeds, the user supplied callback will
  7940. // be triggered multiple times with status updates. The callback should
  7941. // take two arguments - the status code and the error condition.
  7942. //
  7943. // The status code will be one of the values in the Strophe.Status
  7944. // constants. The error condition will be one of the conditions defined
  7945. // in RFC 3920 or the condition ‘strophe-parsererror’.
  7946. //
  7947. // The Parameters wait, hold and route are optional and only relevant
  7948. // for BOSH connections. Please see XEP 124 for a more detailed
  7949. // explanation of the optional parameters.
  7950. //
  7951. // Connection status constants for use by the connection handler
  7952. // callback.
  7953. //
  7954. // Status.ERROR - An error has occurred (websockets specific)
  7955. // Status.CONNECTING - The connection is currently being made
  7956. // Status.CONNFAIL - The connection attempt failed
  7957. // Status.AUTHENTICATING - The connection is authenticating
  7958. // Status.AUTHFAIL - The authentication attempt failed
  7959. // Status.CONNECTED - The connection has succeeded
  7960. // Status.DISCONNECTED - The connection has been terminated
  7961. // Status.DISCONNECTING - The connection is currently being terminated
  7962. // Status.ATTACHED - The connection has been attached
  7963. var anonymousConnectionFailed = false;
  7964. var connectionFailed = false;
  7965. var lastErrorMsg;
  7966. this.connection.connect(jid, password, function (status, msg) {
  7967. console.log('Strophe status changed to',
  7968. Strophe.getStatusString(status), msg);
  7969. if (status === Strophe.Status.CONNECTED) {
  7970. if (self.options.useStunTurn) {
  7971. self.connection.jingle.getStunAndTurnCredentials();
  7972. }
  7973. console.info("My Jabber ID: " + self.connection.jid);
  7974. if (password)
  7975. authenticatedUser = true;
  7976. if (self.connection && self.connection.connected &&
  7977. Strophe.getResourceFromJid(self.connection.jid)) {
  7978. // .connected is true while connecting?
  7979. // self.connection.send($pres());
  7980. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  7981. Strophe.getResourceFromJid(self.connection.jid));
  7982. }
  7983. } else if (status === Strophe.Status.CONNFAIL) {
  7984. if (msg === 'x-strophe-bad-non-anon-jid') {
  7985. anonymousConnectionFailed = true;
  7986. }
  7987. else
  7988. {
  7989. connectionFailed = true;
  7990. }
  7991. lastErrorMsg = msg;
  7992. } else if (status === Strophe.Status.DISCONNECTED) {
  7993. self.disconnectInProgress = false;
  7994. if (anonymousConnectionFailed) {
  7995. // prompt user for username and password
  7996. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  7997. JitsiConnectionErrors.PASSWORD_REQUIRED);
  7998. } else if(connectionFailed) {
  7999. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8000. JitsiConnectionErrors.OTHER_ERROR,
  8001. msg ? msg : lastErrorMsg);
  8002. } else {
  8003. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  8004. msg ? msg : lastErrorMsg);
  8005. }
  8006. } else if (status === Strophe.Status.AUTHFAIL) {
  8007. // wrong password or username, prompt user
  8008. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  8009. JitsiConnectionErrors.PASSWORD_REQUIRED);
  8010. }
  8011. });
  8012. }
  8013. XMPP.prototype.connect = function (jid, password) {
  8014. if(!jid) {
  8015. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  8016. // Force authenticated domain if room is appended with '?login=true'
  8017. if (this.options.hosts.anonymousdomain &&
  8018. window.location.search.indexOf("login=true") !== -1) {
  8019. configDomain = this.options.hosts.domain;
  8020. }
  8021. jid = configDomain || window.location.hostname;
  8022. }
  8023. return this._connect(jid, password);
  8024. };
  8025. XMPP.prototype.createRoom = function (roomName, options, useNicks, nick) {
  8026. var roomjid = roomName + '@' + this.options.hosts.muc;
  8027. if (useNicks) {
  8028. if (nick) {
  8029. roomjid += '/' + nick;
  8030. } else {
  8031. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  8032. }
  8033. } else {
  8034. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  8035. if(!authenticatedUser)
  8036. tmpJid = tmpJid.substr(0, 8);
  8037. roomjid += '/' + tmpJid;
  8038. }
  8039. return this.connection.emuc.createRoom(roomjid, null, options);
  8040. }
  8041. XMPP.prototype.addListener = function(type, listener) {
  8042. this.eventEmitter.on(type, listener);
  8043. };
  8044. XMPP.prototype.removeListener = function (type, listener) {
  8045. this.eventEmitter.removeListener(type, listener);
  8046. };
  8047. //FIXME: this should work with the room
  8048. XMPP.prototype.leaveRoom = function (jid) {
  8049. var handler = this.connection.jingle.jid2session[jid];
  8050. if (handler && handler.peerconnection) {
  8051. // FIXME: probably removing streams is not required and close() should
  8052. // be enough
  8053. if (RTC.localAudio) {
  8054. handler.peerconnection.removeStream(
  8055. RTC.localAudio.getOriginalStream(), true);
  8056. }
  8057. if (RTC.localVideo) {
  8058. handler.peerconnection.removeStream(
  8059. RTC.localVideo.getOriginalStream(), true);
  8060. }
  8061. handler.peerconnection.close();
  8062. }
  8063. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  8064. this.connection.emuc.doLeave(jid);
  8065. };
  8066. /**
  8067. * Sends 'data' as a log message to the focus. Returns true iff a message
  8068. * was sent.
  8069. * @param data
  8070. * @returns {boolean} true iff a message was sent.
  8071. */
  8072. XMPP.prototype.sendLogs = function (data) {
  8073. if(!this.connection.emuc.focusMucJid)
  8074. return false;
  8075. var deflate = true;
  8076. var content = JSON.stringify(data);
  8077. if (deflate) {
  8078. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  8079. }
  8080. content = Base64.encode(content);
  8081. // XEP-0337-ish
  8082. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  8083. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  8084. id: 'PeerConnectionStats'});
  8085. message.c('message').t(content).up();
  8086. if (deflate) {
  8087. message.c('tag', {name: "deflated", value: "true"}).up();
  8088. }
  8089. message.up();
  8090. this.connection.send(message);
  8091. return true;
  8092. };
  8093. // Gets the logs from strophe.jingle.
  8094. XMPP.prototype.getJingleLog = function () {
  8095. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  8096. };
  8097. // Gets the logs from strophe.
  8098. XMPP.prototype.getXmppLog = function () {
  8099. return this.connection.logger ? this.connection.logger.log : null;
  8100. };
  8101. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  8102. this.connection.rayo.dial(to, from, roomName,roomPass);
  8103. };
  8104. XMPP.prototype.setMute = function (jid, mute) {
  8105. this.connection.moderate.setMute(jid, mute);
  8106. };
  8107. XMPP.prototype.eject = function (jid) {
  8108. this.connection.moderate.eject(jid);
  8109. };
  8110. XMPP.prototype.getJidFromSSRC = function (ssrc) {
  8111. if (!this.isConferenceInProgress())
  8112. return null;
  8113. return this.connection.jingle.activecall.getSsrcOwner(ssrc);
  8114. };
  8115. XMPP.prototype.getSessions = function () {
  8116. return this.connection.jingle.sessions;
  8117. };
  8118. XMPP.prototype.disconnect = function () {
  8119. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  8120. {
  8121. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  8122. return;
  8123. }
  8124. this.disconnectInProgress = true;
  8125. this.connection.disconnect();
  8126. };
  8127. module.exports = XMPP;
  8128. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":70,"../../service/RTC/StreamEventTypes":72,"../../service/xmpp/XMPPEvents":75,"../RTC/RTC":12,"./strophe.emuc":27,"./strophe.jingle":28,"./strophe.logger":29,"./strophe.rayo":30,"./strophe.util":31,"events":76,"pako":35}],33:[function(require,module,exports){
  8129. (function (process){
  8130. /*!
  8131. * async
  8132. * https://github.com/caolan/async
  8133. *
  8134. * Copyright 2010-2014 Caolan McMahon
  8135. * Released under the MIT license
  8136. */
  8137. /*jshint onevar: false, indent:4 */
  8138. /*global setImmediate: false, setTimeout: false, console: false */
  8139. (function () {
  8140. var async = {};
  8141. // global on the server, window in the browser
  8142. var root, previous_async;
  8143. root = this;
  8144. if (root != null) {
  8145. previous_async = root.async;
  8146. }
  8147. async.noConflict = function () {
  8148. root.async = previous_async;
  8149. return async;
  8150. };
  8151. function only_once(fn) {
  8152. var called = false;
  8153. return function() {
  8154. if (called) throw new Error("Callback was already called.");
  8155. called = true;
  8156. fn.apply(root, arguments);
  8157. }
  8158. }
  8159. //// cross-browser compatiblity functions ////
  8160. var _toString = Object.prototype.toString;
  8161. var _isArray = Array.isArray || function (obj) {
  8162. return _toString.call(obj) === '[object Array]';
  8163. };
  8164. var _each = function (arr, iterator) {
  8165. if (arr.forEach) {
  8166. return arr.forEach(iterator);
  8167. }
  8168. for (var i = 0; i < arr.length; i += 1) {
  8169. iterator(arr[i], i, arr);
  8170. }
  8171. };
  8172. var _map = function (arr, iterator) {
  8173. if (arr.map) {
  8174. return arr.map(iterator);
  8175. }
  8176. var results = [];
  8177. _each(arr, function (x, i, a) {
  8178. results.push(iterator(x, i, a));
  8179. });
  8180. return results;
  8181. };
  8182. var _reduce = function (arr, iterator, memo) {
  8183. if (arr.reduce) {
  8184. return arr.reduce(iterator, memo);
  8185. }
  8186. _each(arr, function (x, i, a) {
  8187. memo = iterator(memo, x, i, a);
  8188. });
  8189. return memo;
  8190. };
  8191. var _keys = function (obj) {
  8192. if (Object.keys) {
  8193. return Object.keys(obj);
  8194. }
  8195. var keys = [];
  8196. for (var k in obj) {
  8197. if (obj.hasOwnProperty(k)) {
  8198. keys.push(k);
  8199. }
  8200. }
  8201. return keys;
  8202. };
  8203. //// exported async module functions ////
  8204. //// nextTick implementation with browser-compatible fallback ////
  8205. if (typeof process === 'undefined' || !(process.nextTick)) {
  8206. if (typeof setImmediate === 'function') {
  8207. async.nextTick = function (fn) {
  8208. // not a direct alias for IE10 compatibility
  8209. setImmediate(fn);
  8210. };
  8211. async.setImmediate = async.nextTick;
  8212. }
  8213. else {
  8214. async.nextTick = function (fn) {
  8215. setTimeout(fn, 0);
  8216. };
  8217. async.setImmediate = async.nextTick;
  8218. }
  8219. }
  8220. else {
  8221. async.nextTick = process.nextTick;
  8222. if (typeof setImmediate !== 'undefined') {
  8223. async.setImmediate = function (fn) {
  8224. // not a direct alias for IE10 compatibility
  8225. setImmediate(fn);
  8226. };
  8227. }
  8228. else {
  8229. async.setImmediate = async.nextTick;
  8230. }
  8231. }
  8232. async.each = function (arr, iterator, callback) {
  8233. callback = callback || function () {};
  8234. if (!arr.length) {
  8235. return callback();
  8236. }
  8237. var completed = 0;
  8238. _each(arr, function (x) {
  8239. iterator(x, only_once(done) );
  8240. });
  8241. function done(err) {
  8242. if (err) {
  8243. callback(err);
  8244. callback = function () {};
  8245. }
  8246. else {
  8247. completed += 1;
  8248. if (completed >= arr.length) {
  8249. callback();
  8250. }
  8251. }
  8252. }
  8253. };
  8254. async.forEach = async.each;
  8255. async.eachSeries = function (arr, iterator, callback) {
  8256. callback = callback || function () {};
  8257. if (!arr.length) {
  8258. return callback();
  8259. }
  8260. var completed = 0;
  8261. var iterate = function () {
  8262. iterator(arr[completed], function (err) {
  8263. if (err) {
  8264. callback(err);
  8265. callback = function () {};
  8266. }
  8267. else {
  8268. completed += 1;
  8269. if (completed >= arr.length) {
  8270. callback();
  8271. }
  8272. else {
  8273. iterate();
  8274. }
  8275. }
  8276. });
  8277. };
  8278. iterate();
  8279. };
  8280. async.forEachSeries = async.eachSeries;
  8281. async.eachLimit = function (arr, limit, iterator, callback) {
  8282. var fn = _eachLimit(limit);
  8283. fn.apply(null, [arr, iterator, callback]);
  8284. };
  8285. async.forEachLimit = async.eachLimit;
  8286. var _eachLimit = function (limit) {
  8287. return function (arr, iterator, callback) {
  8288. callback = callback || function () {};
  8289. if (!arr.length || limit <= 0) {
  8290. return callback();
  8291. }
  8292. var completed = 0;
  8293. var started = 0;
  8294. var running = 0;
  8295. (function replenish () {
  8296. if (completed >= arr.length) {
  8297. return callback();
  8298. }
  8299. while (running < limit && started < arr.length) {
  8300. started += 1;
  8301. running += 1;
  8302. iterator(arr[started - 1], function (err) {
  8303. if (err) {
  8304. callback(err);
  8305. callback = function () {};
  8306. }
  8307. else {
  8308. completed += 1;
  8309. running -= 1;
  8310. if (completed >= arr.length) {
  8311. callback();
  8312. }
  8313. else {
  8314. replenish();
  8315. }
  8316. }
  8317. });
  8318. }
  8319. })();
  8320. };
  8321. };
  8322. var doParallel = function (fn) {
  8323. return function () {
  8324. var args = Array.prototype.slice.call(arguments);
  8325. return fn.apply(null, [async.each].concat(args));
  8326. };
  8327. };
  8328. var doParallelLimit = function(limit, fn) {
  8329. return function () {
  8330. var args = Array.prototype.slice.call(arguments);
  8331. return fn.apply(null, [_eachLimit(limit)].concat(args));
  8332. };
  8333. };
  8334. var doSeries = function (fn) {
  8335. return function () {
  8336. var args = Array.prototype.slice.call(arguments);
  8337. return fn.apply(null, [async.eachSeries].concat(args));
  8338. };
  8339. };
  8340. var _asyncMap = function (eachfn, arr, iterator, callback) {
  8341. arr = _map(arr, function (x, i) {
  8342. return {index: i, value: x};
  8343. });
  8344. if (!callback) {
  8345. eachfn(arr, function (x, callback) {
  8346. iterator(x.value, function (err) {
  8347. callback(err);
  8348. });
  8349. });
  8350. } else {
  8351. var results = [];
  8352. eachfn(arr, function (x, callback) {
  8353. iterator(x.value, function (err, v) {
  8354. results[x.index] = v;
  8355. callback(err);
  8356. });
  8357. }, function (err) {
  8358. callback(err, results);
  8359. });
  8360. }
  8361. };
  8362. async.map = doParallel(_asyncMap);
  8363. async.mapSeries = doSeries(_asyncMap);
  8364. async.mapLimit = function (arr, limit, iterator, callback) {
  8365. return _mapLimit(limit)(arr, iterator, callback);
  8366. };
  8367. var _mapLimit = function(limit) {
  8368. return doParallelLimit(limit, _asyncMap);
  8369. };
  8370. // reduce only has a series version, as doing reduce in parallel won't
  8371. // work in many situations.
  8372. async.reduce = function (arr, memo, iterator, callback) {
  8373. async.eachSeries(arr, function (x, callback) {
  8374. iterator(memo, x, function (err, v) {
  8375. memo = v;
  8376. callback(err);
  8377. });
  8378. }, function (err) {
  8379. callback(err, memo);
  8380. });
  8381. };
  8382. // inject alias
  8383. async.inject = async.reduce;
  8384. // foldl alias
  8385. async.foldl = async.reduce;
  8386. async.reduceRight = function (arr, memo, iterator, callback) {
  8387. var reversed = _map(arr, function (x) {
  8388. return x;
  8389. }).reverse();
  8390. async.reduce(reversed, memo, iterator, callback);
  8391. };
  8392. // foldr alias
  8393. async.foldr = async.reduceRight;
  8394. var _filter = function (eachfn, arr, iterator, callback) {
  8395. var results = [];
  8396. arr = _map(arr, function (x, i) {
  8397. return {index: i, value: x};
  8398. });
  8399. eachfn(arr, function (x, callback) {
  8400. iterator(x.value, function (v) {
  8401. if (v) {
  8402. results.push(x);
  8403. }
  8404. callback();
  8405. });
  8406. }, function (err) {
  8407. callback(_map(results.sort(function (a, b) {
  8408. return a.index - b.index;
  8409. }), function (x) {
  8410. return x.value;
  8411. }));
  8412. });
  8413. };
  8414. async.filter = doParallel(_filter);
  8415. async.filterSeries = doSeries(_filter);
  8416. // select alias
  8417. async.select = async.filter;
  8418. async.selectSeries = async.filterSeries;
  8419. var _reject = function (eachfn, arr, iterator, callback) {
  8420. var results = [];
  8421. arr = _map(arr, function (x, i) {
  8422. return {index: i, value: x};
  8423. });
  8424. eachfn(arr, function (x, callback) {
  8425. iterator(x.value, function (v) {
  8426. if (!v) {
  8427. results.push(x);
  8428. }
  8429. callback();
  8430. });
  8431. }, function (err) {
  8432. callback(_map(results.sort(function (a, b) {
  8433. return a.index - b.index;
  8434. }), function (x) {
  8435. return x.value;
  8436. }));
  8437. });
  8438. };
  8439. async.reject = doParallel(_reject);
  8440. async.rejectSeries = doSeries(_reject);
  8441. var _detect = function (eachfn, arr, iterator, main_callback) {
  8442. eachfn(arr, function (x, callback) {
  8443. iterator(x, function (result) {
  8444. if (result) {
  8445. main_callback(x);
  8446. main_callback = function () {};
  8447. }
  8448. else {
  8449. callback();
  8450. }
  8451. });
  8452. }, function (err) {
  8453. main_callback();
  8454. });
  8455. };
  8456. async.detect = doParallel(_detect);
  8457. async.detectSeries = doSeries(_detect);
  8458. async.some = function (arr, iterator, main_callback) {
  8459. async.each(arr, function (x, callback) {
  8460. iterator(x, function (v) {
  8461. if (v) {
  8462. main_callback(true);
  8463. main_callback = function () {};
  8464. }
  8465. callback();
  8466. });
  8467. }, function (err) {
  8468. main_callback(false);
  8469. });
  8470. };
  8471. // any alias
  8472. async.any = async.some;
  8473. async.every = function (arr, iterator, main_callback) {
  8474. async.each(arr, function (x, callback) {
  8475. iterator(x, function (v) {
  8476. if (!v) {
  8477. main_callback(false);
  8478. main_callback = function () {};
  8479. }
  8480. callback();
  8481. });
  8482. }, function (err) {
  8483. main_callback(true);
  8484. });
  8485. };
  8486. // all alias
  8487. async.all = async.every;
  8488. async.sortBy = function (arr, iterator, callback) {
  8489. async.map(arr, function (x, callback) {
  8490. iterator(x, function (err, criteria) {
  8491. if (err) {
  8492. callback(err);
  8493. }
  8494. else {
  8495. callback(null, {value: x, criteria: criteria});
  8496. }
  8497. });
  8498. }, function (err, results) {
  8499. if (err) {
  8500. return callback(err);
  8501. }
  8502. else {
  8503. var fn = function (left, right) {
  8504. var a = left.criteria, b = right.criteria;
  8505. return a < b ? -1 : a > b ? 1 : 0;
  8506. };
  8507. callback(null, _map(results.sort(fn), function (x) {
  8508. return x.value;
  8509. }));
  8510. }
  8511. });
  8512. };
  8513. async.auto = function (tasks, callback) {
  8514. callback = callback || function () {};
  8515. var keys = _keys(tasks);
  8516. var remainingTasks = keys.length
  8517. if (!remainingTasks) {
  8518. return callback();
  8519. }
  8520. var results = {};
  8521. var listeners = [];
  8522. var addListener = function (fn) {
  8523. listeners.unshift(fn);
  8524. };
  8525. var removeListener = function (fn) {
  8526. for (var i = 0; i < listeners.length; i += 1) {
  8527. if (listeners[i] === fn) {
  8528. listeners.splice(i, 1);
  8529. return;
  8530. }
  8531. }
  8532. };
  8533. var taskComplete = function () {
  8534. remainingTasks--
  8535. _each(listeners.slice(0), function (fn) {
  8536. fn();
  8537. });
  8538. };
  8539. addListener(function () {
  8540. if (!remainingTasks) {
  8541. var theCallback = callback;
  8542. // prevent final callback from calling itself if it errors
  8543. callback = function () {};
  8544. theCallback(null, results);
  8545. }
  8546. });
  8547. _each(keys, function (k) {
  8548. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  8549. var taskCallback = function (err) {
  8550. var args = Array.prototype.slice.call(arguments, 1);
  8551. if (args.length <= 1) {
  8552. args = args[0];
  8553. }
  8554. if (err) {
  8555. var safeResults = {};
  8556. _each(_keys(results), function(rkey) {
  8557. safeResults[rkey] = results[rkey];
  8558. });
  8559. safeResults[k] = args;
  8560. callback(err, safeResults);
  8561. // stop subsequent errors hitting callback multiple times
  8562. callback = function () {};
  8563. }
  8564. else {
  8565. results[k] = args;
  8566. async.setImmediate(taskComplete);
  8567. }
  8568. };
  8569. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  8570. var ready = function () {
  8571. return _reduce(requires, function (a, x) {
  8572. return (a && results.hasOwnProperty(x));
  8573. }, true) && !results.hasOwnProperty(k);
  8574. };
  8575. if (ready()) {
  8576. task[task.length - 1](taskCallback, results);
  8577. }
  8578. else {
  8579. var listener = function () {
  8580. if (ready()) {
  8581. removeListener(listener);
  8582. task[task.length - 1](taskCallback, results);
  8583. }
  8584. };
  8585. addListener(listener);
  8586. }
  8587. });
  8588. };
  8589. async.retry = function(times, task, callback) {
  8590. var DEFAULT_TIMES = 5;
  8591. var attempts = [];
  8592. // Use defaults if times not passed
  8593. if (typeof times === 'function') {
  8594. callback = task;
  8595. task = times;
  8596. times = DEFAULT_TIMES;
  8597. }
  8598. // Make sure times is a number
  8599. times = parseInt(times, 10) || DEFAULT_TIMES;
  8600. var wrappedTask = function(wrappedCallback, wrappedResults) {
  8601. var retryAttempt = function(task, finalAttempt) {
  8602. return function(seriesCallback) {
  8603. task(function(err, result){
  8604. seriesCallback(!err || finalAttempt, {err: err, result: result});
  8605. }, wrappedResults);
  8606. };
  8607. };
  8608. while (times) {
  8609. attempts.push(retryAttempt(task, !(times-=1)));
  8610. }
  8611. async.series(attempts, function(done, data){
  8612. data = data[data.length - 1];
  8613. (wrappedCallback || callback)(data.err, data.result);
  8614. });
  8615. }
  8616. // If a callback is passed, run this as a controll flow
  8617. return callback ? wrappedTask() : wrappedTask
  8618. };
  8619. async.waterfall = function (tasks, callback) {
  8620. callback = callback || function () {};
  8621. if (!_isArray(tasks)) {
  8622. var err = new Error('First argument to waterfall must be an array of functions');
  8623. return callback(err);
  8624. }
  8625. if (!tasks.length) {
  8626. return callback();
  8627. }
  8628. var wrapIterator = function (iterator) {
  8629. return function (err) {
  8630. if (err) {
  8631. callback.apply(null, arguments);
  8632. callback = function () {};
  8633. }
  8634. else {
  8635. var args = Array.prototype.slice.call(arguments, 1);
  8636. var next = iterator.next();
  8637. if (next) {
  8638. args.push(wrapIterator(next));
  8639. }
  8640. else {
  8641. args.push(callback);
  8642. }
  8643. async.setImmediate(function () {
  8644. iterator.apply(null, args);
  8645. });
  8646. }
  8647. };
  8648. };
  8649. wrapIterator(async.iterator(tasks))();
  8650. };
  8651. var _parallel = function(eachfn, tasks, callback) {
  8652. callback = callback || function () {};
  8653. if (_isArray(tasks)) {
  8654. eachfn.map(tasks, function (fn, callback) {
  8655. if (fn) {
  8656. fn(function (err) {
  8657. var args = Array.prototype.slice.call(arguments, 1);
  8658. if (args.length <= 1) {
  8659. args = args[0];
  8660. }
  8661. callback.call(null, err, args);
  8662. });
  8663. }
  8664. }, callback);
  8665. }
  8666. else {
  8667. var results = {};
  8668. eachfn.each(_keys(tasks), function (k, callback) {
  8669. tasks[k](function (err) {
  8670. var args = Array.prototype.slice.call(arguments, 1);
  8671. if (args.length <= 1) {
  8672. args = args[0];
  8673. }
  8674. results[k] = args;
  8675. callback(err);
  8676. });
  8677. }, function (err) {
  8678. callback(err, results);
  8679. });
  8680. }
  8681. };
  8682. async.parallel = function (tasks, callback) {
  8683. _parallel({ map: async.map, each: async.each }, tasks, callback);
  8684. };
  8685. async.parallelLimit = function(tasks, limit, callback) {
  8686. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  8687. };
  8688. async.series = function (tasks, callback) {
  8689. callback = callback || function () {};
  8690. if (_isArray(tasks)) {
  8691. async.mapSeries(tasks, function (fn, callback) {
  8692. if (fn) {
  8693. fn(function (err) {
  8694. var args = Array.prototype.slice.call(arguments, 1);
  8695. if (args.length <= 1) {
  8696. args = args[0];
  8697. }
  8698. callback.call(null, err, args);
  8699. });
  8700. }
  8701. }, callback);
  8702. }
  8703. else {
  8704. var results = {};
  8705. async.eachSeries(_keys(tasks), function (k, callback) {
  8706. tasks[k](function (err) {
  8707. var args = Array.prototype.slice.call(arguments, 1);
  8708. if (args.length <= 1) {
  8709. args = args[0];
  8710. }
  8711. results[k] = args;
  8712. callback(err);
  8713. });
  8714. }, function (err) {
  8715. callback(err, results);
  8716. });
  8717. }
  8718. };
  8719. async.iterator = function (tasks) {
  8720. var makeCallback = function (index) {
  8721. var fn = function () {
  8722. if (tasks.length) {
  8723. tasks[index].apply(null, arguments);
  8724. }
  8725. return fn.next();
  8726. };
  8727. fn.next = function () {
  8728. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  8729. };
  8730. return fn;
  8731. };
  8732. return makeCallback(0);
  8733. };
  8734. async.apply = function (fn) {
  8735. var args = Array.prototype.slice.call(arguments, 1);
  8736. return function () {
  8737. return fn.apply(
  8738. null, args.concat(Array.prototype.slice.call(arguments))
  8739. );
  8740. };
  8741. };
  8742. var _concat = function (eachfn, arr, fn, callback) {
  8743. var r = [];
  8744. eachfn(arr, function (x, cb) {
  8745. fn(x, function (err, y) {
  8746. r = r.concat(y || []);
  8747. cb(err);
  8748. });
  8749. }, function (err) {
  8750. callback(err, r);
  8751. });
  8752. };
  8753. async.concat = doParallel(_concat);
  8754. async.concatSeries = doSeries(_concat);
  8755. async.whilst = function (test, iterator, callback) {
  8756. if (test()) {
  8757. iterator(function (err) {
  8758. if (err) {
  8759. return callback(err);
  8760. }
  8761. async.whilst(test, iterator, callback);
  8762. });
  8763. }
  8764. else {
  8765. callback();
  8766. }
  8767. };
  8768. async.doWhilst = function (iterator, test, callback) {
  8769. iterator(function (err) {
  8770. if (err) {
  8771. return callback(err);
  8772. }
  8773. var args = Array.prototype.slice.call(arguments, 1);
  8774. if (test.apply(null, args)) {
  8775. async.doWhilst(iterator, test, callback);
  8776. }
  8777. else {
  8778. callback();
  8779. }
  8780. });
  8781. };
  8782. async.until = function (test, iterator, callback) {
  8783. if (!test()) {
  8784. iterator(function (err) {
  8785. if (err) {
  8786. return callback(err);
  8787. }
  8788. async.until(test, iterator, callback);
  8789. });
  8790. }
  8791. else {
  8792. callback();
  8793. }
  8794. };
  8795. async.doUntil = function (iterator, test, callback) {
  8796. iterator(function (err) {
  8797. if (err) {
  8798. return callback(err);
  8799. }
  8800. var args = Array.prototype.slice.call(arguments, 1);
  8801. if (!test.apply(null, args)) {
  8802. async.doUntil(iterator, test, callback);
  8803. }
  8804. else {
  8805. callback();
  8806. }
  8807. });
  8808. };
  8809. async.queue = function (worker, concurrency) {
  8810. if (concurrency === undefined) {
  8811. concurrency = 1;
  8812. }
  8813. function _insert(q, data, pos, callback) {
  8814. if (!q.started){
  8815. q.started = true;
  8816. }
  8817. if (!_isArray(data)) {
  8818. data = [data];
  8819. }
  8820. if(data.length == 0) {
  8821. // call drain immediately if there are no tasks
  8822. return async.setImmediate(function() {
  8823. if (q.drain) {
  8824. q.drain();
  8825. }
  8826. });
  8827. }
  8828. _each(data, function(task) {
  8829. var item = {
  8830. data: task,
  8831. callback: typeof callback === 'function' ? callback : null
  8832. };
  8833. if (pos) {
  8834. q.tasks.unshift(item);
  8835. } else {
  8836. q.tasks.push(item);
  8837. }
  8838. if (q.saturated && q.tasks.length === q.concurrency) {
  8839. q.saturated();
  8840. }
  8841. async.setImmediate(q.process);
  8842. });
  8843. }
  8844. var workers = 0;
  8845. var q = {
  8846. tasks: [],
  8847. concurrency: concurrency,
  8848. saturated: null,
  8849. empty: null,
  8850. drain: null,
  8851. started: false,
  8852. paused: false,
  8853. push: function (data, callback) {
  8854. _insert(q, data, false, callback);
  8855. },
  8856. kill: function () {
  8857. q.drain = null;
  8858. q.tasks = [];
  8859. },
  8860. unshift: function (data, callback) {
  8861. _insert(q, data, true, callback);
  8862. },
  8863. process: function () {
  8864. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  8865. var task = q.tasks.shift();
  8866. if (q.empty && q.tasks.length === 0) {
  8867. q.empty();
  8868. }
  8869. workers += 1;
  8870. var next = function () {
  8871. workers -= 1;
  8872. if (task.callback) {
  8873. task.callback.apply(task, arguments);
  8874. }
  8875. if (q.drain && q.tasks.length + workers === 0) {
  8876. q.drain();
  8877. }
  8878. q.process();
  8879. };
  8880. var cb = only_once(next);
  8881. worker(task.data, cb);
  8882. }
  8883. },
  8884. length: function () {
  8885. return q.tasks.length;
  8886. },
  8887. running: function () {
  8888. return workers;
  8889. },
  8890. idle: function() {
  8891. return q.tasks.length + workers === 0;
  8892. },
  8893. pause: function () {
  8894. if (q.paused === true) { return; }
  8895. q.paused = true;
  8896. q.process();
  8897. },
  8898. resume: function () {
  8899. if (q.paused === false) { return; }
  8900. q.paused = false;
  8901. q.process();
  8902. }
  8903. };
  8904. return q;
  8905. };
  8906. async.priorityQueue = function (worker, concurrency) {
  8907. function _compareTasks(a, b){
  8908. return a.priority - b.priority;
  8909. };
  8910. function _binarySearch(sequence, item, compare) {
  8911. var beg = -1,
  8912. end = sequence.length - 1;
  8913. while (beg < end) {
  8914. var mid = beg + ((end - beg + 1) >>> 1);
  8915. if (compare(item, sequence[mid]) >= 0) {
  8916. beg = mid;
  8917. } else {
  8918. end = mid - 1;
  8919. }
  8920. }
  8921. return beg;
  8922. }
  8923. function _insert(q, data, priority, callback) {
  8924. if (!q.started){
  8925. q.started = true;
  8926. }
  8927. if (!_isArray(data)) {
  8928. data = [data];
  8929. }
  8930. if(data.length == 0) {
  8931. // call drain immediately if there are no tasks
  8932. return async.setImmediate(function() {
  8933. if (q.drain) {
  8934. q.drain();
  8935. }
  8936. });
  8937. }
  8938. _each(data, function(task) {
  8939. var item = {
  8940. data: task,
  8941. priority: priority,
  8942. callback: typeof callback === 'function' ? callback : null
  8943. };
  8944. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  8945. if (q.saturated && q.tasks.length === q.concurrency) {
  8946. q.saturated();
  8947. }
  8948. async.setImmediate(q.process);
  8949. });
  8950. }
  8951. // Start with a normal queue
  8952. var q = async.queue(worker, concurrency);
  8953. // Override push to accept second parameter representing priority
  8954. q.push = function (data, priority, callback) {
  8955. _insert(q, data, priority, callback);
  8956. };
  8957. // Remove unshift function
  8958. delete q.unshift;
  8959. return q;
  8960. };
  8961. async.cargo = function (worker, payload) {
  8962. var working = false,
  8963. tasks = [];
  8964. var cargo = {
  8965. tasks: tasks,
  8966. payload: payload,
  8967. saturated: null,
  8968. empty: null,
  8969. drain: null,
  8970. drained: true,
  8971. push: function (data, callback) {
  8972. if (!_isArray(data)) {
  8973. data = [data];
  8974. }
  8975. _each(data, function(task) {
  8976. tasks.push({
  8977. data: task,
  8978. callback: typeof callback === 'function' ? callback : null
  8979. });
  8980. cargo.drained = false;
  8981. if (cargo.saturated && tasks.length === payload) {
  8982. cargo.saturated();
  8983. }
  8984. });
  8985. async.setImmediate(cargo.process);
  8986. },
  8987. process: function process() {
  8988. if (working) return;
  8989. if (tasks.length === 0) {
  8990. if(cargo.drain && !cargo.drained) cargo.drain();
  8991. cargo.drained = true;
  8992. return;
  8993. }
  8994. var ts = typeof payload === 'number'
  8995. ? tasks.splice(0, payload)
  8996. : tasks.splice(0, tasks.length);
  8997. var ds = _map(ts, function (task) {
  8998. return task.data;
  8999. });
  9000. if(cargo.empty) cargo.empty();
  9001. working = true;
  9002. worker(ds, function () {
  9003. working = false;
  9004. var args = arguments;
  9005. _each(ts, function (data) {
  9006. if (data.callback) {
  9007. data.callback.apply(null, args);
  9008. }
  9009. });
  9010. process();
  9011. });
  9012. },
  9013. length: function () {
  9014. return tasks.length;
  9015. },
  9016. running: function () {
  9017. return working;
  9018. }
  9019. };
  9020. return cargo;
  9021. };
  9022. var _console_fn = function (name) {
  9023. return function (fn) {
  9024. var args = Array.prototype.slice.call(arguments, 1);
  9025. fn.apply(null, args.concat([function (err) {
  9026. var args = Array.prototype.slice.call(arguments, 1);
  9027. if (typeof console !== 'undefined') {
  9028. if (err) {
  9029. if (console.error) {
  9030. console.error(err);
  9031. }
  9032. }
  9033. else if (console[name]) {
  9034. _each(args, function (x) {
  9035. console[name](x);
  9036. });
  9037. }
  9038. }
  9039. }]));
  9040. };
  9041. };
  9042. async.log = _console_fn('log');
  9043. async.dir = _console_fn('dir');
  9044. /*async.info = _console_fn('info');
  9045. async.warn = _console_fn('warn');
  9046. async.error = _console_fn('error');*/
  9047. async.memoize = function (fn, hasher) {
  9048. var memo = {};
  9049. var queues = {};
  9050. hasher = hasher || function (x) {
  9051. return x;
  9052. };
  9053. var memoized = function () {
  9054. var args = Array.prototype.slice.call(arguments);
  9055. var callback = args.pop();
  9056. var key = hasher.apply(null, args);
  9057. if (key in memo) {
  9058. async.nextTick(function () {
  9059. callback.apply(null, memo[key]);
  9060. });
  9061. }
  9062. else if (key in queues) {
  9063. queues[key].push(callback);
  9064. }
  9065. else {
  9066. queues[key] = [callback];
  9067. fn.apply(null, args.concat([function () {
  9068. memo[key] = arguments;
  9069. var q = queues[key];
  9070. delete queues[key];
  9071. for (var i = 0, l = q.length; i < l; i++) {
  9072. q[i].apply(null, arguments);
  9073. }
  9074. }]));
  9075. }
  9076. };
  9077. memoized.memo = memo;
  9078. memoized.unmemoized = fn;
  9079. return memoized;
  9080. };
  9081. async.unmemoize = function (fn) {
  9082. return function () {
  9083. return (fn.unmemoized || fn).apply(null, arguments);
  9084. };
  9085. };
  9086. async.times = function (count, iterator, callback) {
  9087. var counter = [];
  9088. for (var i = 0; i < count; i++) {
  9089. counter.push(i);
  9090. }
  9091. return async.map(counter, iterator, callback);
  9092. };
  9093. async.timesSeries = function (count, iterator, callback) {
  9094. var counter = [];
  9095. for (var i = 0; i < count; i++) {
  9096. counter.push(i);
  9097. }
  9098. return async.mapSeries(counter, iterator, callback);
  9099. };
  9100. async.seq = function (/* functions... */) {
  9101. var fns = arguments;
  9102. return function () {
  9103. var that = this;
  9104. var args = Array.prototype.slice.call(arguments);
  9105. var callback = args.pop();
  9106. async.reduce(fns, args, function (newargs, fn, cb) {
  9107. fn.apply(that, newargs.concat([function () {
  9108. var err = arguments[0];
  9109. var nextargs = Array.prototype.slice.call(arguments, 1);
  9110. cb(err, nextargs);
  9111. }]))
  9112. },
  9113. function (err, results) {
  9114. callback.apply(that, [err].concat(results));
  9115. });
  9116. };
  9117. };
  9118. async.compose = function (/* functions... */) {
  9119. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  9120. };
  9121. var _applyEach = function (eachfn, fns /*args...*/) {
  9122. var go = function () {
  9123. var that = this;
  9124. var args = Array.prototype.slice.call(arguments);
  9125. var callback = args.pop();
  9126. return eachfn(fns, function (fn, cb) {
  9127. fn.apply(that, args.concat([cb]));
  9128. },
  9129. callback);
  9130. };
  9131. if (arguments.length > 2) {
  9132. var args = Array.prototype.slice.call(arguments, 2);
  9133. return go.apply(this, args);
  9134. }
  9135. else {
  9136. return go;
  9137. }
  9138. };
  9139. async.applyEach = doParallel(_applyEach);
  9140. async.applyEachSeries = doSeries(_applyEach);
  9141. async.forever = function (fn, callback) {
  9142. function next(err) {
  9143. if (err) {
  9144. if (callback) {
  9145. return callback(err);
  9146. }
  9147. throw err;
  9148. }
  9149. fn(next);
  9150. }
  9151. next();
  9152. };
  9153. // Node.js
  9154. if (typeof module !== 'undefined' && module.exports) {
  9155. module.exports = async;
  9156. }
  9157. // AMD / RequireJS
  9158. else if (typeof define !== 'undefined' && define.amd) {
  9159. define([], function () {
  9160. return async;
  9161. });
  9162. }
  9163. // included directly via <script> tag
  9164. else {
  9165. root.async = async;
  9166. }
  9167. }());
  9168. }).call(this,require('_process'))
  9169. },{"_process":77}],34:[function(require,module,exports){
  9170. (function (process,global){
  9171. /*!
  9172. * @overview es6-promise - a tiny implementation of Promises/A+.
  9173. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  9174. * @license Licensed under MIT license
  9175. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  9176. * @version 3.0.2
  9177. */
  9178. (function() {
  9179. "use strict";
  9180. function lib$es6$promise$utils$$objectOrFunction(x) {
  9181. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  9182. }
  9183. function lib$es6$promise$utils$$isFunction(x) {
  9184. return typeof x === 'function';
  9185. }
  9186. function lib$es6$promise$utils$$isMaybeThenable(x) {
  9187. return typeof x === 'object' && x !== null;
  9188. }
  9189. var lib$es6$promise$utils$$_isArray;
  9190. if (!Array.isArray) {
  9191. lib$es6$promise$utils$$_isArray = function (x) {
  9192. return Object.prototype.toString.call(x) === '[object Array]';
  9193. };
  9194. } else {
  9195. lib$es6$promise$utils$$_isArray = Array.isArray;
  9196. }
  9197. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  9198. var lib$es6$promise$asap$$len = 0;
  9199. var lib$es6$promise$asap$$toString = {}.toString;
  9200. var lib$es6$promise$asap$$vertxNext;
  9201. var lib$es6$promise$asap$$customSchedulerFn;
  9202. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  9203. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  9204. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  9205. lib$es6$promise$asap$$len += 2;
  9206. if (lib$es6$promise$asap$$len === 2) {
  9207. // If len is 2, that means that we need to schedule an async flush.
  9208. // If additional callbacks are queued before the queue is flushed, they
  9209. // will be processed by this flush that we are scheduling.
  9210. if (lib$es6$promise$asap$$customSchedulerFn) {
  9211. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  9212. } else {
  9213. lib$es6$promise$asap$$scheduleFlush();
  9214. }
  9215. }
  9216. }
  9217. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  9218. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  9219. }
  9220. function lib$es6$promise$asap$$setAsap(asapFn) {
  9221. lib$es6$promise$asap$$asap = asapFn;
  9222. }
  9223. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  9224. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  9225. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  9226. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  9227. // test for web worker but not in IE10
  9228. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  9229. typeof importScripts !== 'undefined' &&
  9230. typeof MessageChannel !== 'undefined';
  9231. // node
  9232. function lib$es6$promise$asap$$useNextTick() {
  9233. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  9234. // see https://github.com/cujojs/when/issues/410 for details
  9235. return function() {
  9236. process.nextTick(lib$es6$promise$asap$$flush);
  9237. };
  9238. }
  9239. // vertx
  9240. function lib$es6$promise$asap$$useVertxTimer() {
  9241. return function() {
  9242. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  9243. };
  9244. }
  9245. function lib$es6$promise$asap$$useMutationObserver() {
  9246. var iterations = 0;
  9247. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  9248. var node = document.createTextNode('');
  9249. observer.observe(node, { characterData: true });
  9250. return function() {
  9251. node.data = (iterations = ++iterations % 2);
  9252. };
  9253. }
  9254. // web worker
  9255. function lib$es6$promise$asap$$useMessageChannel() {
  9256. var channel = new MessageChannel();
  9257. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  9258. return function () {
  9259. channel.port2.postMessage(0);
  9260. };
  9261. }
  9262. function lib$es6$promise$asap$$useSetTimeout() {
  9263. return function() {
  9264. setTimeout(lib$es6$promise$asap$$flush, 1);
  9265. };
  9266. }
  9267. var lib$es6$promise$asap$$queue = new Array(1000);
  9268. function lib$es6$promise$asap$$flush() {
  9269. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  9270. var callback = lib$es6$promise$asap$$queue[i];
  9271. var arg = lib$es6$promise$asap$$queue[i+1];
  9272. callback(arg);
  9273. lib$es6$promise$asap$$queue[i] = undefined;
  9274. lib$es6$promise$asap$$queue[i+1] = undefined;
  9275. }
  9276. lib$es6$promise$asap$$len = 0;
  9277. }
  9278. function lib$es6$promise$asap$$attemptVertx() {
  9279. try {
  9280. var r = require;
  9281. var vertx = r('vertx');
  9282. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  9283. return lib$es6$promise$asap$$useVertxTimer();
  9284. } catch(e) {
  9285. return lib$es6$promise$asap$$useSetTimeout();
  9286. }
  9287. }
  9288. var lib$es6$promise$asap$$scheduleFlush;
  9289. // Decide what async method to use to triggering processing of queued callbacks:
  9290. if (lib$es6$promise$asap$$isNode) {
  9291. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  9292. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  9293. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  9294. } else if (lib$es6$promise$asap$$isWorker) {
  9295. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  9296. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  9297. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  9298. } else {
  9299. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  9300. }
  9301. function lib$es6$promise$$internal$$noop() {}
  9302. var lib$es6$promise$$internal$$PENDING = void 0;
  9303. var lib$es6$promise$$internal$$FULFILLED = 1;
  9304. var lib$es6$promise$$internal$$REJECTED = 2;
  9305. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  9306. function lib$es6$promise$$internal$$selfFulfillment() {
  9307. return new TypeError("You cannot resolve a promise with itself");
  9308. }
  9309. function lib$es6$promise$$internal$$cannotReturnOwn() {
  9310. return new TypeError('A promises callback cannot return that same promise.');
  9311. }
  9312. function lib$es6$promise$$internal$$getThen(promise) {
  9313. try {
  9314. return promise.then;
  9315. } catch(error) {
  9316. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  9317. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  9318. }
  9319. }
  9320. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  9321. try {
  9322. then.call(value, fulfillmentHandler, rejectionHandler);
  9323. } catch(e) {
  9324. return e;
  9325. }
  9326. }
  9327. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  9328. lib$es6$promise$asap$$asap(function(promise) {
  9329. var sealed = false;
  9330. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  9331. if (sealed) { return; }
  9332. sealed = true;
  9333. if (thenable !== value) {
  9334. lib$es6$promise$$internal$$resolve(promise, value);
  9335. } else {
  9336. lib$es6$promise$$internal$$fulfill(promise, value);
  9337. }
  9338. }, function(reason) {
  9339. if (sealed) { return; }
  9340. sealed = true;
  9341. lib$es6$promise$$internal$$reject(promise, reason);
  9342. }, 'Settle: ' + (promise._label || ' unknown promise'));
  9343. if (!sealed && error) {
  9344. sealed = true;
  9345. lib$es6$promise$$internal$$reject(promise, error);
  9346. }
  9347. }, promise);
  9348. }
  9349. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  9350. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  9351. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  9352. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  9353. lib$es6$promise$$internal$$reject(promise, thenable._result);
  9354. } else {
  9355. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  9356. lib$es6$promise$$internal$$resolve(promise, value);
  9357. }, function(reason) {
  9358. lib$es6$promise$$internal$$reject(promise, reason);
  9359. });
  9360. }
  9361. }
  9362. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  9363. if (maybeThenable.constructor === promise.constructor) {
  9364. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  9365. } else {
  9366. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  9367. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  9368. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  9369. } else if (then === undefined) {
  9370. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  9371. } else if (lib$es6$promise$utils$$isFunction(then)) {
  9372. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  9373. } else {
  9374. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  9375. }
  9376. }
  9377. }
  9378. function lib$es6$promise$$internal$$resolve(promise, value) {
  9379. if (promise === value) {
  9380. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  9381. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  9382. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  9383. } else {
  9384. lib$es6$promise$$internal$$fulfill(promise, value);
  9385. }
  9386. }
  9387. function lib$es6$promise$$internal$$publishRejection(promise) {
  9388. if (promise._onerror) {
  9389. promise._onerror(promise._result);
  9390. }
  9391. lib$es6$promise$$internal$$publish(promise);
  9392. }
  9393. function lib$es6$promise$$internal$$fulfill(promise, value) {
  9394. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  9395. promise._result = value;
  9396. promise._state = lib$es6$promise$$internal$$FULFILLED;
  9397. if (promise._subscribers.length !== 0) {
  9398. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  9399. }
  9400. }
  9401. function lib$es6$promise$$internal$$reject(promise, reason) {
  9402. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  9403. promise._state = lib$es6$promise$$internal$$REJECTED;
  9404. promise._result = reason;
  9405. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  9406. }
  9407. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  9408. var subscribers = parent._subscribers;
  9409. var length = subscribers.length;
  9410. parent._onerror = null;
  9411. subscribers[length] = child;
  9412. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  9413. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  9414. if (length === 0 && parent._state) {
  9415. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  9416. }
  9417. }
  9418. function lib$es6$promise$$internal$$publish(promise) {
  9419. var subscribers = promise._subscribers;
  9420. var settled = promise._state;
  9421. if (subscribers.length === 0) { return; }
  9422. var child, callback, detail = promise._result;
  9423. for (var i = 0; i < subscribers.length; i += 3) {
  9424. child = subscribers[i];
  9425. callback = subscribers[i + settled];
  9426. if (child) {
  9427. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  9428. } else {
  9429. callback(detail);
  9430. }
  9431. }
  9432. promise._subscribers.length = 0;
  9433. }
  9434. function lib$es6$promise$$internal$$ErrorObject() {
  9435. this.error = null;
  9436. }
  9437. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  9438. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  9439. try {
  9440. return callback(detail);
  9441. } catch(e) {
  9442. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  9443. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  9444. }
  9445. }
  9446. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  9447. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  9448. value, error, succeeded, failed;
  9449. if (hasCallback) {
  9450. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  9451. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  9452. failed = true;
  9453. error = value.error;
  9454. value = null;
  9455. } else {
  9456. succeeded = true;
  9457. }
  9458. if (promise === value) {
  9459. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  9460. return;
  9461. }
  9462. } else {
  9463. value = detail;
  9464. succeeded = true;
  9465. }
  9466. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  9467. // noop
  9468. } else if (hasCallback && succeeded) {
  9469. lib$es6$promise$$internal$$resolve(promise, value);
  9470. } else if (failed) {
  9471. lib$es6$promise$$internal$$reject(promise, error);
  9472. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  9473. lib$es6$promise$$internal$$fulfill(promise, value);
  9474. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  9475. lib$es6$promise$$internal$$reject(promise, value);
  9476. }
  9477. }
  9478. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  9479. try {
  9480. resolver(function resolvePromise(value){
  9481. lib$es6$promise$$internal$$resolve(promise, value);
  9482. }, function rejectPromise(reason) {
  9483. lib$es6$promise$$internal$$reject(promise, reason);
  9484. });
  9485. } catch(e) {
  9486. lib$es6$promise$$internal$$reject(promise, e);
  9487. }
  9488. }
  9489. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  9490. var enumerator = this;
  9491. enumerator._instanceConstructor = Constructor;
  9492. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  9493. if (enumerator._validateInput(input)) {
  9494. enumerator._input = input;
  9495. enumerator.length = input.length;
  9496. enumerator._remaining = input.length;
  9497. enumerator._init();
  9498. if (enumerator.length === 0) {
  9499. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  9500. } else {
  9501. enumerator.length = enumerator.length || 0;
  9502. enumerator._enumerate();
  9503. if (enumerator._remaining === 0) {
  9504. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  9505. }
  9506. }
  9507. } else {
  9508. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  9509. }
  9510. }
  9511. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  9512. return lib$es6$promise$utils$$isArray(input);
  9513. };
  9514. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  9515. return new Error('Array Methods must be provided an Array');
  9516. };
  9517. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  9518. this._result = new Array(this.length);
  9519. };
  9520. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  9521. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  9522. var enumerator = this;
  9523. var length = enumerator.length;
  9524. var promise = enumerator.promise;
  9525. var input = enumerator._input;
  9526. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9527. enumerator._eachEntry(input[i], i);
  9528. }
  9529. };
  9530. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  9531. var enumerator = this;
  9532. var c = enumerator._instanceConstructor;
  9533. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  9534. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  9535. entry._onerror = null;
  9536. enumerator._settledAt(entry._state, i, entry._result);
  9537. } else {
  9538. enumerator._willSettleAt(c.resolve(entry), i);
  9539. }
  9540. } else {
  9541. enumerator._remaining--;
  9542. enumerator._result[i] = entry;
  9543. }
  9544. };
  9545. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  9546. var enumerator = this;
  9547. var promise = enumerator.promise;
  9548. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  9549. enumerator._remaining--;
  9550. if (state === lib$es6$promise$$internal$$REJECTED) {
  9551. lib$es6$promise$$internal$$reject(promise, value);
  9552. } else {
  9553. enumerator._result[i] = value;
  9554. }
  9555. }
  9556. if (enumerator._remaining === 0) {
  9557. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  9558. }
  9559. };
  9560. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  9561. var enumerator = this;
  9562. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  9563. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  9564. }, function(reason) {
  9565. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  9566. });
  9567. };
  9568. function lib$es6$promise$promise$all$$all(entries) {
  9569. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  9570. }
  9571. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  9572. function lib$es6$promise$promise$race$$race(entries) {
  9573. /*jshint validthis:true */
  9574. var Constructor = this;
  9575. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9576. if (!lib$es6$promise$utils$$isArray(entries)) {
  9577. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  9578. return promise;
  9579. }
  9580. var length = entries.length;
  9581. function onFulfillment(value) {
  9582. lib$es6$promise$$internal$$resolve(promise, value);
  9583. }
  9584. function onRejection(reason) {
  9585. lib$es6$promise$$internal$$reject(promise, reason);
  9586. }
  9587. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9588. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  9589. }
  9590. return promise;
  9591. }
  9592. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  9593. function lib$es6$promise$promise$resolve$$resolve(object) {
  9594. /*jshint validthis:true */
  9595. var Constructor = this;
  9596. if (object && typeof object === 'object' && object.constructor === Constructor) {
  9597. return object;
  9598. }
  9599. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9600. lib$es6$promise$$internal$$resolve(promise, object);
  9601. return promise;
  9602. }
  9603. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  9604. function lib$es6$promise$promise$reject$$reject(reason) {
  9605. /*jshint validthis:true */
  9606. var Constructor = this;
  9607. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9608. lib$es6$promise$$internal$$reject(promise, reason);
  9609. return promise;
  9610. }
  9611. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  9612. var lib$es6$promise$promise$$counter = 0;
  9613. function lib$es6$promise$promise$$needsResolver() {
  9614. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  9615. }
  9616. function lib$es6$promise$promise$$needsNew() {
  9617. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  9618. }
  9619. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  9620. /**
  9621. Promise objects represent the eventual result of an asynchronous operation. The
  9622. primary way of interacting with a promise is through its `then` method, which
  9623. registers callbacks to receive either a promise's eventual value or the reason
  9624. why the promise cannot be fulfilled.
  9625. Terminology
  9626. -----------
  9627. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  9628. - `thenable` is an object or function that defines a `then` method.
  9629. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  9630. - `exception` is a value that is thrown using the throw statement.
  9631. - `reason` is a value that indicates why a promise was rejected.
  9632. - `settled` the final resting state of a promise, fulfilled or rejected.
  9633. A promise can be in one of three states: pending, fulfilled, or rejected.
  9634. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  9635. state. Promises that are rejected have a rejection reason and are in the
  9636. rejected state. A fulfillment value is never a thenable.
  9637. Promises can also be said to *resolve* a value. If this value is also a
  9638. promise, then the original promise's settled state will match the value's
  9639. settled state. So a promise that *resolves* a promise that rejects will
  9640. itself reject, and a promise that *resolves* a promise that fulfills will
  9641. itself fulfill.
  9642. Basic Usage:
  9643. ------------
  9644. ```js
  9645. var promise = new Promise(function(resolve, reject) {
  9646. // on success
  9647. resolve(value);
  9648. // on failure
  9649. reject(reason);
  9650. });
  9651. promise.then(function(value) {
  9652. // on fulfillment
  9653. }, function(reason) {
  9654. // on rejection
  9655. });
  9656. ```
  9657. Advanced Usage:
  9658. ---------------
  9659. Promises shine when abstracting away asynchronous interactions such as
  9660. `XMLHttpRequest`s.
  9661. ```js
  9662. function getJSON(url) {
  9663. return new Promise(function(resolve, reject){
  9664. var xhr = new XMLHttpRequest();
  9665. xhr.open('GET', url);
  9666. xhr.onreadystatechange = handler;
  9667. xhr.responseType = 'json';
  9668. xhr.setRequestHeader('Accept', 'application/json');
  9669. xhr.send();
  9670. function handler() {
  9671. if (this.readyState === this.DONE) {
  9672. if (this.status === 200) {
  9673. resolve(this.response);
  9674. } else {
  9675. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  9676. }
  9677. }
  9678. };
  9679. });
  9680. }
  9681. getJSON('/posts.json').then(function(json) {
  9682. // on fulfillment
  9683. }, function(reason) {
  9684. // on rejection
  9685. });
  9686. ```
  9687. Unlike callbacks, promises are great composable primitives.
  9688. ```js
  9689. Promise.all([
  9690. getJSON('/posts'),
  9691. getJSON('/comments')
  9692. ]).then(function(values){
  9693. values[0] // => postsJSON
  9694. values[1] // => commentsJSON
  9695. return values;
  9696. });
  9697. ```
  9698. @class Promise
  9699. @param {function} resolver
  9700. Useful for tooling.
  9701. @constructor
  9702. */
  9703. function lib$es6$promise$promise$$Promise(resolver) {
  9704. this._id = lib$es6$promise$promise$$counter++;
  9705. this._state = undefined;
  9706. this._result = undefined;
  9707. this._subscribers = [];
  9708. if (lib$es6$promise$$internal$$noop !== resolver) {
  9709. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  9710. lib$es6$promise$promise$$needsResolver();
  9711. }
  9712. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  9713. lib$es6$promise$promise$$needsNew();
  9714. }
  9715. lib$es6$promise$$internal$$initializePromise(this, resolver);
  9716. }
  9717. }
  9718. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  9719. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  9720. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  9721. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  9722. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  9723. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  9724. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  9725. lib$es6$promise$promise$$Promise.prototype = {
  9726. constructor: lib$es6$promise$promise$$Promise,
  9727. /**
  9728. The primary way of interacting with a promise is through its `then` method,
  9729. which registers callbacks to receive either a promise's eventual value or the
  9730. reason why the promise cannot be fulfilled.
  9731. ```js
  9732. findUser().then(function(user){
  9733. // user is available
  9734. }, function(reason){
  9735. // user is unavailable, and you are given the reason why
  9736. });
  9737. ```
  9738. Chaining
  9739. --------
  9740. The return value of `then` is itself a promise. This second, 'downstream'
  9741. promise is resolved with the return value of the first promise's fulfillment
  9742. or rejection handler, or rejected if the handler throws an exception.
  9743. ```js
  9744. findUser().then(function (user) {
  9745. return user.name;
  9746. }, function (reason) {
  9747. return 'default name';
  9748. }).then(function (userName) {
  9749. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  9750. // will be `'default name'`
  9751. });
  9752. findUser().then(function (user) {
  9753. throw new Error('Found user, but still unhappy');
  9754. }, function (reason) {
  9755. throw new Error('`findUser` rejected and we're unhappy');
  9756. }).then(function (value) {
  9757. // never reached
  9758. }, function (reason) {
  9759. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  9760. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  9761. });
  9762. ```
  9763. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  9764. ```js
  9765. findUser().then(function (user) {
  9766. throw new PedagogicalException('Upstream error');
  9767. }).then(function (value) {
  9768. // never reached
  9769. }).then(function (value) {
  9770. // never reached
  9771. }, function (reason) {
  9772. // The `PedgagocialException` is propagated all the way down to here
  9773. });
  9774. ```
  9775. Assimilation
  9776. ------------
  9777. Sometimes the value you want to propagate to a downstream promise can only be
  9778. retrieved asynchronously. This can be achieved by returning a promise in the
  9779. fulfillment or rejection handler. The downstream promise will then be pending
  9780. until the returned promise is settled. This is called *assimilation*.
  9781. ```js
  9782. findUser().then(function (user) {
  9783. return findCommentsByAuthor(user);
  9784. }).then(function (comments) {
  9785. // The user's comments are now available
  9786. });
  9787. ```
  9788. If the assimliated promise rejects, then the downstream promise will also reject.
  9789. ```js
  9790. findUser().then(function (user) {
  9791. return findCommentsByAuthor(user);
  9792. }).then(function (comments) {
  9793. // If `findCommentsByAuthor` fulfills, we'll have the value here
  9794. }, function (reason) {
  9795. // If `findCommentsByAuthor` rejects, we'll have the reason here
  9796. });
  9797. ```
  9798. Simple Example
  9799. --------------
  9800. Synchronous Example
  9801. ```javascript
  9802. var result;
  9803. try {
  9804. result = findResult();
  9805. // success
  9806. } catch(reason) {
  9807. // failure
  9808. }
  9809. ```
  9810. Errback Example
  9811. ```js
  9812. findResult(function(result, err){
  9813. if (err) {
  9814. // failure
  9815. } else {
  9816. // success
  9817. }
  9818. });
  9819. ```
  9820. Promise Example;
  9821. ```javascript
  9822. findResult().then(function(result){
  9823. // success
  9824. }, function(reason){
  9825. // failure
  9826. });
  9827. ```
  9828. Advanced Example
  9829. --------------
  9830. Synchronous Example
  9831. ```javascript
  9832. var author, books;
  9833. try {
  9834. author = findAuthor();
  9835. books = findBooksByAuthor(author);
  9836. // success
  9837. } catch(reason) {
  9838. // failure
  9839. }
  9840. ```
  9841. Errback Example
  9842. ```js
  9843. function foundBooks(books) {
  9844. }
  9845. function failure(reason) {
  9846. }
  9847. findAuthor(function(author, err){
  9848. if (err) {
  9849. failure(err);
  9850. // failure
  9851. } else {
  9852. try {
  9853. findBoooksByAuthor(author, function(books, err) {
  9854. if (err) {
  9855. failure(err);
  9856. } else {
  9857. try {
  9858. foundBooks(books);
  9859. } catch(reason) {
  9860. failure(reason);
  9861. }
  9862. }
  9863. });
  9864. } catch(error) {
  9865. failure(err);
  9866. }
  9867. // success
  9868. }
  9869. });
  9870. ```
  9871. Promise Example;
  9872. ```javascript
  9873. findAuthor().
  9874. then(findBooksByAuthor).
  9875. then(function(books){
  9876. // found books
  9877. }).catch(function(reason){
  9878. // something went wrong
  9879. });
  9880. ```
  9881. @method then
  9882. @param {Function} onFulfilled
  9883. @param {Function} onRejected
  9884. Useful for tooling.
  9885. @return {Promise}
  9886. */
  9887. then: function(onFulfillment, onRejection) {
  9888. var parent = this;
  9889. var state = parent._state;
  9890. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  9891. return this;
  9892. }
  9893. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  9894. var result = parent._result;
  9895. if (state) {
  9896. var callback = arguments[state - 1];
  9897. lib$es6$promise$asap$$asap(function(){
  9898. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  9899. });
  9900. } else {
  9901. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  9902. }
  9903. return child;
  9904. },
  9905. /**
  9906. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  9907. as the catch block of a try/catch statement.
  9908. ```js
  9909. function findAuthor(){
  9910. throw new Error('couldn't find that author');
  9911. }
  9912. // synchronous
  9913. try {
  9914. findAuthor();
  9915. } catch(reason) {
  9916. // something went wrong
  9917. }
  9918. // async with promises
  9919. findAuthor().catch(function(reason){
  9920. // something went wrong
  9921. });
  9922. ```
  9923. @method catch
  9924. @param {Function} onRejection
  9925. Useful for tooling.
  9926. @return {Promise}
  9927. */
  9928. 'catch': function(onRejection) {
  9929. return this.then(null, onRejection);
  9930. }
  9931. };
  9932. function lib$es6$promise$polyfill$$polyfill() {
  9933. var local;
  9934. if (typeof global !== 'undefined') {
  9935. local = global;
  9936. } else if (typeof self !== 'undefined') {
  9937. local = self;
  9938. } else {
  9939. try {
  9940. local = Function('return this')();
  9941. } catch (e) {
  9942. throw new Error('polyfill failed because global object is unavailable in this environment');
  9943. }
  9944. }
  9945. var P = local.Promise;
  9946. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  9947. return;
  9948. }
  9949. local.Promise = lib$es6$promise$promise$$default;
  9950. }
  9951. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  9952. var lib$es6$promise$umd$$ES6Promise = {
  9953. 'Promise': lib$es6$promise$promise$$default,
  9954. 'polyfill': lib$es6$promise$polyfill$$default
  9955. };
  9956. /* global define:true module:true window: true */
  9957. if (typeof define === 'function' && define['amd']) {
  9958. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  9959. } else if (typeof module !== 'undefined' && module['exports']) {
  9960. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  9961. } else if (typeof this !== 'undefined') {
  9962. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  9963. }
  9964. lib$es6$promise$polyfill$$default();
  9965. }).call(this);
  9966. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9967. },{"_process":77}],35:[function(require,module,exports){
  9968. // Top level file is just a mixin of submodules & constants
  9969. 'use strict';
  9970. var assign = require('./lib/utils/common').assign;
  9971. var deflate = require('./lib/deflate');
  9972. var inflate = require('./lib/inflate');
  9973. var constants = require('./lib/zlib/constants');
  9974. var pako = {};
  9975. assign(pako, deflate, inflate, constants);
  9976. module.exports = pako;
  9977. },{"./lib/deflate":36,"./lib/inflate":37,"./lib/utils/common":38,"./lib/zlib/constants":41}],36:[function(require,module,exports){
  9978. 'use strict';
  9979. var zlib_deflate = require('./zlib/deflate.js');
  9980. var utils = require('./utils/common');
  9981. var strings = require('./utils/strings');
  9982. var msg = require('./zlib/messages');
  9983. var zstream = require('./zlib/zstream');
  9984. var toString = Object.prototype.toString;
  9985. /* Public constants ==========================================================*/
  9986. /* ===========================================================================*/
  9987. var Z_NO_FLUSH = 0;
  9988. var Z_FINISH = 4;
  9989. var Z_OK = 0;
  9990. var Z_STREAM_END = 1;
  9991. var Z_SYNC_FLUSH = 2;
  9992. var Z_DEFAULT_COMPRESSION = -1;
  9993. var Z_DEFAULT_STRATEGY = 0;
  9994. var Z_DEFLATED = 8;
  9995. /* ===========================================================================*/
  9996. /**
  9997. * class Deflate
  9998. *
  9999. * Generic JS-style wrapper for zlib calls. If you don't need
  10000. * streaming behaviour - use more simple functions: [[deflate]],
  10001. * [[deflateRaw]] and [[gzip]].
  10002. **/
  10003. /* internal
  10004. * Deflate.chunks -> Array
  10005. *
  10006. * Chunks of output data, if [[Deflate#onData]] not overriden.
  10007. **/
  10008. /**
  10009. * Deflate.result -> Uint8Array|Array
  10010. *
  10011. * Compressed result, generated by default [[Deflate#onData]]
  10012. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  10013. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  10014. * push a chunk with explicit flush (call [[Deflate#push]] with
  10015. * `Z_SYNC_FLUSH` param).
  10016. **/
  10017. /**
  10018. * Deflate.err -> Number
  10019. *
  10020. * Error code after deflate finished. 0 (Z_OK) on success.
  10021. * You will not need it in real life, because deflate errors
  10022. * are possible only on wrong options or bad `onData` / `onEnd`
  10023. * custom handlers.
  10024. **/
  10025. /**
  10026. * Deflate.msg -> String
  10027. *
  10028. * Error message, if [[Deflate.err]] != 0
  10029. **/
  10030. /**
  10031. * new Deflate(options)
  10032. * - options (Object): zlib deflate options.
  10033. *
  10034. * Creates new deflator instance with specified params. Throws exception
  10035. * on bad params. Supported options:
  10036. *
  10037. * - `level`
  10038. * - `windowBits`
  10039. * - `memLevel`
  10040. * - `strategy`
  10041. *
  10042. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10043. * for more information on these.
  10044. *
  10045. * Additional options, for internal needs:
  10046. *
  10047. * - `chunkSize` - size of generated data chunks (16K by default)
  10048. * - `raw` (Boolean) - do raw deflate
  10049. * - `gzip` (Boolean) - create gzip wrapper
  10050. * - `to` (String) - if equal to 'string', then result will be "binary string"
  10051. * (each char code [0..255])
  10052. * - `header` (Object) - custom header for gzip
  10053. * - `text` (Boolean) - true if compressed data believed to be text
  10054. * - `time` (Number) - modification time, unix timestamp
  10055. * - `os` (Number) - operation system code
  10056. * - `extra` (Array) - array of bytes with extra data (max 65536)
  10057. * - `name` (String) - file name (binary string)
  10058. * - `comment` (String) - comment (binary string)
  10059. * - `hcrc` (Boolean) - true if header crc should be added
  10060. *
  10061. * ##### Example:
  10062. *
  10063. * ```javascript
  10064. * var pako = require('pako')
  10065. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  10066. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  10067. *
  10068. * var deflate = new pako.Deflate({ level: 3});
  10069. *
  10070. * deflate.push(chunk1, false);
  10071. * deflate.push(chunk2, true); // true -> last chunk
  10072. *
  10073. * if (deflate.err) { throw new Error(deflate.err); }
  10074. *
  10075. * console.log(deflate.result);
  10076. * ```
  10077. **/
  10078. var Deflate = function(options) {
  10079. this.options = utils.assign({
  10080. level: Z_DEFAULT_COMPRESSION,
  10081. method: Z_DEFLATED,
  10082. chunkSize: 16384,
  10083. windowBits: 15,
  10084. memLevel: 8,
  10085. strategy: Z_DEFAULT_STRATEGY,
  10086. to: ''
  10087. }, options || {});
  10088. var opt = this.options;
  10089. if (opt.raw && (opt.windowBits > 0)) {
  10090. opt.windowBits = -opt.windowBits;
  10091. }
  10092. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  10093. opt.windowBits += 16;
  10094. }
  10095. this.err = 0; // error code, if happens (0 = Z_OK)
  10096. this.msg = ''; // error message
  10097. this.ended = false; // used to avoid multiple onEnd() calls
  10098. this.chunks = []; // chunks of compressed data
  10099. this.strm = new zstream();
  10100. this.strm.avail_out = 0;
  10101. var status = zlib_deflate.deflateInit2(
  10102. this.strm,
  10103. opt.level,
  10104. opt.method,
  10105. opt.windowBits,
  10106. opt.memLevel,
  10107. opt.strategy
  10108. );
  10109. if (status !== Z_OK) {
  10110. throw new Error(msg[status]);
  10111. }
  10112. if (opt.header) {
  10113. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  10114. }
  10115. };
  10116. /**
  10117. * Deflate#push(data[, mode]) -> Boolean
  10118. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  10119. * converted to utf8 byte sequence.
  10120. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  10121. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  10122. *
  10123. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  10124. * new compressed chunks. Returns `true` on success. The last data block must have
  10125. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  10126. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  10127. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  10128. *
  10129. * On fail call [[Deflate#onEnd]] with error code and return false.
  10130. *
  10131. * We strongly recommend to use `Uint8Array` on input for best speed (output
  10132. * array format is detected automatically). Also, don't skip last param and always
  10133. * use the same type in your code (boolean or number). That will improve JS speed.
  10134. *
  10135. * For regular `Array`-s make sure all elements are [0..255].
  10136. *
  10137. * ##### Example
  10138. *
  10139. * ```javascript
  10140. * push(chunk, false); // push one of data chunks
  10141. * ...
  10142. * push(chunk, true); // push last chunk
  10143. * ```
  10144. **/
  10145. Deflate.prototype.push = function(data, mode) {
  10146. var strm = this.strm;
  10147. var chunkSize = this.options.chunkSize;
  10148. var status, _mode;
  10149. if (this.ended) { return false; }
  10150. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  10151. // Convert data if needed
  10152. if (typeof data === 'string') {
  10153. // If we need to compress text, change encoding to utf8.
  10154. strm.input = strings.string2buf(data);
  10155. } else if (toString.call(data) === '[object ArrayBuffer]') {
  10156. strm.input = new Uint8Array(data);
  10157. } else {
  10158. strm.input = data;
  10159. }
  10160. strm.next_in = 0;
  10161. strm.avail_in = strm.input.length;
  10162. do {
  10163. if (strm.avail_out === 0) {
  10164. strm.output = new utils.Buf8(chunkSize);
  10165. strm.next_out = 0;
  10166. strm.avail_out = chunkSize;
  10167. }
  10168. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  10169. if (status !== Z_STREAM_END && status !== Z_OK) {
  10170. this.onEnd(status);
  10171. this.ended = true;
  10172. return false;
  10173. }
  10174. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  10175. if (this.options.to === 'string') {
  10176. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  10177. } else {
  10178. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  10179. }
  10180. }
  10181. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  10182. // Finalize on the last chunk.
  10183. if (_mode === Z_FINISH) {
  10184. status = zlib_deflate.deflateEnd(this.strm);
  10185. this.onEnd(status);
  10186. this.ended = true;
  10187. return status === Z_OK;
  10188. }
  10189. // callback interim results if Z_SYNC_FLUSH.
  10190. if (_mode === Z_SYNC_FLUSH) {
  10191. this.onEnd(Z_OK);
  10192. strm.avail_out = 0;
  10193. return true;
  10194. }
  10195. return true;
  10196. };
  10197. /**
  10198. * Deflate#onData(chunk) -> Void
  10199. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  10200. * on js engine support. When string output requested, each chunk
  10201. * will be string.
  10202. *
  10203. * By default, stores data blocks in `chunks[]` property and glue
  10204. * those in `onEnd`. Override this handler, if you need another behaviour.
  10205. **/
  10206. Deflate.prototype.onData = function(chunk) {
  10207. this.chunks.push(chunk);
  10208. };
  10209. /**
  10210. * Deflate#onEnd(status) -> Void
  10211. * - status (Number): deflate status. 0 (Z_OK) on success,
  10212. * other if not.
  10213. *
  10214. * Called once after you tell deflate that the input stream is
  10215. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  10216. * or if an error happened. By default - join collected chunks,
  10217. * free memory and fill `results` / `err` properties.
  10218. **/
  10219. Deflate.prototype.onEnd = function(status) {
  10220. // On success - join
  10221. if (status === Z_OK) {
  10222. if (this.options.to === 'string') {
  10223. this.result = this.chunks.join('');
  10224. } else {
  10225. this.result = utils.flattenChunks(this.chunks);
  10226. }
  10227. }
  10228. this.chunks = [];
  10229. this.err = status;
  10230. this.msg = this.strm.msg;
  10231. };
  10232. /**
  10233. * deflate(data[, options]) -> Uint8Array|Array|String
  10234. * - data (Uint8Array|Array|String): input data to compress.
  10235. * - options (Object): zlib deflate options.
  10236. *
  10237. * Compress `data` with deflate alrorythm and `options`.
  10238. *
  10239. * Supported options are:
  10240. *
  10241. * - level
  10242. * - windowBits
  10243. * - memLevel
  10244. * - strategy
  10245. *
  10246. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10247. * for more information on these.
  10248. *
  10249. * Sugar (options):
  10250. *
  10251. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10252. * negative windowBits implicitly.
  10253. * - `to` (String) - if equal to 'string', then result will be "binary string"
  10254. * (each char code [0..255])
  10255. *
  10256. * ##### Example:
  10257. *
  10258. * ```javascript
  10259. * var pako = require('pako')
  10260. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  10261. *
  10262. * console.log(pako.deflate(data));
  10263. * ```
  10264. **/
  10265. function deflate(input, options) {
  10266. var deflator = new Deflate(options);
  10267. deflator.push(input, true);
  10268. // That will never happens, if you don't cheat with options :)
  10269. if (deflator.err) { throw deflator.msg; }
  10270. return deflator.result;
  10271. }
  10272. /**
  10273. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  10274. * - data (Uint8Array|Array|String): input data to compress.
  10275. * - options (Object): zlib deflate options.
  10276. *
  10277. * The same as [[deflate]], but creates raw data, without wrapper
  10278. * (header and adler32 crc).
  10279. **/
  10280. function deflateRaw(input, options) {
  10281. options = options || {};
  10282. options.raw = true;
  10283. return deflate(input, options);
  10284. }
  10285. /**
  10286. * gzip(data[, options]) -> Uint8Array|Array|String
  10287. * - data (Uint8Array|Array|String): input data to compress.
  10288. * - options (Object): zlib deflate options.
  10289. *
  10290. * The same as [[deflate]], but create gzip wrapper instead of
  10291. * deflate one.
  10292. **/
  10293. function gzip(input, options) {
  10294. options = options || {};
  10295. options.gzip = true;
  10296. return deflate(input, options);
  10297. }
  10298. exports.Deflate = Deflate;
  10299. exports.deflate = deflate;
  10300. exports.deflateRaw = deflateRaw;
  10301. exports.gzip = gzip;
  10302. },{"./utils/common":38,"./utils/strings":39,"./zlib/deflate.js":43,"./zlib/messages":48,"./zlib/zstream":50}],37:[function(require,module,exports){
  10303. 'use strict';
  10304. var zlib_inflate = require('./zlib/inflate.js');
  10305. var utils = require('./utils/common');
  10306. var strings = require('./utils/strings');
  10307. var c = require('./zlib/constants');
  10308. var msg = require('./zlib/messages');
  10309. var zstream = require('./zlib/zstream');
  10310. var gzheader = require('./zlib/gzheader');
  10311. var toString = Object.prototype.toString;
  10312. /**
  10313. * class Inflate
  10314. *
  10315. * Generic JS-style wrapper for zlib calls. If you don't need
  10316. * streaming behaviour - use more simple functions: [[inflate]]
  10317. * and [[inflateRaw]].
  10318. **/
  10319. /* internal
  10320. * inflate.chunks -> Array
  10321. *
  10322. * Chunks of output data, if [[Inflate#onData]] not overriden.
  10323. **/
  10324. /**
  10325. * Inflate.result -> Uint8Array|Array|String
  10326. *
  10327. * Uncompressed result, generated by default [[Inflate#onData]]
  10328. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  10329. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  10330. * push a chunk with explicit flush (call [[Inflate#push]] with
  10331. * `Z_SYNC_FLUSH` param).
  10332. **/
  10333. /**
  10334. * Inflate.err -> Number
  10335. *
  10336. * Error code after inflate finished. 0 (Z_OK) on success.
  10337. * Should be checked if broken data possible.
  10338. **/
  10339. /**
  10340. * Inflate.msg -> String
  10341. *
  10342. * Error message, if [[Inflate.err]] != 0
  10343. **/
  10344. /**
  10345. * new Inflate(options)
  10346. * - options (Object): zlib inflate options.
  10347. *
  10348. * Creates new inflator instance with specified params. Throws exception
  10349. * on bad params. Supported options:
  10350. *
  10351. * - `windowBits`
  10352. *
  10353. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10354. * for more information on these.
  10355. *
  10356. * Additional options, for internal needs:
  10357. *
  10358. * - `chunkSize` - size of generated data chunks (16K by default)
  10359. * - `raw` (Boolean) - do raw inflate
  10360. * - `to` (String) - if equal to 'string', then result will be converted
  10361. * from utf8 to utf16 (javascript) string. When string output requested,
  10362. * chunk length can differ from `chunkSize`, depending on content.
  10363. *
  10364. * By default, when no options set, autodetect deflate/gzip data format via
  10365. * wrapper header.
  10366. *
  10367. * ##### Example:
  10368. *
  10369. * ```javascript
  10370. * var pako = require('pako')
  10371. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  10372. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  10373. *
  10374. * var inflate = new pako.Inflate({ level: 3});
  10375. *
  10376. * inflate.push(chunk1, false);
  10377. * inflate.push(chunk2, true); // true -> last chunk
  10378. *
  10379. * if (inflate.err) { throw new Error(inflate.err); }
  10380. *
  10381. * console.log(inflate.result);
  10382. * ```
  10383. **/
  10384. var Inflate = function(options) {
  10385. this.options = utils.assign({
  10386. chunkSize: 16384,
  10387. windowBits: 0,
  10388. to: ''
  10389. }, options || {});
  10390. var opt = this.options;
  10391. // Force window size for `raw` data, if not set directly,
  10392. // because we have no header for autodetect.
  10393. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  10394. opt.windowBits = -opt.windowBits;
  10395. if (opt.windowBits === 0) { opt.windowBits = -15; }
  10396. }
  10397. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  10398. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  10399. !(options && options.windowBits)) {
  10400. opt.windowBits += 32;
  10401. }
  10402. // Gzip header has no info about windows size, we can do autodetect only
  10403. // for deflate. So, if window size not set, force it to max when gzip possible
  10404. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  10405. // bit 3 (16) -> gzipped data
  10406. // bit 4 (32) -> autodetect gzip/deflate
  10407. if ((opt.windowBits & 15) === 0) {
  10408. opt.windowBits |= 15;
  10409. }
  10410. }
  10411. this.err = 0; // error code, if happens (0 = Z_OK)
  10412. this.msg = ''; // error message
  10413. this.ended = false; // used to avoid multiple onEnd() calls
  10414. this.chunks = []; // chunks of compressed data
  10415. this.strm = new zstream();
  10416. this.strm.avail_out = 0;
  10417. var status = zlib_inflate.inflateInit2(
  10418. this.strm,
  10419. opt.windowBits
  10420. );
  10421. if (status !== c.Z_OK) {
  10422. throw new Error(msg[status]);
  10423. }
  10424. this.header = new gzheader();
  10425. zlib_inflate.inflateGetHeader(this.strm, this.header);
  10426. };
  10427. /**
  10428. * Inflate#push(data[, mode]) -> Boolean
  10429. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  10430. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  10431. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  10432. *
  10433. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  10434. * new output chunks. Returns `true` on success. The last data block must have
  10435. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  10436. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  10437. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  10438. *
  10439. * On fail call [[Inflate#onEnd]] with error code and return false.
  10440. *
  10441. * We strongly recommend to use `Uint8Array` on input for best speed (output
  10442. * format is detected automatically). Also, don't skip last param and always
  10443. * use the same type in your code (boolean or number). That will improve JS speed.
  10444. *
  10445. * For regular `Array`-s make sure all elements are [0..255].
  10446. *
  10447. * ##### Example
  10448. *
  10449. * ```javascript
  10450. * push(chunk, false); // push one of data chunks
  10451. * ...
  10452. * push(chunk, true); // push last chunk
  10453. * ```
  10454. **/
  10455. Inflate.prototype.push = function(data, mode) {
  10456. var strm = this.strm;
  10457. var chunkSize = this.options.chunkSize;
  10458. var status, _mode;
  10459. var next_out_utf8, tail, utf8str;
  10460. if (this.ended) { return false; }
  10461. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  10462. // Convert data if needed
  10463. if (typeof data === 'string') {
  10464. // Only binary strings can be decompressed on practice
  10465. strm.input = strings.binstring2buf(data);
  10466. } else if (toString.call(data) === '[object ArrayBuffer]') {
  10467. strm.input = new Uint8Array(data);
  10468. } else {
  10469. strm.input = data;
  10470. }
  10471. strm.next_in = 0;
  10472. strm.avail_in = strm.input.length;
  10473. do {
  10474. if (strm.avail_out === 0) {
  10475. strm.output = new utils.Buf8(chunkSize);
  10476. strm.next_out = 0;
  10477. strm.avail_out = chunkSize;
  10478. }
  10479. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  10480. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  10481. this.onEnd(status);
  10482. this.ended = true;
  10483. return false;
  10484. }
  10485. if (strm.next_out) {
  10486. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  10487. if (this.options.to === 'string') {
  10488. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  10489. tail = strm.next_out - next_out_utf8;
  10490. utf8str = strings.buf2string(strm.output, next_out_utf8);
  10491. // move tail
  10492. strm.next_out = tail;
  10493. strm.avail_out = chunkSize - tail;
  10494. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  10495. this.onData(utf8str);
  10496. } else {
  10497. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  10498. }
  10499. }
  10500. }
  10501. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  10502. if (status === c.Z_STREAM_END) {
  10503. _mode = c.Z_FINISH;
  10504. }
  10505. // Finalize on the last chunk.
  10506. if (_mode === c.Z_FINISH) {
  10507. status = zlib_inflate.inflateEnd(this.strm);
  10508. this.onEnd(status);
  10509. this.ended = true;
  10510. return status === c.Z_OK;
  10511. }
  10512. // callback interim results if Z_SYNC_FLUSH.
  10513. if (_mode === c.Z_SYNC_FLUSH) {
  10514. this.onEnd(c.Z_OK);
  10515. strm.avail_out = 0;
  10516. return true;
  10517. }
  10518. return true;
  10519. };
  10520. /**
  10521. * Inflate#onData(chunk) -> Void
  10522. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  10523. * on js engine support. When string output requested, each chunk
  10524. * will be string.
  10525. *
  10526. * By default, stores data blocks in `chunks[]` property and glue
  10527. * those in `onEnd`. Override this handler, if you need another behaviour.
  10528. **/
  10529. Inflate.prototype.onData = function(chunk) {
  10530. this.chunks.push(chunk);
  10531. };
  10532. /**
  10533. * Inflate#onEnd(status) -> Void
  10534. * - status (Number): inflate status. 0 (Z_OK) on success,
  10535. * other if not.
  10536. *
  10537. * Called either after you tell inflate that the input stream is
  10538. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  10539. * or if an error happened. By default - join collected chunks,
  10540. * free memory and fill `results` / `err` properties.
  10541. **/
  10542. Inflate.prototype.onEnd = function(status) {
  10543. // On success - join
  10544. if (status === c.Z_OK) {
  10545. if (this.options.to === 'string') {
  10546. // Glue & convert here, until we teach pako to send
  10547. // utf8 alligned strings to onData
  10548. this.result = this.chunks.join('');
  10549. } else {
  10550. this.result = utils.flattenChunks(this.chunks);
  10551. }
  10552. }
  10553. this.chunks = [];
  10554. this.err = status;
  10555. this.msg = this.strm.msg;
  10556. };
  10557. /**
  10558. * inflate(data[, options]) -> Uint8Array|Array|String
  10559. * - data (Uint8Array|Array|String): input data to decompress.
  10560. * - options (Object): zlib inflate options.
  10561. *
  10562. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  10563. * format via wrapper header by default. That's why we don't provide
  10564. * separate `ungzip` method.
  10565. *
  10566. * Supported options are:
  10567. *
  10568. * - windowBits
  10569. *
  10570. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  10571. * for more information.
  10572. *
  10573. * Sugar (options):
  10574. *
  10575. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10576. * negative windowBits implicitly.
  10577. * - `to` (String) - if equal to 'string', then result will be converted
  10578. * from utf8 to utf16 (javascript) string. When string output requested,
  10579. * chunk length can differ from `chunkSize`, depending on content.
  10580. *
  10581. *
  10582. * ##### Example:
  10583. *
  10584. * ```javascript
  10585. * var pako = require('pako')
  10586. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  10587. * , output;
  10588. *
  10589. * try {
  10590. * output = pako.inflate(input);
  10591. * } catch (err)
  10592. * console.log(err);
  10593. * }
  10594. * ```
  10595. **/
  10596. function inflate(input, options) {
  10597. var inflator = new Inflate(options);
  10598. inflator.push(input, true);
  10599. // That will never happens, if you don't cheat with options :)
  10600. if (inflator.err) { throw inflator.msg; }
  10601. return inflator.result;
  10602. }
  10603. /**
  10604. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  10605. * - data (Uint8Array|Array|String): input data to decompress.
  10606. * - options (Object): zlib inflate options.
  10607. *
  10608. * The same as [[inflate]], but creates raw data, without wrapper
  10609. * (header and adler32 crc).
  10610. **/
  10611. function inflateRaw(input, options) {
  10612. options = options || {};
  10613. options.raw = true;
  10614. return inflate(input, options);
  10615. }
  10616. /**
  10617. * ungzip(data[, options]) -> Uint8Array|Array|String
  10618. * - data (Uint8Array|Array|String): input data to decompress.
  10619. * - options (Object): zlib inflate options.
  10620. *
  10621. * Just shortcut to [[inflate]], because it autodetects format
  10622. * by header.content. Done for convenience.
  10623. **/
  10624. exports.Inflate = Inflate;
  10625. exports.inflate = inflate;
  10626. exports.inflateRaw = inflateRaw;
  10627. exports.ungzip = inflate;
  10628. },{"./utils/common":38,"./utils/strings":39,"./zlib/constants":41,"./zlib/gzheader":44,"./zlib/inflate.js":46,"./zlib/messages":48,"./zlib/zstream":50}],38:[function(require,module,exports){
  10629. 'use strict';
  10630. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  10631. (typeof Uint16Array !== 'undefined') &&
  10632. (typeof Int32Array !== 'undefined');
  10633. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  10634. var sources = Array.prototype.slice.call(arguments, 1);
  10635. while (sources.length) {
  10636. var source = sources.shift();
  10637. if (!source) { continue; }
  10638. if (typeof source !== 'object') {
  10639. throw new TypeError(source + 'must be non-object');
  10640. }
  10641. for (var p in source) {
  10642. if (source.hasOwnProperty(p)) {
  10643. obj[p] = source[p];
  10644. }
  10645. }
  10646. }
  10647. return obj;
  10648. };
  10649. // reduce buffer size, avoiding mem copy
  10650. exports.shrinkBuf = function (buf, size) {
  10651. if (buf.length === size) { return buf; }
  10652. if (buf.subarray) { return buf.subarray(0, size); }
  10653. buf.length = size;
  10654. return buf;
  10655. };
  10656. var fnTyped = {
  10657. arraySet: function (dest, src, src_offs, len, dest_offs) {
  10658. if (src.subarray && dest.subarray) {
  10659. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  10660. return;
  10661. }
  10662. // Fallback to ordinary array
  10663. for (var i=0; i<len; i++) {
  10664. dest[dest_offs + i] = src[src_offs + i];
  10665. }
  10666. },
  10667. // Join array of chunks to single array.
  10668. flattenChunks: function(chunks) {
  10669. var i, l, len, pos, chunk, result;
  10670. // calculate data length
  10671. len = 0;
  10672. for (i=0, l=chunks.length; i<l; i++) {
  10673. len += chunks[i].length;
  10674. }
  10675. // join chunks
  10676. result = new Uint8Array(len);
  10677. pos = 0;
  10678. for (i=0, l=chunks.length; i<l; i++) {
  10679. chunk = chunks[i];
  10680. result.set(chunk, pos);
  10681. pos += chunk.length;
  10682. }
  10683. return result;
  10684. }
  10685. };
  10686. var fnUntyped = {
  10687. arraySet: function (dest, src, src_offs, len, dest_offs) {
  10688. for (var i=0; i<len; i++) {
  10689. dest[dest_offs + i] = src[src_offs + i];
  10690. }
  10691. },
  10692. // Join array of chunks to single array.
  10693. flattenChunks: function(chunks) {
  10694. return [].concat.apply([], chunks);
  10695. }
  10696. };
  10697. // Enable/Disable typed arrays use, for testing
  10698. //
  10699. exports.setTyped = function (on) {
  10700. if (on) {
  10701. exports.Buf8 = Uint8Array;
  10702. exports.Buf16 = Uint16Array;
  10703. exports.Buf32 = Int32Array;
  10704. exports.assign(exports, fnTyped);
  10705. } else {
  10706. exports.Buf8 = Array;
  10707. exports.Buf16 = Array;
  10708. exports.Buf32 = Array;
  10709. exports.assign(exports, fnUntyped);
  10710. }
  10711. };
  10712. exports.setTyped(TYPED_OK);
  10713. },{}],39:[function(require,module,exports){
  10714. // String encode/decode helpers
  10715. 'use strict';
  10716. var utils = require('./common');
  10717. // Quick check if we can use fast array to bin string conversion
  10718. //
  10719. // - apply(Array) can fail on Android 2.2
  10720. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  10721. //
  10722. var STR_APPLY_OK = true;
  10723. var STR_APPLY_UIA_OK = true;
  10724. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  10725. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  10726. // Table with utf8 lengths (calculated by first byte of sequence)
  10727. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  10728. // because max possible codepoint is 0x10ffff
  10729. var _utf8len = new utils.Buf8(256);
  10730. for (var q=0; q<256; q++) {
  10731. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  10732. }
  10733. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  10734. // convert string to array (typed, when possible)
  10735. exports.string2buf = function (str) {
  10736. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  10737. // count binary size
  10738. for (m_pos = 0; m_pos < str_len; m_pos++) {
  10739. c = str.charCodeAt(m_pos);
  10740. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  10741. c2 = str.charCodeAt(m_pos+1);
  10742. if ((c2 & 0xfc00) === 0xdc00) {
  10743. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  10744. m_pos++;
  10745. }
  10746. }
  10747. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  10748. }
  10749. // allocate buffer
  10750. buf = new utils.Buf8(buf_len);
  10751. // convert
  10752. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  10753. c = str.charCodeAt(m_pos);
  10754. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  10755. c2 = str.charCodeAt(m_pos+1);
  10756. if ((c2 & 0xfc00) === 0xdc00) {
  10757. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  10758. m_pos++;
  10759. }
  10760. }
  10761. if (c < 0x80) {
  10762. /* one byte */
  10763. buf[i++] = c;
  10764. } else if (c < 0x800) {
  10765. /* two bytes */
  10766. buf[i++] = 0xC0 | (c >>> 6);
  10767. buf[i++] = 0x80 | (c & 0x3f);
  10768. } else if (c < 0x10000) {
  10769. /* three bytes */
  10770. buf[i++] = 0xE0 | (c >>> 12);
  10771. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  10772. buf[i++] = 0x80 | (c & 0x3f);
  10773. } else {
  10774. /* four bytes */
  10775. buf[i++] = 0xf0 | (c >>> 18);
  10776. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  10777. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  10778. buf[i++] = 0x80 | (c & 0x3f);
  10779. }
  10780. }
  10781. return buf;
  10782. };
  10783. // Helper (used in 2 places)
  10784. function buf2binstring(buf, len) {
  10785. // use fallback for big arrays to avoid stack overflow
  10786. if (len < 65537) {
  10787. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  10788. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  10789. }
  10790. }
  10791. var result = '';
  10792. for (var i=0; i < len; i++) {
  10793. result += String.fromCharCode(buf[i]);
  10794. }
  10795. return result;
  10796. }
  10797. // Convert byte array to binary string
  10798. exports.buf2binstring = function(buf) {
  10799. return buf2binstring(buf, buf.length);
  10800. };
  10801. // Convert binary string (typed, when possible)
  10802. exports.binstring2buf = function(str) {
  10803. var buf = new utils.Buf8(str.length);
  10804. for (var i=0, len=buf.length; i < len; i++) {
  10805. buf[i] = str.charCodeAt(i);
  10806. }
  10807. return buf;
  10808. };
  10809. // convert array to string
  10810. exports.buf2string = function (buf, max) {
  10811. var i, out, c, c_len;
  10812. var len = max || buf.length;
  10813. // Reserve max possible length (2 words per char)
  10814. // NB: by unknown reasons, Array is significantly faster for
  10815. // String.fromCharCode.apply than Uint16Array.
  10816. var utf16buf = new Array(len*2);
  10817. for (out=0, i=0; i<len;) {
  10818. c = buf[i++];
  10819. // quick process ascii
  10820. if (c < 0x80) { utf16buf[out++] = c; continue; }
  10821. c_len = _utf8len[c];
  10822. // skip 5 & 6 byte codes
  10823. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  10824. // apply mask on first byte
  10825. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  10826. // join the rest
  10827. while (c_len > 1 && i < len) {
  10828. c = (c << 6) | (buf[i++] & 0x3f);
  10829. c_len--;
  10830. }
  10831. // terminated by end of string?
  10832. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  10833. if (c < 0x10000) {
  10834. utf16buf[out++] = c;
  10835. } else {
  10836. c -= 0x10000;
  10837. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  10838. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  10839. }
  10840. }
  10841. return buf2binstring(utf16buf, out);
  10842. };
  10843. // Calculate max possible position in utf8 buffer,
  10844. // that will not break sequence. If that's not possible
  10845. // - (very small limits) return max size as is.
  10846. //
  10847. // buf[] - utf8 bytes array
  10848. // max - length limit (mandatory);
  10849. exports.utf8border = function(buf, max) {
  10850. var pos;
  10851. max = max || buf.length;
  10852. if (max > buf.length) { max = buf.length; }
  10853. // go back from last position, until start of sequence found
  10854. pos = max-1;
  10855. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  10856. // Fuckup - very small and broken sequence,
  10857. // return max, because we should return something anyway.
  10858. if (pos < 0) { return max; }
  10859. // If we came to start of buffer - that means vuffer is too small,
  10860. // return max too.
  10861. if (pos === 0) { return max; }
  10862. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  10863. };
  10864. },{"./common":38}],40:[function(require,module,exports){
  10865. 'use strict';
  10866. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  10867. // It doesn't worth to make additional optimizationa as in original.
  10868. // Small size is preferable.
  10869. function adler32(adler, buf, len, pos) {
  10870. var s1 = (adler & 0xffff) |0,
  10871. s2 = ((adler >>> 16) & 0xffff) |0,
  10872. n = 0;
  10873. while (len !== 0) {
  10874. // Set limit ~ twice less than 5552, to keep
  10875. // s2 in 31-bits, because we force signed ints.
  10876. // in other case %= will fail.
  10877. n = len > 2000 ? 2000 : len;
  10878. len -= n;
  10879. do {
  10880. s1 = (s1 + buf[pos++]) |0;
  10881. s2 = (s2 + s1) |0;
  10882. } while (--n);
  10883. s1 %= 65521;
  10884. s2 %= 65521;
  10885. }
  10886. return (s1 | (s2 << 16)) |0;
  10887. }
  10888. module.exports = adler32;
  10889. },{}],41:[function(require,module,exports){
  10890. module.exports = {
  10891. /* Allowed flush values; see deflate() and inflate() below for details */
  10892. Z_NO_FLUSH: 0,
  10893. Z_PARTIAL_FLUSH: 1,
  10894. Z_SYNC_FLUSH: 2,
  10895. Z_FULL_FLUSH: 3,
  10896. Z_FINISH: 4,
  10897. Z_BLOCK: 5,
  10898. Z_TREES: 6,
  10899. /* Return codes for the compression/decompression functions. Negative values
  10900. * are errors, positive values are used for special but normal events.
  10901. */
  10902. Z_OK: 0,
  10903. Z_STREAM_END: 1,
  10904. Z_NEED_DICT: 2,
  10905. Z_ERRNO: -1,
  10906. Z_STREAM_ERROR: -2,
  10907. Z_DATA_ERROR: -3,
  10908. //Z_MEM_ERROR: -4,
  10909. Z_BUF_ERROR: -5,
  10910. //Z_VERSION_ERROR: -6,
  10911. /* compression levels */
  10912. Z_NO_COMPRESSION: 0,
  10913. Z_BEST_SPEED: 1,
  10914. Z_BEST_COMPRESSION: 9,
  10915. Z_DEFAULT_COMPRESSION: -1,
  10916. Z_FILTERED: 1,
  10917. Z_HUFFMAN_ONLY: 2,
  10918. Z_RLE: 3,
  10919. Z_FIXED: 4,
  10920. Z_DEFAULT_STRATEGY: 0,
  10921. /* Possible values of the data_type field (though see inflate()) */
  10922. Z_BINARY: 0,
  10923. Z_TEXT: 1,
  10924. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  10925. Z_UNKNOWN: 2,
  10926. /* The deflate compression method */
  10927. Z_DEFLATED: 8
  10928. //Z_NULL: null // Use -1 or null inline, depending on var type
  10929. };
  10930. },{}],42:[function(require,module,exports){
  10931. 'use strict';
  10932. // Note: we can't get significant speed boost here.
  10933. // So write code to minimize size - no pregenerated tables
  10934. // and array tools dependencies.
  10935. // Use ordinary array, since untyped makes no boost here
  10936. function makeTable() {
  10937. var c, table = [];
  10938. for (var n =0; n < 256; n++) {
  10939. c = n;
  10940. for (var k =0; k < 8; k++) {
  10941. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  10942. }
  10943. table[n] = c;
  10944. }
  10945. return table;
  10946. }
  10947. // Create table on load. Just 255 signed longs. Not a problem.
  10948. var crcTable = makeTable();
  10949. function crc32(crc, buf, len, pos) {
  10950. var t = crcTable,
  10951. end = pos + len;
  10952. crc = crc ^ (-1);
  10953. for (var i = pos; i < end; i++) {
  10954. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  10955. }
  10956. return (crc ^ (-1)); // >>> 0;
  10957. }
  10958. module.exports = crc32;
  10959. },{}],43:[function(require,module,exports){
  10960. 'use strict';
  10961. var utils = require('../utils/common');
  10962. var trees = require('./trees');
  10963. var adler32 = require('./adler32');
  10964. var crc32 = require('./crc32');
  10965. var msg = require('./messages');
  10966. /* Public constants ==========================================================*/
  10967. /* ===========================================================================*/
  10968. /* Allowed flush values; see deflate() and inflate() below for details */
  10969. var Z_NO_FLUSH = 0;
  10970. var Z_PARTIAL_FLUSH = 1;
  10971. //var Z_SYNC_FLUSH = 2;
  10972. var Z_FULL_FLUSH = 3;
  10973. var Z_FINISH = 4;
  10974. var Z_BLOCK = 5;
  10975. //var Z_TREES = 6;
  10976. /* Return codes for the compression/decompression functions. Negative values
  10977. * are errors, positive values are used for special but normal events.
  10978. */
  10979. var Z_OK = 0;
  10980. var Z_STREAM_END = 1;
  10981. //var Z_NEED_DICT = 2;
  10982. //var Z_ERRNO = -1;
  10983. var Z_STREAM_ERROR = -2;
  10984. var Z_DATA_ERROR = -3;
  10985. //var Z_MEM_ERROR = -4;
  10986. var Z_BUF_ERROR = -5;
  10987. //var Z_VERSION_ERROR = -6;
  10988. /* compression levels */
  10989. //var Z_NO_COMPRESSION = 0;
  10990. //var Z_BEST_SPEED = 1;
  10991. //var Z_BEST_COMPRESSION = 9;
  10992. var Z_DEFAULT_COMPRESSION = -1;
  10993. var Z_FILTERED = 1;
  10994. var Z_HUFFMAN_ONLY = 2;
  10995. var Z_RLE = 3;
  10996. var Z_FIXED = 4;
  10997. var Z_DEFAULT_STRATEGY = 0;
  10998. /* Possible values of the data_type field (though see inflate()) */
  10999. //var Z_BINARY = 0;
  11000. //var Z_TEXT = 1;
  11001. //var Z_ASCII = 1; // = Z_TEXT
  11002. var Z_UNKNOWN = 2;
  11003. /* The deflate compression method */
  11004. var Z_DEFLATED = 8;
  11005. /*============================================================================*/
  11006. var MAX_MEM_LEVEL = 9;
  11007. /* Maximum value for memLevel in deflateInit2 */
  11008. var MAX_WBITS = 15;
  11009. /* 32K LZ77 window */
  11010. var DEF_MEM_LEVEL = 8;
  11011. var LENGTH_CODES = 29;
  11012. /* number of length codes, not counting the special END_BLOCK code */
  11013. var LITERALS = 256;
  11014. /* number of literal bytes 0..255 */
  11015. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  11016. /* number of Literal or Length codes, including the END_BLOCK code */
  11017. var D_CODES = 30;
  11018. /* number of distance codes */
  11019. var BL_CODES = 19;
  11020. /* number of codes used to transfer the bit lengths */
  11021. var HEAP_SIZE = 2*L_CODES + 1;
  11022. /* maximum heap size */
  11023. var MAX_BITS = 15;
  11024. /* All codes must not exceed MAX_BITS bits */
  11025. var MIN_MATCH = 3;
  11026. var MAX_MATCH = 258;
  11027. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  11028. var PRESET_DICT = 0x20;
  11029. var INIT_STATE = 42;
  11030. var EXTRA_STATE = 69;
  11031. var NAME_STATE = 73;
  11032. var COMMENT_STATE = 91;
  11033. var HCRC_STATE = 103;
  11034. var BUSY_STATE = 113;
  11035. var FINISH_STATE = 666;
  11036. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  11037. var BS_BLOCK_DONE = 2; /* block flush performed */
  11038. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  11039. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  11040. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  11041. function err(strm, errorCode) {
  11042. strm.msg = msg[errorCode];
  11043. return errorCode;
  11044. }
  11045. function rank(f) {
  11046. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  11047. }
  11048. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  11049. /* =========================================================================
  11050. * Flush as much pending output as possible. All deflate() output goes
  11051. * through this function so some applications may wish to modify it
  11052. * to avoid allocating a large strm->output buffer and copying into it.
  11053. * (See also read_buf()).
  11054. */
  11055. function flush_pending(strm) {
  11056. var s = strm.state;
  11057. //_tr_flush_bits(s);
  11058. var len = s.pending;
  11059. if (len > strm.avail_out) {
  11060. len = strm.avail_out;
  11061. }
  11062. if (len === 0) { return; }
  11063. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  11064. strm.next_out += len;
  11065. s.pending_out += len;
  11066. strm.total_out += len;
  11067. strm.avail_out -= len;
  11068. s.pending -= len;
  11069. if (s.pending === 0) {
  11070. s.pending_out = 0;
  11071. }
  11072. }
  11073. function flush_block_only (s, last) {
  11074. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  11075. s.block_start = s.strstart;
  11076. flush_pending(s.strm);
  11077. }
  11078. function put_byte(s, b) {
  11079. s.pending_buf[s.pending++] = b;
  11080. }
  11081. /* =========================================================================
  11082. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  11083. * IN assertion: the stream state is correct and there is enough room in
  11084. * pending_buf.
  11085. */
  11086. function putShortMSB(s, b) {
  11087. // put_byte(s, (Byte)(b >> 8));
  11088. // put_byte(s, (Byte)(b & 0xff));
  11089. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  11090. s.pending_buf[s.pending++] = b & 0xff;
  11091. }
  11092. /* ===========================================================================
  11093. * Read a new buffer from the current input stream, update the adler32
  11094. * and total number of bytes read. All deflate() input goes through
  11095. * this function so some applications may wish to modify it to avoid
  11096. * allocating a large strm->input buffer and copying from it.
  11097. * (See also flush_pending()).
  11098. */
  11099. function read_buf(strm, buf, start, size) {
  11100. var len = strm.avail_in;
  11101. if (len > size) { len = size; }
  11102. if (len === 0) { return 0; }
  11103. strm.avail_in -= len;
  11104. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  11105. if (strm.state.wrap === 1) {
  11106. strm.adler = adler32(strm.adler, buf, len, start);
  11107. }
  11108. else if (strm.state.wrap === 2) {
  11109. strm.adler = crc32(strm.adler, buf, len, start);
  11110. }
  11111. strm.next_in += len;
  11112. strm.total_in += len;
  11113. return len;
  11114. }
  11115. /* ===========================================================================
  11116. * Set match_start to the longest match starting at the given string and
  11117. * return its length. Matches shorter or equal to prev_length are discarded,
  11118. * in which case the result is equal to prev_length and match_start is
  11119. * garbage.
  11120. * IN assertions: cur_match is the head of the hash chain for the current
  11121. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  11122. * OUT assertion: the match length is not greater than s->lookahead.
  11123. */
  11124. function longest_match(s, cur_match) {
  11125. var chain_length = s.max_chain_length; /* max hash chain length */
  11126. var scan = s.strstart; /* current string */
  11127. var match; /* matched string */
  11128. var len; /* length of current match */
  11129. var best_len = s.prev_length; /* best match length so far */
  11130. var nice_match = s.nice_match; /* stop if match long enough */
  11131. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  11132. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  11133. var _win = s.window; // shortcut
  11134. var wmask = s.w_mask;
  11135. var prev = s.prev;
  11136. /* Stop when cur_match becomes <= limit. To simplify the code,
  11137. * we prevent matches with the string of window index 0.
  11138. */
  11139. var strend = s.strstart + MAX_MATCH;
  11140. var scan_end1 = _win[scan + best_len - 1];
  11141. var scan_end = _win[scan + best_len];
  11142. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  11143. * It is easy to get rid of this optimization if necessary.
  11144. */
  11145. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  11146. /* Do not waste too much time if we already have a good match: */
  11147. if (s.prev_length >= s.good_match) {
  11148. chain_length >>= 2;
  11149. }
  11150. /* Do not look for matches beyond the end of the input. This is necessary
  11151. * to make deflate deterministic.
  11152. */
  11153. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  11154. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  11155. do {
  11156. // Assert(cur_match < s->strstart, "no future");
  11157. match = cur_match;
  11158. /* Skip to next match if the match length cannot increase
  11159. * or if the match length is less than 2. Note that the checks below
  11160. * for insufficient lookahead only occur occasionally for performance
  11161. * reasons. Therefore uninitialized memory will be accessed, and
  11162. * conditional jumps will be made that depend on those values.
  11163. * However the length of the match is limited to the lookahead, so
  11164. * the output of deflate is not affected by the uninitialized values.
  11165. */
  11166. if (_win[match + best_len] !== scan_end ||
  11167. _win[match + best_len - 1] !== scan_end1 ||
  11168. _win[match] !== _win[scan] ||
  11169. _win[++match] !== _win[scan + 1]) {
  11170. continue;
  11171. }
  11172. /* The check at best_len-1 can be removed because it will be made
  11173. * again later. (This heuristic is not always a win.)
  11174. * It is not necessary to compare scan[2] and match[2] since they
  11175. * are always equal when the other bytes match, given that
  11176. * the hash keys are equal and that HASH_BITS >= 8.
  11177. */
  11178. scan += 2;
  11179. match++;
  11180. // Assert(*scan == *match, "match[2]?");
  11181. /* We check for insufficient lookahead only every 8th comparison;
  11182. * the 256th check will be made at strstart+258.
  11183. */
  11184. do {
  11185. /*jshint noempty:false*/
  11186. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11187. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11188. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11189. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  11190. scan < strend);
  11191. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  11192. len = MAX_MATCH - (strend - scan);
  11193. scan = strend - MAX_MATCH;
  11194. if (len > best_len) {
  11195. s.match_start = cur_match;
  11196. best_len = len;
  11197. if (len >= nice_match) {
  11198. break;
  11199. }
  11200. scan_end1 = _win[scan + best_len - 1];
  11201. scan_end = _win[scan + best_len];
  11202. }
  11203. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  11204. if (best_len <= s.lookahead) {
  11205. return best_len;
  11206. }
  11207. return s.lookahead;
  11208. }
  11209. /* ===========================================================================
  11210. * Fill the window when the lookahead becomes insufficient.
  11211. * Updates strstart and lookahead.
  11212. *
  11213. * IN assertion: lookahead < MIN_LOOKAHEAD
  11214. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  11215. * At least one byte has been read, or avail_in == 0; reads are
  11216. * performed for at least two bytes (required for the zip translate_eol
  11217. * option -- not supported here).
  11218. */
  11219. function fill_window(s) {
  11220. var _w_size = s.w_size;
  11221. var p, n, m, more, str;
  11222. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  11223. do {
  11224. more = s.window_size - s.lookahead - s.strstart;
  11225. // JS ints have 32 bit, block below not needed
  11226. /* Deal with !@#$% 64K limit: */
  11227. //if (sizeof(int) <= 2) {
  11228. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  11229. // more = wsize;
  11230. //
  11231. // } else if (more == (unsigned)(-1)) {
  11232. // /* Very unlikely, but possible on 16 bit machine if
  11233. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  11234. // */
  11235. // more--;
  11236. // }
  11237. //}
  11238. /* If the window is almost full and there is insufficient lookahead,
  11239. * move the upper half to the lower one to make room in the upper half.
  11240. */
  11241. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  11242. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  11243. s.match_start -= _w_size;
  11244. s.strstart -= _w_size;
  11245. /* we now have strstart >= MAX_DIST */
  11246. s.block_start -= _w_size;
  11247. /* Slide the hash table (could be avoided with 32 bit values
  11248. at the expense of memory usage). We slide even when level == 0
  11249. to keep the hash table consistent if we switch back to level > 0
  11250. later. (Using level 0 permanently is not an optimal usage of
  11251. zlib, so we don't care about this pathological case.)
  11252. */
  11253. n = s.hash_size;
  11254. p = n;
  11255. do {
  11256. m = s.head[--p];
  11257. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  11258. } while (--n);
  11259. n = _w_size;
  11260. p = n;
  11261. do {
  11262. m = s.prev[--p];
  11263. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  11264. /* If n is not on any hash chain, prev[n] is garbage but
  11265. * its value will never be used.
  11266. */
  11267. } while (--n);
  11268. more += _w_size;
  11269. }
  11270. if (s.strm.avail_in === 0) {
  11271. break;
  11272. }
  11273. /* If there was no sliding:
  11274. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  11275. * more == window_size - lookahead - strstart
  11276. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  11277. * => more >= window_size - 2*WSIZE + 2
  11278. * In the BIG_MEM or MMAP case (not yet supported),
  11279. * window_size == input_size + MIN_LOOKAHEAD &&
  11280. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  11281. * Otherwise, window_size == 2*WSIZE so more >= 2.
  11282. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  11283. */
  11284. //Assert(more >= 2, "more < 2");
  11285. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  11286. s.lookahead += n;
  11287. /* Initialize the hash value now that we have some input: */
  11288. if (s.lookahead + s.insert >= MIN_MATCH) {
  11289. str = s.strstart - s.insert;
  11290. s.ins_h = s.window[str];
  11291. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  11292. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  11293. //#if MIN_MATCH != 3
  11294. // Call update_hash() MIN_MATCH-3 more times
  11295. //#endif
  11296. while (s.insert) {
  11297. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  11298. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  11299. s.prev[str & s.w_mask] = s.head[s.ins_h];
  11300. s.head[s.ins_h] = str;
  11301. str++;
  11302. s.insert--;
  11303. if (s.lookahead + s.insert < MIN_MATCH) {
  11304. break;
  11305. }
  11306. }
  11307. }
  11308. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  11309. * but this is not important since only literal bytes will be emitted.
  11310. */
  11311. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  11312. /* If the WIN_INIT bytes after the end of the current data have never been
  11313. * written, then zero those bytes in order to avoid memory check reports of
  11314. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  11315. * the longest match routines. Update the high water mark for the next
  11316. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  11317. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  11318. */
  11319. // if (s.high_water < s.window_size) {
  11320. // var curr = s.strstart + s.lookahead;
  11321. // var init = 0;
  11322. //
  11323. // if (s.high_water < curr) {
  11324. // /* Previous high water mark below current data -- zero WIN_INIT
  11325. // * bytes or up to end of window, whichever is less.
  11326. // */
  11327. // init = s.window_size - curr;
  11328. // if (init > WIN_INIT)
  11329. // init = WIN_INIT;
  11330. // zmemzero(s->window + curr, (unsigned)init);
  11331. // s->high_water = curr + init;
  11332. // }
  11333. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  11334. // /* High water mark at or above current data, but below current data
  11335. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  11336. // * to end of window, whichever is less.
  11337. // */
  11338. // init = (ulg)curr + WIN_INIT - s->high_water;
  11339. // if (init > s->window_size - s->high_water)
  11340. // init = s->window_size - s->high_water;
  11341. // zmemzero(s->window + s->high_water, (unsigned)init);
  11342. // s->high_water += init;
  11343. // }
  11344. // }
  11345. //
  11346. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  11347. // "not enough room for search");
  11348. }
  11349. /* ===========================================================================
  11350. * Copy without compression as much as possible from the input stream, return
  11351. * the current block state.
  11352. * This function does not insert new strings in the dictionary since
  11353. * uncompressible data is probably not useful. This function is used
  11354. * only for the level=0 compression option.
  11355. * NOTE: this function should be optimized to avoid extra copying from
  11356. * window to pending_buf.
  11357. */
  11358. function deflate_stored(s, flush) {
  11359. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  11360. * to pending_buf_size, and each stored block has a 5 byte header:
  11361. */
  11362. var max_block_size = 0xffff;
  11363. if (max_block_size > s.pending_buf_size - 5) {
  11364. max_block_size = s.pending_buf_size - 5;
  11365. }
  11366. /* Copy as much as possible from input to output: */
  11367. for (;;) {
  11368. /* Fill the window as much as possible: */
  11369. if (s.lookahead <= 1) {
  11370. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  11371. // s->block_start >= (long)s->w_size, "slide too late");
  11372. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  11373. // s.block_start >= s.w_size)) {
  11374. // throw new Error("slide too late");
  11375. // }
  11376. fill_window(s);
  11377. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  11378. return BS_NEED_MORE;
  11379. }
  11380. if (s.lookahead === 0) {
  11381. break;
  11382. }
  11383. /* flush the current block */
  11384. }
  11385. //Assert(s->block_start >= 0L, "block gone");
  11386. // if (s.block_start < 0) throw new Error("block gone");
  11387. s.strstart += s.lookahead;
  11388. s.lookahead = 0;
  11389. /* Emit a stored block if pending_buf will be full: */
  11390. var max_start = s.block_start + max_block_size;
  11391. if (s.strstart === 0 || s.strstart >= max_start) {
  11392. /* strstart == 0 is possible when wraparound on 16-bit machine */
  11393. s.lookahead = s.strstart - max_start;
  11394. s.strstart = max_start;
  11395. /*** FLUSH_BLOCK(s, 0); ***/
  11396. flush_block_only(s, false);
  11397. if (s.strm.avail_out === 0) {
  11398. return BS_NEED_MORE;
  11399. }
  11400. /***/
  11401. }
  11402. /* Flush if we may have to slide, otherwise block_start may become
  11403. * negative and the data will be gone:
  11404. */
  11405. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  11406. /*** FLUSH_BLOCK(s, 0); ***/
  11407. flush_block_only(s, false);
  11408. if (s.strm.avail_out === 0) {
  11409. return BS_NEED_MORE;
  11410. }
  11411. /***/
  11412. }
  11413. }
  11414. s.insert = 0;
  11415. if (flush === Z_FINISH) {
  11416. /*** FLUSH_BLOCK(s, 1); ***/
  11417. flush_block_only(s, true);
  11418. if (s.strm.avail_out === 0) {
  11419. return BS_FINISH_STARTED;
  11420. }
  11421. /***/
  11422. return BS_FINISH_DONE;
  11423. }
  11424. if (s.strstart > s.block_start) {
  11425. /*** FLUSH_BLOCK(s, 0); ***/
  11426. flush_block_only(s, false);
  11427. if (s.strm.avail_out === 0) {
  11428. return BS_NEED_MORE;
  11429. }
  11430. /***/
  11431. }
  11432. return BS_NEED_MORE;
  11433. }
  11434. /* ===========================================================================
  11435. * Compress as much as possible from the input stream, return the current
  11436. * block state.
  11437. * This function does not perform lazy evaluation of matches and inserts
  11438. * new strings in the dictionary only for unmatched strings or for short
  11439. * matches. It is used only for the fast compression options.
  11440. */
  11441. function deflate_fast(s, flush) {
  11442. var hash_head; /* head of the hash chain */
  11443. var bflush; /* set if current block must be flushed */
  11444. for (;;) {
  11445. /* Make sure that we always have enough lookahead, except
  11446. * at the end of the input file. We need MAX_MATCH bytes
  11447. * for the next match, plus MIN_MATCH bytes to insert the
  11448. * string following the next match.
  11449. */
  11450. if (s.lookahead < MIN_LOOKAHEAD) {
  11451. fill_window(s);
  11452. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11453. return BS_NEED_MORE;
  11454. }
  11455. if (s.lookahead === 0) {
  11456. break; /* flush the current block */
  11457. }
  11458. }
  11459. /* Insert the string window[strstart .. strstart+2] in the
  11460. * dictionary, and set hash_head to the head of the hash chain:
  11461. */
  11462. hash_head = 0/*NIL*/;
  11463. if (s.lookahead >= MIN_MATCH) {
  11464. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11465. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11466. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11467. s.head[s.ins_h] = s.strstart;
  11468. /***/
  11469. }
  11470. /* Find the longest match, discarding those <= prev_length.
  11471. * At this point we have always match_length < MIN_MATCH
  11472. */
  11473. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  11474. /* To simplify the code, we prevent matches with the string
  11475. * of window index 0 (in particular we have to avoid a match
  11476. * of the string with itself at the start of the input file).
  11477. */
  11478. s.match_length = longest_match(s, hash_head);
  11479. /* longest_match() sets match_start */
  11480. }
  11481. if (s.match_length >= MIN_MATCH) {
  11482. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  11483. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  11484. s.match_length - MIN_MATCH, bflush); ***/
  11485. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  11486. s.lookahead -= s.match_length;
  11487. /* Insert new strings in the hash table only if the match length
  11488. * is not too large. This saves time but degrades compression.
  11489. */
  11490. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  11491. s.match_length--; /* string at strstart already in table */
  11492. do {
  11493. s.strstart++;
  11494. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11495. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11496. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11497. s.head[s.ins_h] = s.strstart;
  11498. /***/
  11499. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  11500. * always MIN_MATCH bytes ahead.
  11501. */
  11502. } while (--s.match_length !== 0);
  11503. s.strstart++;
  11504. } else
  11505. {
  11506. s.strstart += s.match_length;
  11507. s.match_length = 0;
  11508. s.ins_h = s.window[s.strstart];
  11509. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  11510. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  11511. //#if MIN_MATCH != 3
  11512. // Call UPDATE_HASH() MIN_MATCH-3 more times
  11513. //#endif
  11514. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  11515. * matter since it will be recomputed at next deflate call.
  11516. */
  11517. }
  11518. } else {
  11519. /* No match, output a literal byte */
  11520. //Tracevv((stderr,"%c", s.window[s.strstart]));
  11521. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11522. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11523. s.lookahead--;
  11524. s.strstart++;
  11525. }
  11526. if (bflush) {
  11527. /*** FLUSH_BLOCK(s, 0); ***/
  11528. flush_block_only(s, false);
  11529. if (s.strm.avail_out === 0) {
  11530. return BS_NEED_MORE;
  11531. }
  11532. /***/
  11533. }
  11534. }
  11535. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  11536. if (flush === Z_FINISH) {
  11537. /*** FLUSH_BLOCK(s, 1); ***/
  11538. flush_block_only(s, true);
  11539. if (s.strm.avail_out === 0) {
  11540. return BS_FINISH_STARTED;
  11541. }
  11542. /***/
  11543. return BS_FINISH_DONE;
  11544. }
  11545. if (s.last_lit) {
  11546. /*** FLUSH_BLOCK(s, 0); ***/
  11547. flush_block_only(s, false);
  11548. if (s.strm.avail_out === 0) {
  11549. return BS_NEED_MORE;
  11550. }
  11551. /***/
  11552. }
  11553. return BS_BLOCK_DONE;
  11554. }
  11555. /* ===========================================================================
  11556. * Same as above, but achieves better compression. We use a lazy
  11557. * evaluation for matches: a match is finally adopted only if there is
  11558. * no better match at the next window position.
  11559. */
  11560. function deflate_slow(s, flush) {
  11561. var hash_head; /* head of hash chain */
  11562. var bflush; /* set if current block must be flushed */
  11563. var max_insert;
  11564. /* Process the input block. */
  11565. for (;;) {
  11566. /* Make sure that we always have enough lookahead, except
  11567. * at the end of the input file. We need MAX_MATCH bytes
  11568. * for the next match, plus MIN_MATCH bytes to insert the
  11569. * string following the next match.
  11570. */
  11571. if (s.lookahead < MIN_LOOKAHEAD) {
  11572. fill_window(s);
  11573. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11574. return BS_NEED_MORE;
  11575. }
  11576. if (s.lookahead === 0) { break; } /* flush the current block */
  11577. }
  11578. /* Insert the string window[strstart .. strstart+2] in the
  11579. * dictionary, and set hash_head to the head of the hash chain:
  11580. */
  11581. hash_head = 0/*NIL*/;
  11582. if (s.lookahead >= MIN_MATCH) {
  11583. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11584. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11585. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11586. s.head[s.ins_h] = s.strstart;
  11587. /***/
  11588. }
  11589. /* Find the longest match, discarding those <= prev_length.
  11590. */
  11591. s.prev_length = s.match_length;
  11592. s.prev_match = s.match_start;
  11593. s.match_length = MIN_MATCH-1;
  11594. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  11595. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  11596. /* To simplify the code, we prevent matches with the string
  11597. * of window index 0 (in particular we have to avoid a match
  11598. * of the string with itself at the start of the input file).
  11599. */
  11600. s.match_length = longest_match(s, hash_head);
  11601. /* longest_match() sets match_start */
  11602. if (s.match_length <= 5 &&
  11603. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  11604. /* If prev_match is also MIN_MATCH, match_start is garbage
  11605. * but we will ignore the current match anyway.
  11606. */
  11607. s.match_length = MIN_MATCH-1;
  11608. }
  11609. }
  11610. /* If there was a match at the previous step and the current
  11611. * match is not better, output the previous match:
  11612. */
  11613. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  11614. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  11615. /* Do not insert strings in hash table beyond this. */
  11616. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  11617. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  11618. s.prev_length - MIN_MATCH, bflush);***/
  11619. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  11620. /* Insert in hash table all strings up to the end of the match.
  11621. * strstart-1 and strstart are already inserted. If there is not
  11622. * enough lookahead, the last two strings are not inserted in
  11623. * the hash table.
  11624. */
  11625. s.lookahead -= s.prev_length-1;
  11626. s.prev_length -= 2;
  11627. do {
  11628. if (++s.strstart <= max_insert) {
  11629. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11630. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11631. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11632. s.head[s.ins_h] = s.strstart;
  11633. /***/
  11634. }
  11635. } while (--s.prev_length !== 0);
  11636. s.match_available = 0;
  11637. s.match_length = MIN_MATCH-1;
  11638. s.strstart++;
  11639. if (bflush) {
  11640. /*** FLUSH_BLOCK(s, 0); ***/
  11641. flush_block_only(s, false);
  11642. if (s.strm.avail_out === 0) {
  11643. return BS_NEED_MORE;
  11644. }
  11645. /***/
  11646. }
  11647. } else if (s.match_available) {
  11648. /* If there was no match at the previous position, output a
  11649. * single literal. If there was a match but the current match
  11650. * is longer, truncate the previous match to a single literal.
  11651. */
  11652. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  11653. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  11654. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  11655. if (bflush) {
  11656. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  11657. flush_block_only(s, false);
  11658. /***/
  11659. }
  11660. s.strstart++;
  11661. s.lookahead--;
  11662. if (s.strm.avail_out === 0) {
  11663. return BS_NEED_MORE;
  11664. }
  11665. } else {
  11666. /* There is no previous match to compare with, wait for
  11667. * the next step to decide.
  11668. */
  11669. s.match_available = 1;
  11670. s.strstart++;
  11671. s.lookahead--;
  11672. }
  11673. }
  11674. //Assert (flush != Z_NO_FLUSH, "no flush?");
  11675. if (s.match_available) {
  11676. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  11677. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  11678. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  11679. s.match_available = 0;
  11680. }
  11681. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  11682. if (flush === Z_FINISH) {
  11683. /*** FLUSH_BLOCK(s, 1); ***/
  11684. flush_block_only(s, true);
  11685. if (s.strm.avail_out === 0) {
  11686. return BS_FINISH_STARTED;
  11687. }
  11688. /***/
  11689. return BS_FINISH_DONE;
  11690. }
  11691. if (s.last_lit) {
  11692. /*** FLUSH_BLOCK(s, 0); ***/
  11693. flush_block_only(s, false);
  11694. if (s.strm.avail_out === 0) {
  11695. return BS_NEED_MORE;
  11696. }
  11697. /***/
  11698. }
  11699. return BS_BLOCK_DONE;
  11700. }
  11701. /* ===========================================================================
  11702. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  11703. * one. Do not maintain a hash table. (It will be regenerated if this run of
  11704. * deflate switches away from Z_RLE.)
  11705. */
  11706. function deflate_rle(s, flush) {
  11707. var bflush; /* set if current block must be flushed */
  11708. var prev; /* byte at distance one to match */
  11709. var scan, strend; /* scan goes up to strend for length of run */
  11710. var _win = s.window;
  11711. for (;;) {
  11712. /* Make sure that we always have enough lookahead, except
  11713. * at the end of the input file. We need MAX_MATCH bytes
  11714. * for the longest run, plus one for the unrolled loop.
  11715. */
  11716. if (s.lookahead <= MAX_MATCH) {
  11717. fill_window(s);
  11718. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  11719. return BS_NEED_MORE;
  11720. }
  11721. if (s.lookahead === 0) { break; } /* flush the current block */
  11722. }
  11723. /* See how many times the previous byte repeats */
  11724. s.match_length = 0;
  11725. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  11726. scan = s.strstart - 1;
  11727. prev = _win[scan];
  11728. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  11729. strend = s.strstart + MAX_MATCH;
  11730. do {
  11731. /*jshint noempty:false*/
  11732. } while (prev === _win[++scan] && prev === _win[++scan] &&
  11733. prev === _win[++scan] && prev === _win[++scan] &&
  11734. prev === _win[++scan] && prev === _win[++scan] &&
  11735. prev === _win[++scan] && prev === _win[++scan] &&
  11736. scan < strend);
  11737. s.match_length = MAX_MATCH - (strend - scan);
  11738. if (s.match_length > s.lookahead) {
  11739. s.match_length = s.lookahead;
  11740. }
  11741. }
  11742. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  11743. }
  11744. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  11745. if (s.match_length >= MIN_MATCH) {
  11746. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  11747. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  11748. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  11749. s.lookahead -= s.match_length;
  11750. s.strstart += s.match_length;
  11751. s.match_length = 0;
  11752. } else {
  11753. /* No match, output a literal byte */
  11754. //Tracevv((stderr,"%c", s->window[s->strstart]));
  11755. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11756. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11757. s.lookahead--;
  11758. s.strstart++;
  11759. }
  11760. if (bflush) {
  11761. /*** FLUSH_BLOCK(s, 0); ***/
  11762. flush_block_only(s, false);
  11763. if (s.strm.avail_out === 0) {
  11764. return BS_NEED_MORE;
  11765. }
  11766. /***/
  11767. }
  11768. }
  11769. s.insert = 0;
  11770. if (flush === Z_FINISH) {
  11771. /*** FLUSH_BLOCK(s, 1); ***/
  11772. flush_block_only(s, true);
  11773. if (s.strm.avail_out === 0) {
  11774. return BS_FINISH_STARTED;
  11775. }
  11776. /***/
  11777. return BS_FINISH_DONE;
  11778. }
  11779. if (s.last_lit) {
  11780. /*** FLUSH_BLOCK(s, 0); ***/
  11781. flush_block_only(s, false);
  11782. if (s.strm.avail_out === 0) {
  11783. return BS_NEED_MORE;
  11784. }
  11785. /***/
  11786. }
  11787. return BS_BLOCK_DONE;
  11788. }
  11789. /* ===========================================================================
  11790. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  11791. * (It will be regenerated if this run of deflate switches away from Huffman.)
  11792. */
  11793. function deflate_huff(s, flush) {
  11794. var bflush; /* set if current block must be flushed */
  11795. for (;;) {
  11796. /* Make sure that we have a literal to write. */
  11797. if (s.lookahead === 0) {
  11798. fill_window(s);
  11799. if (s.lookahead === 0) {
  11800. if (flush === Z_NO_FLUSH) {
  11801. return BS_NEED_MORE;
  11802. }
  11803. break; /* flush the current block */
  11804. }
  11805. }
  11806. /* Output a literal byte */
  11807. s.match_length = 0;
  11808. //Tracevv((stderr,"%c", s->window[s->strstart]));
  11809. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11810. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11811. s.lookahead--;
  11812. s.strstart++;
  11813. if (bflush) {
  11814. /*** FLUSH_BLOCK(s, 0); ***/
  11815. flush_block_only(s, false);
  11816. if (s.strm.avail_out === 0) {
  11817. return BS_NEED_MORE;
  11818. }
  11819. /***/
  11820. }
  11821. }
  11822. s.insert = 0;
  11823. if (flush === Z_FINISH) {
  11824. /*** FLUSH_BLOCK(s, 1); ***/
  11825. flush_block_only(s, true);
  11826. if (s.strm.avail_out === 0) {
  11827. return BS_FINISH_STARTED;
  11828. }
  11829. /***/
  11830. return BS_FINISH_DONE;
  11831. }
  11832. if (s.last_lit) {
  11833. /*** FLUSH_BLOCK(s, 0); ***/
  11834. flush_block_only(s, false);
  11835. if (s.strm.avail_out === 0) {
  11836. return BS_NEED_MORE;
  11837. }
  11838. /***/
  11839. }
  11840. return BS_BLOCK_DONE;
  11841. }
  11842. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  11843. * the desired pack level (0..9). The values given below have been tuned to
  11844. * exclude worst case performance for pathological files. Better values may be
  11845. * found for specific files.
  11846. */
  11847. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  11848. this.good_length = good_length;
  11849. this.max_lazy = max_lazy;
  11850. this.nice_length = nice_length;
  11851. this.max_chain = max_chain;
  11852. this.func = func;
  11853. };
  11854. var configuration_table;
  11855. configuration_table = [
  11856. /* good lazy nice chain */
  11857. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  11858. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  11859. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  11860. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  11861. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  11862. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  11863. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  11864. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  11865. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  11866. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  11867. ];
  11868. /* ===========================================================================
  11869. * Initialize the "longest match" routines for a new zlib stream
  11870. */
  11871. function lm_init(s) {
  11872. s.window_size = 2 * s.w_size;
  11873. /*** CLEAR_HASH(s); ***/
  11874. zero(s.head); // Fill with NIL (= 0);
  11875. /* Set the default configuration parameters:
  11876. */
  11877. s.max_lazy_match = configuration_table[s.level].max_lazy;
  11878. s.good_match = configuration_table[s.level].good_length;
  11879. s.nice_match = configuration_table[s.level].nice_length;
  11880. s.max_chain_length = configuration_table[s.level].max_chain;
  11881. s.strstart = 0;
  11882. s.block_start = 0;
  11883. s.lookahead = 0;
  11884. s.insert = 0;
  11885. s.match_length = s.prev_length = MIN_MATCH - 1;
  11886. s.match_available = 0;
  11887. s.ins_h = 0;
  11888. }
  11889. function DeflateState() {
  11890. this.strm = null; /* pointer back to this zlib stream */
  11891. this.status = 0; /* as the name implies */
  11892. this.pending_buf = null; /* output still pending */
  11893. this.pending_buf_size = 0; /* size of pending_buf */
  11894. this.pending_out = 0; /* next pending byte to output to the stream */
  11895. this.pending = 0; /* nb of bytes in the pending buffer */
  11896. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  11897. this.gzhead = null; /* gzip header information to write */
  11898. this.gzindex = 0; /* where in extra, name, or comment */
  11899. this.method = Z_DEFLATED; /* can only be DEFLATED */
  11900. this.last_flush = -1; /* value of flush param for previous deflate call */
  11901. this.w_size = 0; /* LZ77 window size (32K by default) */
  11902. this.w_bits = 0; /* log2(w_size) (8..16) */
  11903. this.w_mask = 0; /* w_size - 1 */
  11904. this.window = null;
  11905. /* Sliding window. Input bytes are read into the second half of the window,
  11906. * and move to the first half later to keep a dictionary of at least wSize
  11907. * bytes. With this organization, matches are limited to a distance of
  11908. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  11909. * performed with a length multiple of the block size.
  11910. */
  11911. this.window_size = 0;
  11912. /* Actual size of window: 2*wSize, except when the user input buffer
  11913. * is directly used as sliding window.
  11914. */
  11915. this.prev = null;
  11916. /* Link to older string with same hash index. To limit the size of this
  11917. * array to 64K, this link is maintained only for the last 32K strings.
  11918. * An index in this array is thus a window index modulo 32K.
  11919. */
  11920. this.head = null; /* Heads of the hash chains or NIL. */
  11921. this.ins_h = 0; /* hash index of string to be inserted */
  11922. this.hash_size = 0; /* number of elements in hash table */
  11923. this.hash_bits = 0; /* log2(hash_size) */
  11924. this.hash_mask = 0; /* hash_size-1 */
  11925. this.hash_shift = 0;
  11926. /* Number of bits by which ins_h must be shifted at each input
  11927. * step. It must be such that after MIN_MATCH steps, the oldest
  11928. * byte no longer takes part in the hash key, that is:
  11929. * hash_shift * MIN_MATCH >= hash_bits
  11930. */
  11931. this.block_start = 0;
  11932. /* Window position at the beginning of the current output block. Gets
  11933. * negative when the window is moved backwards.
  11934. */
  11935. this.match_length = 0; /* length of best match */
  11936. this.prev_match = 0; /* previous match */
  11937. this.match_available = 0; /* set if previous match exists */
  11938. this.strstart = 0; /* start of string to insert */
  11939. this.match_start = 0; /* start of matching string */
  11940. this.lookahead = 0; /* number of valid bytes ahead in window */
  11941. this.prev_length = 0;
  11942. /* Length of the best match at previous step. Matches not greater than this
  11943. * are discarded. This is used in the lazy match evaluation.
  11944. */
  11945. this.max_chain_length = 0;
  11946. /* To speed up deflation, hash chains are never searched beyond this
  11947. * length. A higher limit improves compression ratio but degrades the
  11948. * speed.
  11949. */
  11950. this.max_lazy_match = 0;
  11951. /* Attempt to find a better match only when the current match is strictly
  11952. * smaller than this value. This mechanism is used only for compression
  11953. * levels >= 4.
  11954. */
  11955. // That's alias to max_lazy_match, don't use directly
  11956. //this.max_insert_length = 0;
  11957. /* Insert new strings in the hash table only if the match length is not
  11958. * greater than this length. This saves time but degrades compression.
  11959. * max_insert_length is used only for compression levels <= 3.
  11960. */
  11961. this.level = 0; /* compression level (1..9) */
  11962. this.strategy = 0; /* favor or force Huffman coding*/
  11963. this.good_match = 0;
  11964. /* Use a faster search when the previous match is longer than this */
  11965. this.nice_match = 0; /* Stop searching when current match exceeds this */
  11966. /* used by trees.c: */
  11967. /* Didn't use ct_data typedef below to suppress compiler warning */
  11968. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  11969. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  11970. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  11971. // Use flat array of DOUBLE size, with interleaved fata,
  11972. // because JS does not support effective
  11973. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  11974. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  11975. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  11976. zero(this.dyn_ltree);
  11977. zero(this.dyn_dtree);
  11978. zero(this.bl_tree);
  11979. this.l_desc = null; /* desc. for literal tree */
  11980. this.d_desc = null; /* desc. for distance tree */
  11981. this.bl_desc = null; /* desc. for bit length tree */
  11982. //ush bl_count[MAX_BITS+1];
  11983. this.bl_count = new utils.Buf16(MAX_BITS+1);
  11984. /* number of codes at each bit length for an optimal tree */
  11985. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  11986. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  11987. zero(this.heap);
  11988. this.heap_len = 0; /* number of elements in the heap */
  11989. this.heap_max = 0; /* element of largest frequency */
  11990. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  11991. * The same heap array is used to build all trees.
  11992. */
  11993. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  11994. zero(this.depth);
  11995. /* Depth of each subtree used as tie breaker for trees of equal frequency
  11996. */
  11997. this.l_buf = 0; /* buffer index for literals or lengths */
  11998. this.lit_bufsize = 0;
  11999. /* Size of match buffer for literals/lengths. There are 4 reasons for
  12000. * limiting lit_bufsize to 64K:
  12001. * - frequencies can be kept in 16 bit counters
  12002. * - if compression is not successful for the first block, all input
  12003. * data is still in the window so we can still emit a stored block even
  12004. * when input comes from standard input. (This can also be done for
  12005. * all blocks if lit_bufsize is not greater than 32K.)
  12006. * - if compression is not successful for a file smaller than 64K, we can
  12007. * even emit a stored file instead of a stored block (saving 5 bytes).
  12008. * This is applicable only for zip (not gzip or zlib).
  12009. * - creating new Huffman trees less frequently may not provide fast
  12010. * adaptation to changes in the input data statistics. (Take for
  12011. * example a binary file with poorly compressible code followed by
  12012. * a highly compressible string table.) Smaller buffer sizes give
  12013. * fast adaptation but have of course the overhead of transmitting
  12014. * trees more frequently.
  12015. * - I can't count above 4
  12016. */
  12017. this.last_lit = 0; /* running index in l_buf */
  12018. this.d_buf = 0;
  12019. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  12020. * the same number of elements. To use different lengths, an extra flag
  12021. * array would be necessary.
  12022. */
  12023. this.opt_len = 0; /* bit length of current block with optimal trees */
  12024. this.static_len = 0; /* bit length of current block with static trees */
  12025. this.matches = 0; /* number of string matches in current block */
  12026. this.insert = 0; /* bytes at end of window left to insert */
  12027. this.bi_buf = 0;
  12028. /* Output buffer. bits are inserted starting at the bottom (least
  12029. * significant bits).
  12030. */
  12031. this.bi_valid = 0;
  12032. /* Number of valid bits in bi_buf. All bits above the last valid bit
  12033. * are always zero.
  12034. */
  12035. // Used for window memory init. We safely ignore it for JS. That makes
  12036. // sense only for pointers and memory check tools.
  12037. //this.high_water = 0;
  12038. /* High water mark offset in window for initialized bytes -- bytes above
  12039. * this are set to zero in order to avoid memory check warnings when
  12040. * longest match routines access bytes past the input. This is then
  12041. * updated to the new high water mark.
  12042. */
  12043. }
  12044. function deflateResetKeep(strm) {
  12045. var s;
  12046. if (!strm || !strm.state) {
  12047. return err(strm, Z_STREAM_ERROR);
  12048. }
  12049. strm.total_in = strm.total_out = 0;
  12050. strm.data_type = Z_UNKNOWN;
  12051. s = strm.state;
  12052. s.pending = 0;
  12053. s.pending_out = 0;
  12054. if (s.wrap < 0) {
  12055. s.wrap = -s.wrap;
  12056. /* was made negative by deflate(..., Z_FINISH); */
  12057. }
  12058. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  12059. strm.adler = (s.wrap === 2) ?
  12060. 0 // crc32(0, Z_NULL, 0)
  12061. :
  12062. 1; // adler32(0, Z_NULL, 0)
  12063. s.last_flush = Z_NO_FLUSH;
  12064. trees._tr_init(s);
  12065. return Z_OK;
  12066. }
  12067. function deflateReset(strm) {
  12068. var ret = deflateResetKeep(strm);
  12069. if (ret === Z_OK) {
  12070. lm_init(strm.state);
  12071. }
  12072. return ret;
  12073. }
  12074. function deflateSetHeader(strm, head) {
  12075. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12076. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  12077. strm.state.gzhead = head;
  12078. return Z_OK;
  12079. }
  12080. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  12081. if (!strm) { // === Z_NULL
  12082. return Z_STREAM_ERROR;
  12083. }
  12084. var wrap = 1;
  12085. if (level === Z_DEFAULT_COMPRESSION) {
  12086. level = 6;
  12087. }
  12088. if (windowBits < 0) { /* suppress zlib wrapper */
  12089. wrap = 0;
  12090. windowBits = -windowBits;
  12091. }
  12092. else if (windowBits > 15) {
  12093. wrap = 2; /* write gzip wrapper instead */
  12094. windowBits -= 16;
  12095. }
  12096. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  12097. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  12098. strategy < 0 || strategy > Z_FIXED) {
  12099. return err(strm, Z_STREAM_ERROR);
  12100. }
  12101. if (windowBits === 8) {
  12102. windowBits = 9;
  12103. }
  12104. /* until 256-byte window bug fixed */
  12105. var s = new DeflateState();
  12106. strm.state = s;
  12107. s.strm = strm;
  12108. s.wrap = wrap;
  12109. s.gzhead = null;
  12110. s.w_bits = windowBits;
  12111. s.w_size = 1 << s.w_bits;
  12112. s.w_mask = s.w_size - 1;
  12113. s.hash_bits = memLevel + 7;
  12114. s.hash_size = 1 << s.hash_bits;
  12115. s.hash_mask = s.hash_size - 1;
  12116. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  12117. s.window = new utils.Buf8(s.w_size * 2);
  12118. s.head = new utils.Buf16(s.hash_size);
  12119. s.prev = new utils.Buf16(s.w_size);
  12120. // Don't need mem init magic for JS.
  12121. //s.high_water = 0; /* nothing written to s->window yet */
  12122. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  12123. s.pending_buf_size = s.lit_bufsize * 4;
  12124. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  12125. s.d_buf = s.lit_bufsize >> 1;
  12126. s.l_buf = (1 + 2) * s.lit_bufsize;
  12127. s.level = level;
  12128. s.strategy = strategy;
  12129. s.method = method;
  12130. return deflateReset(strm);
  12131. }
  12132. function deflateInit(strm, level) {
  12133. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  12134. }
  12135. function deflate(strm, flush) {
  12136. var old_flush, s;
  12137. var beg, val; // for gzip header write only
  12138. if (!strm || !strm.state ||
  12139. flush > Z_BLOCK || flush < 0) {
  12140. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  12141. }
  12142. s = strm.state;
  12143. if (!strm.output ||
  12144. (!strm.input && strm.avail_in !== 0) ||
  12145. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  12146. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  12147. }
  12148. s.strm = strm; /* just in case */
  12149. old_flush = s.last_flush;
  12150. s.last_flush = flush;
  12151. /* Write the header */
  12152. if (s.status === INIT_STATE) {
  12153. if (s.wrap === 2) { // GZIP header
  12154. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  12155. put_byte(s, 31);
  12156. put_byte(s, 139);
  12157. put_byte(s, 8);
  12158. if (!s.gzhead) { // s->gzhead == Z_NULL
  12159. put_byte(s, 0);
  12160. put_byte(s, 0);
  12161. put_byte(s, 0);
  12162. put_byte(s, 0);
  12163. put_byte(s, 0);
  12164. put_byte(s, s.level === 9 ? 2 :
  12165. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  12166. 4 : 0));
  12167. put_byte(s, OS_CODE);
  12168. s.status = BUSY_STATE;
  12169. }
  12170. else {
  12171. put_byte(s, (s.gzhead.text ? 1 : 0) +
  12172. (s.gzhead.hcrc ? 2 : 0) +
  12173. (!s.gzhead.extra ? 0 : 4) +
  12174. (!s.gzhead.name ? 0 : 8) +
  12175. (!s.gzhead.comment ? 0 : 16)
  12176. );
  12177. put_byte(s, s.gzhead.time & 0xff);
  12178. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  12179. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  12180. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  12181. put_byte(s, s.level === 9 ? 2 :
  12182. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  12183. 4 : 0));
  12184. put_byte(s, s.gzhead.os & 0xff);
  12185. if (s.gzhead.extra && s.gzhead.extra.length) {
  12186. put_byte(s, s.gzhead.extra.length & 0xff);
  12187. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  12188. }
  12189. if (s.gzhead.hcrc) {
  12190. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  12191. }
  12192. s.gzindex = 0;
  12193. s.status = EXTRA_STATE;
  12194. }
  12195. }
  12196. else // DEFLATE header
  12197. {
  12198. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  12199. var level_flags = -1;
  12200. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  12201. level_flags = 0;
  12202. } else if (s.level < 6) {
  12203. level_flags = 1;
  12204. } else if (s.level === 6) {
  12205. level_flags = 2;
  12206. } else {
  12207. level_flags = 3;
  12208. }
  12209. header |= (level_flags << 6);
  12210. if (s.strstart !== 0) { header |= PRESET_DICT; }
  12211. header += 31 - (header % 31);
  12212. s.status = BUSY_STATE;
  12213. putShortMSB(s, header);
  12214. /* Save the adler32 of the preset dictionary: */
  12215. if (s.strstart !== 0) {
  12216. putShortMSB(s, strm.adler >>> 16);
  12217. putShortMSB(s, strm.adler & 0xffff);
  12218. }
  12219. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  12220. }
  12221. }
  12222. //#ifdef GZIP
  12223. if (s.status === EXTRA_STATE) {
  12224. if (s.gzhead.extra/* != Z_NULL*/) {
  12225. beg = s.pending; /* start of bytes to update crc */
  12226. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  12227. if (s.pending === s.pending_buf_size) {
  12228. if (s.gzhead.hcrc && s.pending > beg) {
  12229. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12230. }
  12231. flush_pending(strm);
  12232. beg = s.pending;
  12233. if (s.pending === s.pending_buf_size) {
  12234. break;
  12235. }
  12236. }
  12237. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  12238. s.gzindex++;
  12239. }
  12240. if (s.gzhead.hcrc && s.pending > beg) {
  12241. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12242. }
  12243. if (s.gzindex === s.gzhead.extra.length) {
  12244. s.gzindex = 0;
  12245. s.status = NAME_STATE;
  12246. }
  12247. }
  12248. else {
  12249. s.status = NAME_STATE;
  12250. }
  12251. }
  12252. if (s.status === NAME_STATE) {
  12253. if (s.gzhead.name/* != Z_NULL*/) {
  12254. beg = s.pending; /* start of bytes to update crc */
  12255. //int val;
  12256. do {
  12257. if (s.pending === s.pending_buf_size) {
  12258. if (s.gzhead.hcrc && s.pending > beg) {
  12259. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12260. }
  12261. flush_pending(strm);
  12262. beg = s.pending;
  12263. if (s.pending === s.pending_buf_size) {
  12264. val = 1;
  12265. break;
  12266. }
  12267. }
  12268. // JS specific: little magic to add zero terminator to end of string
  12269. if (s.gzindex < s.gzhead.name.length) {
  12270. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  12271. } else {
  12272. val = 0;
  12273. }
  12274. put_byte(s, val);
  12275. } while (val !== 0);
  12276. if (s.gzhead.hcrc && s.pending > beg) {
  12277. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12278. }
  12279. if (val === 0) {
  12280. s.gzindex = 0;
  12281. s.status = COMMENT_STATE;
  12282. }
  12283. }
  12284. else {
  12285. s.status = COMMENT_STATE;
  12286. }
  12287. }
  12288. if (s.status === COMMENT_STATE) {
  12289. if (s.gzhead.comment/* != Z_NULL*/) {
  12290. beg = s.pending; /* start of bytes to update crc */
  12291. //int val;
  12292. do {
  12293. if (s.pending === s.pending_buf_size) {
  12294. if (s.gzhead.hcrc && s.pending > beg) {
  12295. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12296. }
  12297. flush_pending(strm);
  12298. beg = s.pending;
  12299. if (s.pending === s.pending_buf_size) {
  12300. val = 1;
  12301. break;
  12302. }
  12303. }
  12304. // JS specific: little magic to add zero terminator to end of string
  12305. if (s.gzindex < s.gzhead.comment.length) {
  12306. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  12307. } else {
  12308. val = 0;
  12309. }
  12310. put_byte(s, val);
  12311. } while (val !== 0);
  12312. if (s.gzhead.hcrc && s.pending > beg) {
  12313. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  12314. }
  12315. if (val === 0) {
  12316. s.status = HCRC_STATE;
  12317. }
  12318. }
  12319. else {
  12320. s.status = HCRC_STATE;
  12321. }
  12322. }
  12323. if (s.status === HCRC_STATE) {
  12324. if (s.gzhead.hcrc) {
  12325. if (s.pending + 2 > s.pending_buf_size) {
  12326. flush_pending(strm);
  12327. }
  12328. if (s.pending + 2 <= s.pending_buf_size) {
  12329. put_byte(s, strm.adler & 0xff);
  12330. put_byte(s, (strm.adler >> 8) & 0xff);
  12331. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  12332. s.status = BUSY_STATE;
  12333. }
  12334. }
  12335. else {
  12336. s.status = BUSY_STATE;
  12337. }
  12338. }
  12339. //#endif
  12340. /* Flush as much pending output as possible */
  12341. if (s.pending !== 0) {
  12342. flush_pending(strm);
  12343. if (strm.avail_out === 0) {
  12344. /* Since avail_out is 0, deflate will be called again with
  12345. * more output space, but possibly with both pending and
  12346. * avail_in equal to zero. There won't be anything to do,
  12347. * but this is not an error situation so make sure we
  12348. * return OK instead of BUF_ERROR at next call of deflate:
  12349. */
  12350. s.last_flush = -1;
  12351. return Z_OK;
  12352. }
  12353. /* Make sure there is something to do and avoid duplicate consecutive
  12354. * flushes. For repeated and useless calls with Z_FINISH, we keep
  12355. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  12356. */
  12357. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  12358. flush !== Z_FINISH) {
  12359. return err(strm, Z_BUF_ERROR);
  12360. }
  12361. /* User must not provide more input after the first FINISH: */
  12362. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  12363. return err(strm, Z_BUF_ERROR);
  12364. }
  12365. /* Start a new block or continue the current one.
  12366. */
  12367. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  12368. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  12369. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  12370. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  12371. configuration_table[s.level].func(s, flush));
  12372. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  12373. s.status = FINISH_STATE;
  12374. }
  12375. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  12376. if (strm.avail_out === 0) {
  12377. s.last_flush = -1;
  12378. /* avoid BUF_ERROR next call, see above */
  12379. }
  12380. return Z_OK;
  12381. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  12382. * of deflate should use the same flush parameter to make sure
  12383. * that the flush is complete. So we don't have to output an
  12384. * empty block here, this will be done at next call. This also
  12385. * ensures that for a very small output buffer, we emit at most
  12386. * one empty block.
  12387. */
  12388. }
  12389. if (bstate === BS_BLOCK_DONE) {
  12390. if (flush === Z_PARTIAL_FLUSH) {
  12391. trees._tr_align(s);
  12392. }
  12393. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  12394. trees._tr_stored_block(s, 0, 0, false);
  12395. /* For a full flush, this empty block will be recognized
  12396. * as a special marker by inflate_sync().
  12397. */
  12398. if (flush === Z_FULL_FLUSH) {
  12399. /*** CLEAR_HASH(s); ***/ /* forget history */
  12400. zero(s.head); // Fill with NIL (= 0);
  12401. if (s.lookahead === 0) {
  12402. s.strstart = 0;
  12403. s.block_start = 0;
  12404. s.insert = 0;
  12405. }
  12406. }
  12407. }
  12408. flush_pending(strm);
  12409. if (strm.avail_out === 0) {
  12410. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  12411. return Z_OK;
  12412. }
  12413. }
  12414. }
  12415. //Assert(strm->avail_out > 0, "bug2");
  12416. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  12417. if (flush !== Z_FINISH) { return Z_OK; }
  12418. if (s.wrap <= 0) { return Z_STREAM_END; }
  12419. /* Write the trailer */
  12420. if (s.wrap === 2) {
  12421. put_byte(s, strm.adler & 0xff);
  12422. put_byte(s, (strm.adler >> 8) & 0xff);
  12423. put_byte(s, (strm.adler >> 16) & 0xff);
  12424. put_byte(s, (strm.adler >> 24) & 0xff);
  12425. put_byte(s, strm.total_in & 0xff);
  12426. put_byte(s, (strm.total_in >> 8) & 0xff);
  12427. put_byte(s, (strm.total_in >> 16) & 0xff);
  12428. put_byte(s, (strm.total_in >> 24) & 0xff);
  12429. }
  12430. else
  12431. {
  12432. putShortMSB(s, strm.adler >>> 16);
  12433. putShortMSB(s, strm.adler & 0xffff);
  12434. }
  12435. flush_pending(strm);
  12436. /* If avail_out is zero, the application will call deflate again
  12437. * to flush the rest.
  12438. */
  12439. if (s.wrap > 0) { s.wrap = -s.wrap; }
  12440. /* write the trailer only once! */
  12441. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  12442. }
  12443. function deflateEnd(strm) {
  12444. var status;
  12445. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  12446. return Z_STREAM_ERROR;
  12447. }
  12448. status = strm.state.status;
  12449. if (status !== INIT_STATE &&
  12450. status !== EXTRA_STATE &&
  12451. status !== NAME_STATE &&
  12452. status !== COMMENT_STATE &&
  12453. status !== HCRC_STATE &&
  12454. status !== BUSY_STATE &&
  12455. status !== FINISH_STATE
  12456. ) {
  12457. return err(strm, Z_STREAM_ERROR);
  12458. }
  12459. strm.state = null;
  12460. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  12461. }
  12462. /* =========================================================================
  12463. * Copy the source state to the destination state
  12464. */
  12465. //function deflateCopy(dest, source) {
  12466. //
  12467. //}
  12468. exports.deflateInit = deflateInit;
  12469. exports.deflateInit2 = deflateInit2;
  12470. exports.deflateReset = deflateReset;
  12471. exports.deflateResetKeep = deflateResetKeep;
  12472. exports.deflateSetHeader = deflateSetHeader;
  12473. exports.deflate = deflate;
  12474. exports.deflateEnd = deflateEnd;
  12475. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  12476. /* Not implemented
  12477. exports.deflateBound = deflateBound;
  12478. exports.deflateCopy = deflateCopy;
  12479. exports.deflateSetDictionary = deflateSetDictionary;
  12480. exports.deflateParams = deflateParams;
  12481. exports.deflatePending = deflatePending;
  12482. exports.deflatePrime = deflatePrime;
  12483. exports.deflateTune = deflateTune;
  12484. */
  12485. },{"../utils/common":38,"./adler32":40,"./crc32":42,"./messages":48,"./trees":49}],44:[function(require,module,exports){
  12486. 'use strict';
  12487. function GZheader() {
  12488. /* true if compressed data believed to be text */
  12489. this.text = 0;
  12490. /* modification time */
  12491. this.time = 0;
  12492. /* extra flags (not used when writing a gzip file) */
  12493. this.xflags = 0;
  12494. /* operating system */
  12495. this.os = 0;
  12496. /* pointer to extra field or Z_NULL if none */
  12497. this.extra = null;
  12498. /* extra field length (valid if extra != Z_NULL) */
  12499. this.extra_len = 0; // Actually, we don't need it in JS,
  12500. // but leave for few code modifications
  12501. //
  12502. // Setup limits is not necessary because in js we should not preallocate memory
  12503. // for inflate use constant limit in 65536 bytes
  12504. //
  12505. /* space at extra (only when reading header) */
  12506. // this.extra_max = 0;
  12507. /* pointer to zero-terminated file name or Z_NULL */
  12508. this.name = '';
  12509. /* space at name (only when reading header) */
  12510. // this.name_max = 0;
  12511. /* pointer to zero-terminated comment or Z_NULL */
  12512. this.comment = '';
  12513. /* space at comment (only when reading header) */
  12514. // this.comm_max = 0;
  12515. /* true if there was or will be a header crc */
  12516. this.hcrc = 0;
  12517. /* true when done reading gzip header (not used when writing a gzip file) */
  12518. this.done = false;
  12519. }
  12520. module.exports = GZheader;
  12521. },{}],45:[function(require,module,exports){
  12522. 'use strict';
  12523. // See state defs from inflate.js
  12524. var BAD = 30; /* got a data error -- remain here until reset */
  12525. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  12526. /*
  12527. Decode literal, length, and distance codes and write out the resulting
  12528. literal and match bytes until either not enough input or output is
  12529. available, an end-of-block is encountered, or a data error is encountered.
  12530. When large enough input and output buffers are supplied to inflate(), for
  12531. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  12532. inflate execution time is spent in this routine.
  12533. Entry assumptions:
  12534. state.mode === LEN
  12535. strm.avail_in >= 6
  12536. strm.avail_out >= 258
  12537. start >= strm.avail_out
  12538. state.bits < 8
  12539. On return, state.mode is one of:
  12540. LEN -- ran out of enough output space or enough available input
  12541. TYPE -- reached end of block code, inflate() to interpret next block
  12542. BAD -- error in block data
  12543. Notes:
  12544. - The maximum input bits used by a length/distance pair is 15 bits for the
  12545. length code, 5 bits for the length extra, 15 bits for the distance code,
  12546. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  12547. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  12548. checking for available input while decoding.
  12549. - The maximum bytes that a single length/distance pair can output is 258
  12550. bytes, which is the maximum length that can be coded. inflate_fast()
  12551. requires strm.avail_out >= 258 for each loop to avoid checking for
  12552. output space.
  12553. */
  12554. module.exports = function inflate_fast(strm, start) {
  12555. var state;
  12556. var _in; /* local strm.input */
  12557. var last; /* have enough input while in < last */
  12558. var _out; /* local strm.output */
  12559. var beg; /* inflate()'s initial strm.output */
  12560. var end; /* while out < end, enough space available */
  12561. //#ifdef INFLATE_STRICT
  12562. var dmax; /* maximum distance from zlib header */
  12563. //#endif
  12564. var wsize; /* window size or zero if not using window */
  12565. var whave; /* valid bytes in the window */
  12566. var wnext; /* window write index */
  12567. var window; /* allocated sliding window, if wsize != 0 */
  12568. var hold; /* local strm.hold */
  12569. var bits; /* local strm.bits */
  12570. var lcode; /* local strm.lencode */
  12571. var dcode; /* local strm.distcode */
  12572. var lmask; /* mask for first level of length codes */
  12573. var dmask; /* mask for first level of distance codes */
  12574. var here; /* retrieved table entry */
  12575. var op; /* code bits, operation, extra bits, or */
  12576. /* window position, window bytes to copy */
  12577. var len; /* match length, unused bytes */
  12578. var dist; /* match distance */
  12579. var from; /* where to copy match from */
  12580. var from_source;
  12581. var input, output; // JS specific, because we have no pointers
  12582. /* copy state to local variables */
  12583. state = strm.state;
  12584. //here = state.here;
  12585. _in = strm.next_in;
  12586. input = strm.input;
  12587. last = _in + (strm.avail_in - 5);
  12588. _out = strm.next_out;
  12589. output = strm.output;
  12590. beg = _out - (start - strm.avail_out);
  12591. end = _out + (strm.avail_out - 257);
  12592. //#ifdef INFLATE_STRICT
  12593. dmax = state.dmax;
  12594. //#endif
  12595. wsize = state.wsize;
  12596. whave = state.whave;
  12597. wnext = state.wnext;
  12598. window = state.window;
  12599. hold = state.hold;
  12600. bits = state.bits;
  12601. lcode = state.lencode;
  12602. dcode = state.distcode;
  12603. lmask = (1 << state.lenbits) - 1;
  12604. dmask = (1 << state.distbits) - 1;
  12605. /* decode literals and length/distances until end-of-block or not enough
  12606. input data or output space */
  12607. top:
  12608. do {
  12609. if (bits < 15) {
  12610. hold += input[_in++] << bits;
  12611. bits += 8;
  12612. hold += input[_in++] << bits;
  12613. bits += 8;
  12614. }
  12615. here = lcode[hold & lmask];
  12616. dolen:
  12617. for (;;) { // Goto emulation
  12618. op = here >>> 24/*here.bits*/;
  12619. hold >>>= op;
  12620. bits -= op;
  12621. op = (here >>> 16) & 0xff/*here.op*/;
  12622. if (op === 0) { /* literal */
  12623. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  12624. // "inflate: literal '%c'\n" :
  12625. // "inflate: literal 0x%02x\n", here.val));
  12626. output[_out++] = here & 0xffff/*here.val*/;
  12627. }
  12628. else if (op & 16) { /* length base */
  12629. len = here & 0xffff/*here.val*/;
  12630. op &= 15; /* number of extra bits */
  12631. if (op) {
  12632. if (bits < op) {
  12633. hold += input[_in++] << bits;
  12634. bits += 8;
  12635. }
  12636. len += hold & ((1 << op) - 1);
  12637. hold >>>= op;
  12638. bits -= op;
  12639. }
  12640. //Tracevv((stderr, "inflate: length %u\n", len));
  12641. if (bits < 15) {
  12642. hold += input[_in++] << bits;
  12643. bits += 8;
  12644. hold += input[_in++] << bits;
  12645. bits += 8;
  12646. }
  12647. here = dcode[hold & dmask];
  12648. dodist:
  12649. for (;;) { // goto emulation
  12650. op = here >>> 24/*here.bits*/;
  12651. hold >>>= op;
  12652. bits -= op;
  12653. op = (here >>> 16) & 0xff/*here.op*/;
  12654. if (op & 16) { /* distance base */
  12655. dist = here & 0xffff/*here.val*/;
  12656. op &= 15; /* number of extra bits */
  12657. if (bits < op) {
  12658. hold += input[_in++] << bits;
  12659. bits += 8;
  12660. if (bits < op) {
  12661. hold += input[_in++] << bits;
  12662. bits += 8;
  12663. }
  12664. }
  12665. dist += hold & ((1 << op) - 1);
  12666. //#ifdef INFLATE_STRICT
  12667. if (dist > dmax) {
  12668. strm.msg = 'invalid distance too far back';
  12669. state.mode = BAD;
  12670. break top;
  12671. }
  12672. //#endif
  12673. hold >>>= op;
  12674. bits -= op;
  12675. //Tracevv((stderr, "inflate: distance %u\n", dist));
  12676. op = _out - beg; /* max distance in output */
  12677. if (dist > op) { /* see if copy from window */
  12678. op = dist - op; /* distance back in window */
  12679. if (op > whave) {
  12680. if (state.sane) {
  12681. strm.msg = 'invalid distance too far back';
  12682. state.mode = BAD;
  12683. break top;
  12684. }
  12685. // (!) This block is disabled in zlib defailts,
  12686. // don't enable it for binary compatibility
  12687. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  12688. // if (len <= op - whave) {
  12689. // do {
  12690. // output[_out++] = 0;
  12691. // } while (--len);
  12692. // continue top;
  12693. // }
  12694. // len -= op - whave;
  12695. // do {
  12696. // output[_out++] = 0;
  12697. // } while (--op > whave);
  12698. // if (op === 0) {
  12699. // from = _out - dist;
  12700. // do {
  12701. // output[_out++] = output[from++];
  12702. // } while (--len);
  12703. // continue top;
  12704. // }
  12705. //#endif
  12706. }
  12707. from = 0; // window index
  12708. from_source = window;
  12709. if (wnext === 0) { /* very common case */
  12710. from += wsize - op;
  12711. if (op < len) { /* some from window */
  12712. len -= op;
  12713. do {
  12714. output[_out++] = window[from++];
  12715. } while (--op);
  12716. from = _out - dist; /* rest from output */
  12717. from_source = output;
  12718. }
  12719. }
  12720. else if (wnext < op) { /* wrap around window */
  12721. from += wsize + wnext - op;
  12722. op -= wnext;
  12723. if (op < len) { /* some from end of window */
  12724. len -= op;
  12725. do {
  12726. output[_out++] = window[from++];
  12727. } while (--op);
  12728. from = 0;
  12729. if (wnext < len) { /* some from start of window */
  12730. op = wnext;
  12731. len -= op;
  12732. do {
  12733. output[_out++] = window[from++];
  12734. } while (--op);
  12735. from = _out - dist; /* rest from output */
  12736. from_source = output;
  12737. }
  12738. }
  12739. }
  12740. else { /* contiguous in window */
  12741. from += wnext - op;
  12742. if (op < len) { /* some from window */
  12743. len -= op;
  12744. do {
  12745. output[_out++] = window[from++];
  12746. } while (--op);
  12747. from = _out - dist; /* rest from output */
  12748. from_source = output;
  12749. }
  12750. }
  12751. while (len > 2) {
  12752. output[_out++] = from_source[from++];
  12753. output[_out++] = from_source[from++];
  12754. output[_out++] = from_source[from++];
  12755. len -= 3;
  12756. }
  12757. if (len) {
  12758. output[_out++] = from_source[from++];
  12759. if (len > 1) {
  12760. output[_out++] = from_source[from++];
  12761. }
  12762. }
  12763. }
  12764. else {
  12765. from = _out - dist; /* copy direct from output */
  12766. do { /* minimum length is three */
  12767. output[_out++] = output[from++];
  12768. output[_out++] = output[from++];
  12769. output[_out++] = output[from++];
  12770. len -= 3;
  12771. } while (len > 2);
  12772. if (len) {
  12773. output[_out++] = output[from++];
  12774. if (len > 1) {
  12775. output[_out++] = output[from++];
  12776. }
  12777. }
  12778. }
  12779. }
  12780. else if ((op & 64) === 0) { /* 2nd level distance code */
  12781. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  12782. continue dodist;
  12783. }
  12784. else {
  12785. strm.msg = 'invalid distance code';
  12786. state.mode = BAD;
  12787. break top;
  12788. }
  12789. break; // need to emulate goto via "continue"
  12790. }
  12791. }
  12792. else if ((op & 64) === 0) { /* 2nd level length code */
  12793. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  12794. continue dolen;
  12795. }
  12796. else if (op & 32) { /* end-of-block */
  12797. //Tracevv((stderr, "inflate: end of block\n"));
  12798. state.mode = TYPE;
  12799. break top;
  12800. }
  12801. else {
  12802. strm.msg = 'invalid literal/length code';
  12803. state.mode = BAD;
  12804. break top;
  12805. }
  12806. break; // need to emulate goto via "continue"
  12807. }
  12808. } while (_in < last && _out < end);
  12809. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  12810. len = bits >> 3;
  12811. _in -= len;
  12812. bits -= len << 3;
  12813. hold &= (1 << bits) - 1;
  12814. /* update state and return */
  12815. strm.next_in = _in;
  12816. strm.next_out = _out;
  12817. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  12818. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  12819. state.hold = hold;
  12820. state.bits = bits;
  12821. return;
  12822. };
  12823. },{}],46:[function(require,module,exports){
  12824. 'use strict';
  12825. var utils = require('../utils/common');
  12826. var adler32 = require('./adler32');
  12827. var crc32 = require('./crc32');
  12828. var inflate_fast = require('./inffast');
  12829. var inflate_table = require('./inftrees');
  12830. var CODES = 0;
  12831. var LENS = 1;
  12832. var DISTS = 2;
  12833. /* Public constants ==========================================================*/
  12834. /* ===========================================================================*/
  12835. /* Allowed flush values; see deflate() and inflate() below for details */
  12836. //var Z_NO_FLUSH = 0;
  12837. //var Z_PARTIAL_FLUSH = 1;
  12838. //var Z_SYNC_FLUSH = 2;
  12839. //var Z_FULL_FLUSH = 3;
  12840. var Z_FINISH = 4;
  12841. var Z_BLOCK = 5;
  12842. var Z_TREES = 6;
  12843. /* Return codes for the compression/decompression functions. Negative values
  12844. * are errors, positive values are used for special but normal events.
  12845. */
  12846. var Z_OK = 0;
  12847. var Z_STREAM_END = 1;
  12848. var Z_NEED_DICT = 2;
  12849. //var Z_ERRNO = -1;
  12850. var Z_STREAM_ERROR = -2;
  12851. var Z_DATA_ERROR = -3;
  12852. var Z_MEM_ERROR = -4;
  12853. var Z_BUF_ERROR = -5;
  12854. //var Z_VERSION_ERROR = -6;
  12855. /* The deflate compression method */
  12856. var Z_DEFLATED = 8;
  12857. /* STATES ====================================================================*/
  12858. /* ===========================================================================*/
  12859. var HEAD = 1; /* i: waiting for magic header */
  12860. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  12861. var TIME = 3; /* i: waiting for modification time (gzip) */
  12862. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  12863. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  12864. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  12865. var NAME = 7; /* i: waiting for end of file name (gzip) */
  12866. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  12867. var HCRC = 9; /* i: waiting for header crc (gzip) */
  12868. var DICTID = 10; /* i: waiting for dictionary check value */
  12869. var DICT = 11; /* waiting for inflateSetDictionary() call */
  12870. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  12871. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  12872. var STORED = 14; /* i: waiting for stored size (length and complement) */
  12873. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  12874. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  12875. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  12876. var LENLENS = 18; /* i: waiting for code length code lengths */
  12877. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  12878. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  12879. var LEN = 21; /* i: waiting for length/lit/eob code */
  12880. var LENEXT = 22; /* i: waiting for length extra bits */
  12881. var DIST = 23; /* i: waiting for distance code */
  12882. var DISTEXT = 24; /* i: waiting for distance extra bits */
  12883. var MATCH = 25; /* o: waiting for output space to copy string */
  12884. var LIT = 26; /* o: waiting for output space to write literal */
  12885. var CHECK = 27; /* i: waiting for 32-bit check value */
  12886. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  12887. var DONE = 29; /* finished check, done -- remain here until reset */
  12888. var BAD = 30; /* got a data error -- remain here until reset */
  12889. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  12890. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  12891. /* ===========================================================================*/
  12892. var ENOUGH_LENS = 852;
  12893. var ENOUGH_DISTS = 592;
  12894. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  12895. var MAX_WBITS = 15;
  12896. /* 32K LZ77 window */
  12897. var DEF_WBITS = MAX_WBITS;
  12898. function ZSWAP32(q) {
  12899. return (((q >>> 24) & 0xff) +
  12900. ((q >>> 8) & 0xff00) +
  12901. ((q & 0xff00) << 8) +
  12902. ((q & 0xff) << 24));
  12903. }
  12904. function InflateState() {
  12905. this.mode = 0; /* current inflate mode */
  12906. this.last = false; /* true if processing last block */
  12907. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  12908. this.havedict = false; /* true if dictionary provided */
  12909. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  12910. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  12911. this.check = 0; /* protected copy of check value */
  12912. this.total = 0; /* protected copy of output count */
  12913. // TODO: may be {}
  12914. this.head = null; /* where to save gzip header information */
  12915. /* sliding window */
  12916. this.wbits = 0; /* log base 2 of requested window size */
  12917. this.wsize = 0; /* window size or zero if not using window */
  12918. this.whave = 0; /* valid bytes in the window */
  12919. this.wnext = 0; /* window write index */
  12920. this.window = null; /* allocated sliding window, if needed */
  12921. /* bit accumulator */
  12922. this.hold = 0; /* input bit accumulator */
  12923. this.bits = 0; /* number of bits in "in" */
  12924. /* for string and stored block copying */
  12925. this.length = 0; /* literal or length of data to copy */
  12926. this.offset = 0; /* distance back to copy string from */
  12927. /* for table and code decoding */
  12928. this.extra = 0; /* extra bits needed */
  12929. /* fixed and dynamic code tables */
  12930. this.lencode = null; /* starting table for length/literal codes */
  12931. this.distcode = null; /* starting table for distance codes */
  12932. this.lenbits = 0; /* index bits for lencode */
  12933. this.distbits = 0; /* index bits for distcode */
  12934. /* dynamic table building */
  12935. this.ncode = 0; /* number of code length code lengths */
  12936. this.nlen = 0; /* number of length code lengths */
  12937. this.ndist = 0; /* number of distance code lengths */
  12938. this.have = 0; /* number of code lengths in lens[] */
  12939. this.next = null; /* next available space in codes[] */
  12940. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  12941. this.work = new utils.Buf16(288); /* work area for code table building */
  12942. /*
  12943. because we don't have pointers in js, we use lencode and distcode directly
  12944. as buffers so we don't need codes
  12945. */
  12946. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  12947. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  12948. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  12949. this.sane = 0; /* if false, allow invalid distance too far */
  12950. this.back = 0; /* bits back of last unprocessed length/lit */
  12951. this.was = 0; /* initial length of match */
  12952. }
  12953. function inflateResetKeep(strm) {
  12954. var state;
  12955. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12956. state = strm.state;
  12957. strm.total_in = strm.total_out = state.total = 0;
  12958. strm.msg = ''; /*Z_NULL*/
  12959. if (state.wrap) { /* to support ill-conceived Java test suite */
  12960. strm.adler = state.wrap & 1;
  12961. }
  12962. state.mode = HEAD;
  12963. state.last = 0;
  12964. state.havedict = 0;
  12965. state.dmax = 32768;
  12966. state.head = null/*Z_NULL*/;
  12967. state.hold = 0;
  12968. state.bits = 0;
  12969. //state.lencode = state.distcode = state.next = state.codes;
  12970. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  12971. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  12972. state.sane = 1;
  12973. state.back = -1;
  12974. //Tracev((stderr, "inflate: reset\n"));
  12975. return Z_OK;
  12976. }
  12977. function inflateReset(strm) {
  12978. var state;
  12979. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12980. state = strm.state;
  12981. state.wsize = 0;
  12982. state.whave = 0;
  12983. state.wnext = 0;
  12984. return inflateResetKeep(strm);
  12985. }
  12986. function inflateReset2(strm, windowBits) {
  12987. var wrap;
  12988. var state;
  12989. /* get the state */
  12990. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12991. state = strm.state;
  12992. /* extract wrap request from windowBits parameter */
  12993. if (windowBits < 0) {
  12994. wrap = 0;
  12995. windowBits = -windowBits;
  12996. }
  12997. else {
  12998. wrap = (windowBits >> 4) + 1;
  12999. if (windowBits < 48) {
  13000. windowBits &= 15;
  13001. }
  13002. }
  13003. /* set number of window bits, free window if different */
  13004. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  13005. return Z_STREAM_ERROR;
  13006. }
  13007. if (state.window !== null && state.wbits !== windowBits) {
  13008. state.window = null;
  13009. }
  13010. /* update state and reset the rest of it */
  13011. state.wrap = wrap;
  13012. state.wbits = windowBits;
  13013. return inflateReset(strm);
  13014. }
  13015. function inflateInit2(strm, windowBits) {
  13016. var ret;
  13017. var state;
  13018. if (!strm) { return Z_STREAM_ERROR; }
  13019. //strm.msg = Z_NULL; /* in case we return an error */
  13020. state = new InflateState();
  13021. //if (state === Z_NULL) return Z_MEM_ERROR;
  13022. //Tracev((stderr, "inflate: allocated\n"));
  13023. strm.state = state;
  13024. state.window = null/*Z_NULL*/;
  13025. ret = inflateReset2(strm, windowBits);
  13026. if (ret !== Z_OK) {
  13027. strm.state = null/*Z_NULL*/;
  13028. }
  13029. return ret;
  13030. }
  13031. function inflateInit(strm) {
  13032. return inflateInit2(strm, DEF_WBITS);
  13033. }
  13034. /*
  13035. Return state with length and distance decoding tables and index sizes set to
  13036. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  13037. If BUILDFIXED is defined, then instead this routine builds the tables the
  13038. first time it's called, and returns those tables the first time and
  13039. thereafter. This reduces the size of the code by about 2K bytes, in
  13040. exchange for a little execution time. However, BUILDFIXED should not be
  13041. used for threaded applications, since the rewriting of the tables and virgin
  13042. may not be thread-safe.
  13043. */
  13044. var virgin = true;
  13045. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  13046. function fixedtables(state) {
  13047. /* build fixed huffman tables if first call (may not be thread safe) */
  13048. if (virgin) {
  13049. var sym;
  13050. lenfix = new utils.Buf32(512);
  13051. distfix = new utils.Buf32(32);
  13052. /* literal/length table */
  13053. sym = 0;
  13054. while (sym < 144) { state.lens[sym++] = 8; }
  13055. while (sym < 256) { state.lens[sym++] = 9; }
  13056. while (sym < 280) { state.lens[sym++] = 7; }
  13057. while (sym < 288) { state.lens[sym++] = 8; }
  13058. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  13059. /* distance table */
  13060. sym = 0;
  13061. while (sym < 32) { state.lens[sym++] = 5; }
  13062. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  13063. /* do this just once */
  13064. virgin = false;
  13065. }
  13066. state.lencode = lenfix;
  13067. state.lenbits = 9;
  13068. state.distcode = distfix;
  13069. state.distbits = 5;
  13070. }
  13071. /*
  13072. Update the window with the last wsize (normally 32K) bytes written before
  13073. returning. If window does not exist yet, create it. This is only called
  13074. when a window is already in use, or when output has been written during this
  13075. inflate call, but the end of the deflate stream has not been reached yet.
  13076. It is also called to create a window for dictionary data when a dictionary
  13077. is loaded.
  13078. Providing output buffers larger than 32K to inflate() should provide a speed
  13079. advantage, since only the last 32K of output is copied to the sliding window
  13080. upon return from inflate(), and since all distances after the first 32K of
  13081. output will fall in the output data, making match copies simpler and faster.
  13082. The advantage may be dependent on the size of the processor's data caches.
  13083. */
  13084. function updatewindow(strm, src, end, copy) {
  13085. var dist;
  13086. var state = strm.state;
  13087. /* if it hasn't been done already, allocate space for the window */
  13088. if (state.window === null) {
  13089. state.wsize = 1 << state.wbits;
  13090. state.wnext = 0;
  13091. state.whave = 0;
  13092. state.window = new utils.Buf8(state.wsize);
  13093. }
  13094. /* copy state->wsize or less output bytes into the circular window */
  13095. if (copy >= state.wsize) {
  13096. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  13097. state.wnext = 0;
  13098. state.whave = state.wsize;
  13099. }
  13100. else {
  13101. dist = state.wsize - state.wnext;
  13102. if (dist > copy) {
  13103. dist = copy;
  13104. }
  13105. //zmemcpy(state->window + state->wnext, end - copy, dist);
  13106. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  13107. copy -= dist;
  13108. if (copy) {
  13109. //zmemcpy(state->window, end - copy, copy);
  13110. utils.arraySet(state.window,src, end - copy, copy, 0);
  13111. state.wnext = copy;
  13112. state.whave = state.wsize;
  13113. }
  13114. else {
  13115. state.wnext += dist;
  13116. if (state.wnext === state.wsize) { state.wnext = 0; }
  13117. if (state.whave < state.wsize) { state.whave += dist; }
  13118. }
  13119. }
  13120. return 0;
  13121. }
  13122. function inflate(strm, flush) {
  13123. var state;
  13124. var input, output; // input/output buffers
  13125. var next; /* next input INDEX */
  13126. var put; /* next output INDEX */
  13127. var have, left; /* available input and output */
  13128. var hold; /* bit buffer */
  13129. var bits; /* bits in bit buffer */
  13130. var _in, _out; /* save starting available input and output */
  13131. var copy; /* number of stored or match bytes to copy */
  13132. var from; /* where to copy match bytes from */
  13133. var from_source;
  13134. var here = 0; /* current decoding table entry */
  13135. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  13136. //var last; /* parent table entry */
  13137. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  13138. var len; /* length to copy for repeats, bits to drop */
  13139. var ret; /* return code */
  13140. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  13141. var opts;
  13142. var n; // temporary var for NEED_BITS
  13143. var order = /* permutation of code lengths */
  13144. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  13145. if (!strm || !strm.state || !strm.output ||
  13146. (!strm.input && strm.avail_in !== 0)) {
  13147. return Z_STREAM_ERROR;
  13148. }
  13149. state = strm.state;
  13150. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  13151. //--- LOAD() ---
  13152. put = strm.next_out;
  13153. output = strm.output;
  13154. left = strm.avail_out;
  13155. next = strm.next_in;
  13156. input = strm.input;
  13157. have = strm.avail_in;
  13158. hold = state.hold;
  13159. bits = state.bits;
  13160. //---
  13161. _in = have;
  13162. _out = left;
  13163. ret = Z_OK;
  13164. inf_leave: // goto emulation
  13165. for (;;) {
  13166. switch (state.mode) {
  13167. case HEAD:
  13168. if (state.wrap === 0) {
  13169. state.mode = TYPEDO;
  13170. break;
  13171. }
  13172. //=== NEEDBITS(16);
  13173. while (bits < 16) {
  13174. if (have === 0) { break inf_leave; }
  13175. have--;
  13176. hold += input[next++] << bits;
  13177. bits += 8;
  13178. }
  13179. //===//
  13180. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  13181. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  13182. //=== CRC2(state.check, hold);
  13183. hbuf[0] = hold & 0xff;
  13184. hbuf[1] = (hold >>> 8) & 0xff;
  13185. state.check = crc32(state.check, hbuf, 2, 0);
  13186. //===//
  13187. //=== INITBITS();
  13188. hold = 0;
  13189. bits = 0;
  13190. //===//
  13191. state.mode = FLAGS;
  13192. break;
  13193. }
  13194. state.flags = 0; /* expect zlib header */
  13195. if (state.head) {
  13196. state.head.done = false;
  13197. }
  13198. if (!(state.wrap & 1) || /* check if zlib header allowed */
  13199. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  13200. strm.msg = 'incorrect header check';
  13201. state.mode = BAD;
  13202. break;
  13203. }
  13204. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  13205. strm.msg = 'unknown compression method';
  13206. state.mode = BAD;
  13207. break;
  13208. }
  13209. //--- DROPBITS(4) ---//
  13210. hold >>>= 4;
  13211. bits -= 4;
  13212. //---//
  13213. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  13214. if (state.wbits === 0) {
  13215. state.wbits = len;
  13216. }
  13217. else if (len > state.wbits) {
  13218. strm.msg = 'invalid window size';
  13219. state.mode = BAD;
  13220. break;
  13221. }
  13222. state.dmax = 1 << len;
  13223. //Tracev((stderr, "inflate: zlib header ok\n"));
  13224. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  13225. state.mode = hold & 0x200 ? DICTID : TYPE;
  13226. //=== INITBITS();
  13227. hold = 0;
  13228. bits = 0;
  13229. //===//
  13230. break;
  13231. case FLAGS:
  13232. //=== NEEDBITS(16); */
  13233. while (bits < 16) {
  13234. if (have === 0) { break inf_leave; }
  13235. have--;
  13236. hold += input[next++] << bits;
  13237. bits += 8;
  13238. }
  13239. //===//
  13240. state.flags = hold;
  13241. if ((state.flags & 0xff) !== Z_DEFLATED) {
  13242. strm.msg = 'unknown compression method';
  13243. state.mode = BAD;
  13244. break;
  13245. }
  13246. if (state.flags & 0xe000) {
  13247. strm.msg = 'unknown header flags set';
  13248. state.mode = BAD;
  13249. break;
  13250. }
  13251. if (state.head) {
  13252. state.head.text = ((hold >> 8) & 1);
  13253. }
  13254. if (state.flags & 0x0200) {
  13255. //=== CRC2(state.check, hold);
  13256. hbuf[0] = hold & 0xff;
  13257. hbuf[1] = (hold >>> 8) & 0xff;
  13258. state.check = crc32(state.check, hbuf, 2, 0);
  13259. //===//
  13260. }
  13261. //=== INITBITS();
  13262. hold = 0;
  13263. bits = 0;
  13264. //===//
  13265. state.mode = TIME;
  13266. /* falls through */
  13267. case TIME:
  13268. //=== NEEDBITS(32); */
  13269. while (bits < 32) {
  13270. if (have === 0) { break inf_leave; }
  13271. have--;
  13272. hold += input[next++] << bits;
  13273. bits += 8;
  13274. }
  13275. //===//
  13276. if (state.head) {
  13277. state.head.time = hold;
  13278. }
  13279. if (state.flags & 0x0200) {
  13280. //=== CRC4(state.check, hold)
  13281. hbuf[0] = hold & 0xff;
  13282. hbuf[1] = (hold >>> 8) & 0xff;
  13283. hbuf[2] = (hold >>> 16) & 0xff;
  13284. hbuf[3] = (hold >>> 24) & 0xff;
  13285. state.check = crc32(state.check, hbuf, 4, 0);
  13286. //===
  13287. }
  13288. //=== INITBITS();
  13289. hold = 0;
  13290. bits = 0;
  13291. //===//
  13292. state.mode = OS;
  13293. /* falls through */
  13294. case OS:
  13295. //=== NEEDBITS(16); */
  13296. while (bits < 16) {
  13297. if (have === 0) { break inf_leave; }
  13298. have--;
  13299. hold += input[next++] << bits;
  13300. bits += 8;
  13301. }
  13302. //===//
  13303. if (state.head) {
  13304. state.head.xflags = (hold & 0xff);
  13305. state.head.os = (hold >> 8);
  13306. }
  13307. if (state.flags & 0x0200) {
  13308. //=== CRC2(state.check, hold);
  13309. hbuf[0] = hold & 0xff;
  13310. hbuf[1] = (hold >>> 8) & 0xff;
  13311. state.check = crc32(state.check, hbuf, 2, 0);
  13312. //===//
  13313. }
  13314. //=== INITBITS();
  13315. hold = 0;
  13316. bits = 0;
  13317. //===//
  13318. state.mode = EXLEN;
  13319. /* falls through */
  13320. case EXLEN:
  13321. if (state.flags & 0x0400) {
  13322. //=== NEEDBITS(16); */
  13323. while (bits < 16) {
  13324. if (have === 0) { break inf_leave; }
  13325. have--;
  13326. hold += input[next++] << bits;
  13327. bits += 8;
  13328. }
  13329. //===//
  13330. state.length = hold;
  13331. if (state.head) {
  13332. state.head.extra_len = hold;
  13333. }
  13334. if (state.flags & 0x0200) {
  13335. //=== CRC2(state.check, hold);
  13336. hbuf[0] = hold & 0xff;
  13337. hbuf[1] = (hold >>> 8) & 0xff;
  13338. state.check = crc32(state.check, hbuf, 2, 0);
  13339. //===//
  13340. }
  13341. //=== INITBITS();
  13342. hold = 0;
  13343. bits = 0;
  13344. //===//
  13345. }
  13346. else if (state.head) {
  13347. state.head.extra = null/*Z_NULL*/;
  13348. }
  13349. state.mode = EXTRA;
  13350. /* falls through */
  13351. case EXTRA:
  13352. if (state.flags & 0x0400) {
  13353. copy = state.length;
  13354. if (copy > have) { copy = have; }
  13355. if (copy) {
  13356. if (state.head) {
  13357. len = state.head.extra_len - state.length;
  13358. if (!state.head.extra) {
  13359. // Use untyped array for more conveniend processing later
  13360. state.head.extra = new Array(state.head.extra_len);
  13361. }
  13362. utils.arraySet(
  13363. state.head.extra,
  13364. input,
  13365. next,
  13366. // extra field is limited to 65536 bytes
  13367. // - no need for additional size check
  13368. copy,
  13369. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  13370. len
  13371. );
  13372. //zmemcpy(state.head.extra + len, next,
  13373. // len + copy > state.head.extra_max ?
  13374. // state.head.extra_max - len : copy);
  13375. }
  13376. if (state.flags & 0x0200) {
  13377. state.check = crc32(state.check, input, copy, next);
  13378. }
  13379. have -= copy;
  13380. next += copy;
  13381. state.length -= copy;
  13382. }
  13383. if (state.length) { break inf_leave; }
  13384. }
  13385. state.length = 0;
  13386. state.mode = NAME;
  13387. /* falls through */
  13388. case NAME:
  13389. if (state.flags & 0x0800) {
  13390. if (have === 0) { break inf_leave; }
  13391. copy = 0;
  13392. do {
  13393. // TODO: 2 or 1 bytes?
  13394. len = input[next + copy++];
  13395. /* use constant limit because in js we should not preallocate memory */
  13396. if (state.head && len &&
  13397. (state.length < 65536 /*state.head.name_max*/)) {
  13398. state.head.name += String.fromCharCode(len);
  13399. }
  13400. } while (len && copy < have);
  13401. if (state.flags & 0x0200) {
  13402. state.check = crc32(state.check, input, copy, next);
  13403. }
  13404. have -= copy;
  13405. next += copy;
  13406. if (len) { break inf_leave; }
  13407. }
  13408. else if (state.head) {
  13409. state.head.name = null;
  13410. }
  13411. state.length = 0;
  13412. state.mode = COMMENT;
  13413. /* falls through */
  13414. case COMMENT:
  13415. if (state.flags & 0x1000) {
  13416. if (have === 0) { break inf_leave; }
  13417. copy = 0;
  13418. do {
  13419. len = input[next + copy++];
  13420. /* use constant limit because in js we should not preallocate memory */
  13421. if (state.head && len &&
  13422. (state.length < 65536 /*state.head.comm_max*/)) {
  13423. state.head.comment += String.fromCharCode(len);
  13424. }
  13425. } while (len && copy < have);
  13426. if (state.flags & 0x0200) {
  13427. state.check = crc32(state.check, input, copy, next);
  13428. }
  13429. have -= copy;
  13430. next += copy;
  13431. if (len) { break inf_leave; }
  13432. }
  13433. else if (state.head) {
  13434. state.head.comment = null;
  13435. }
  13436. state.mode = HCRC;
  13437. /* falls through */
  13438. case HCRC:
  13439. if (state.flags & 0x0200) {
  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 (hold !== (state.check & 0xffff)) {
  13449. strm.msg = 'header crc mismatch';
  13450. state.mode = BAD;
  13451. break;
  13452. }
  13453. //=== INITBITS();
  13454. hold = 0;
  13455. bits = 0;
  13456. //===//
  13457. }
  13458. if (state.head) {
  13459. state.head.hcrc = ((state.flags >> 9) & 1);
  13460. state.head.done = true;
  13461. }
  13462. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  13463. state.mode = TYPE;
  13464. break;
  13465. case DICTID:
  13466. //=== NEEDBITS(32); */
  13467. while (bits < 32) {
  13468. if (have === 0) { break inf_leave; }
  13469. have--;
  13470. hold += input[next++] << bits;
  13471. bits += 8;
  13472. }
  13473. //===//
  13474. strm.adler = state.check = ZSWAP32(hold);
  13475. //=== INITBITS();
  13476. hold = 0;
  13477. bits = 0;
  13478. //===//
  13479. state.mode = DICT;
  13480. /* falls through */
  13481. case DICT:
  13482. if (state.havedict === 0) {
  13483. //--- RESTORE() ---
  13484. strm.next_out = put;
  13485. strm.avail_out = left;
  13486. strm.next_in = next;
  13487. strm.avail_in = have;
  13488. state.hold = hold;
  13489. state.bits = bits;
  13490. //---
  13491. return Z_NEED_DICT;
  13492. }
  13493. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  13494. state.mode = TYPE;
  13495. /* falls through */
  13496. case TYPE:
  13497. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  13498. /* falls through */
  13499. case TYPEDO:
  13500. if (state.last) {
  13501. //--- BYTEBITS() ---//
  13502. hold >>>= bits & 7;
  13503. bits -= bits & 7;
  13504. //---//
  13505. state.mode = CHECK;
  13506. break;
  13507. }
  13508. //=== NEEDBITS(3); */
  13509. while (bits < 3) {
  13510. if (have === 0) { break inf_leave; }
  13511. have--;
  13512. hold += input[next++] << bits;
  13513. bits += 8;
  13514. }
  13515. //===//
  13516. state.last = (hold & 0x01)/*BITS(1)*/;
  13517. //--- DROPBITS(1) ---//
  13518. hold >>>= 1;
  13519. bits -= 1;
  13520. //---//
  13521. switch ((hold & 0x03)/*BITS(2)*/) {
  13522. case 0: /* stored block */
  13523. //Tracev((stderr, "inflate: stored block%s\n",
  13524. // state.last ? " (last)" : ""));
  13525. state.mode = STORED;
  13526. break;
  13527. case 1: /* fixed block */
  13528. fixedtables(state);
  13529. //Tracev((stderr, "inflate: fixed codes block%s\n",
  13530. // state.last ? " (last)" : ""));
  13531. state.mode = LEN_; /* decode codes */
  13532. if (flush === Z_TREES) {
  13533. //--- DROPBITS(2) ---//
  13534. hold >>>= 2;
  13535. bits -= 2;
  13536. //---//
  13537. break inf_leave;
  13538. }
  13539. break;
  13540. case 2: /* dynamic block */
  13541. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  13542. // state.last ? " (last)" : ""));
  13543. state.mode = TABLE;
  13544. break;
  13545. case 3:
  13546. strm.msg = 'invalid block type';
  13547. state.mode = BAD;
  13548. }
  13549. //--- DROPBITS(2) ---//
  13550. hold >>>= 2;
  13551. bits -= 2;
  13552. //---//
  13553. break;
  13554. case STORED:
  13555. //--- BYTEBITS() ---// /* go to byte boundary */
  13556. hold >>>= bits & 7;
  13557. bits -= bits & 7;
  13558. //---//
  13559. //=== NEEDBITS(32); */
  13560. while (bits < 32) {
  13561. if (have === 0) { break inf_leave; }
  13562. have--;
  13563. hold += input[next++] << bits;
  13564. bits += 8;
  13565. }
  13566. //===//
  13567. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  13568. strm.msg = 'invalid stored block lengths';
  13569. state.mode = BAD;
  13570. break;
  13571. }
  13572. state.length = hold & 0xffff;
  13573. //Tracev((stderr, "inflate: stored length %u\n",
  13574. // state.length));
  13575. //=== INITBITS();
  13576. hold = 0;
  13577. bits = 0;
  13578. //===//
  13579. state.mode = COPY_;
  13580. if (flush === Z_TREES) { break inf_leave; }
  13581. /* falls through */
  13582. case COPY_:
  13583. state.mode = COPY;
  13584. /* falls through */
  13585. case COPY:
  13586. copy = state.length;
  13587. if (copy) {
  13588. if (copy > have) { copy = have; }
  13589. if (copy > left) { copy = left; }
  13590. if (copy === 0) { break inf_leave; }
  13591. //--- zmemcpy(put, next, copy); ---
  13592. utils.arraySet(output, input, next, copy, put);
  13593. //---//
  13594. have -= copy;
  13595. next += copy;
  13596. left -= copy;
  13597. put += copy;
  13598. state.length -= copy;
  13599. break;
  13600. }
  13601. //Tracev((stderr, "inflate: stored end\n"));
  13602. state.mode = TYPE;
  13603. break;
  13604. case TABLE:
  13605. //=== NEEDBITS(14); */
  13606. while (bits < 14) {
  13607. if (have === 0) { break inf_leave; }
  13608. have--;
  13609. hold += input[next++] << bits;
  13610. bits += 8;
  13611. }
  13612. //===//
  13613. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  13614. //--- DROPBITS(5) ---//
  13615. hold >>>= 5;
  13616. bits -= 5;
  13617. //---//
  13618. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  13619. //--- DROPBITS(5) ---//
  13620. hold >>>= 5;
  13621. bits -= 5;
  13622. //---//
  13623. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  13624. //--- DROPBITS(4) ---//
  13625. hold >>>= 4;
  13626. bits -= 4;
  13627. //---//
  13628. //#ifndef PKZIP_BUG_WORKAROUND
  13629. if (state.nlen > 286 || state.ndist > 30) {
  13630. strm.msg = 'too many length or distance symbols';
  13631. state.mode = BAD;
  13632. break;
  13633. }
  13634. //#endif
  13635. //Tracev((stderr, "inflate: table sizes ok\n"));
  13636. state.have = 0;
  13637. state.mode = LENLENS;
  13638. /* falls through */
  13639. case LENLENS:
  13640. while (state.have < state.ncode) {
  13641. //=== NEEDBITS(3);
  13642. while (bits < 3) {
  13643. if (have === 0) { break inf_leave; }
  13644. have--;
  13645. hold += input[next++] << bits;
  13646. bits += 8;
  13647. }
  13648. //===//
  13649. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  13650. //--- DROPBITS(3) ---//
  13651. hold >>>= 3;
  13652. bits -= 3;
  13653. //---//
  13654. }
  13655. while (state.have < 19) {
  13656. state.lens[order[state.have++]] = 0;
  13657. }
  13658. // We have separate tables & no pointers. 2 commented lines below not needed.
  13659. //state.next = state.codes;
  13660. //state.lencode = state.next;
  13661. // Switch to use dynamic table
  13662. state.lencode = state.lendyn;
  13663. state.lenbits = 7;
  13664. opts = {bits: state.lenbits};
  13665. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  13666. state.lenbits = opts.bits;
  13667. if (ret) {
  13668. strm.msg = 'invalid code lengths set';
  13669. state.mode = BAD;
  13670. break;
  13671. }
  13672. //Tracev((stderr, "inflate: code lengths ok\n"));
  13673. state.have = 0;
  13674. state.mode = CODELENS;
  13675. /* falls through */
  13676. case CODELENS:
  13677. while (state.have < state.nlen + state.ndist) {
  13678. for (;;) {
  13679. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  13680. here_bits = here >>> 24;
  13681. here_op = (here >>> 16) & 0xff;
  13682. here_val = here & 0xffff;
  13683. if ((here_bits) <= bits) { break; }
  13684. //--- PULLBYTE() ---//
  13685. if (have === 0) { break inf_leave; }
  13686. have--;
  13687. hold += input[next++] << bits;
  13688. bits += 8;
  13689. //---//
  13690. }
  13691. if (here_val < 16) {
  13692. //--- DROPBITS(here.bits) ---//
  13693. hold >>>= here_bits;
  13694. bits -= here_bits;
  13695. //---//
  13696. state.lens[state.have++] = here_val;
  13697. }
  13698. else {
  13699. if (here_val === 16) {
  13700. //=== NEEDBITS(here.bits + 2);
  13701. n = here_bits + 2;
  13702. while (bits < n) {
  13703. if (have === 0) { break inf_leave; }
  13704. have--;
  13705. hold += input[next++] << bits;
  13706. bits += 8;
  13707. }
  13708. //===//
  13709. //--- DROPBITS(here.bits) ---//
  13710. hold >>>= here_bits;
  13711. bits -= here_bits;
  13712. //---//
  13713. if (state.have === 0) {
  13714. strm.msg = 'invalid bit length repeat';
  13715. state.mode = BAD;
  13716. break;
  13717. }
  13718. len = state.lens[state.have - 1];
  13719. copy = 3 + (hold & 0x03);//BITS(2);
  13720. //--- DROPBITS(2) ---//
  13721. hold >>>= 2;
  13722. bits -= 2;
  13723. //---//
  13724. }
  13725. else if (here_val === 17) {
  13726. //=== NEEDBITS(here.bits + 3);
  13727. n = here_bits + 3;
  13728. while (bits < n) {
  13729. if (have === 0) { break inf_leave; }
  13730. have--;
  13731. hold += input[next++] << bits;
  13732. bits += 8;
  13733. }
  13734. //===//
  13735. //--- DROPBITS(here.bits) ---//
  13736. hold >>>= here_bits;
  13737. bits -= here_bits;
  13738. //---//
  13739. len = 0;
  13740. copy = 3 + (hold & 0x07);//BITS(3);
  13741. //--- DROPBITS(3) ---//
  13742. hold >>>= 3;
  13743. bits -= 3;
  13744. //---//
  13745. }
  13746. else {
  13747. //=== NEEDBITS(here.bits + 7);
  13748. n = here_bits + 7;
  13749. while (bits < n) {
  13750. if (have === 0) { break inf_leave; }
  13751. have--;
  13752. hold += input[next++] << bits;
  13753. bits += 8;
  13754. }
  13755. //===//
  13756. //--- DROPBITS(here.bits) ---//
  13757. hold >>>= here_bits;
  13758. bits -= here_bits;
  13759. //---//
  13760. len = 0;
  13761. copy = 11 + (hold & 0x7f);//BITS(7);
  13762. //--- DROPBITS(7) ---//
  13763. hold >>>= 7;
  13764. bits -= 7;
  13765. //---//
  13766. }
  13767. if (state.have + copy > state.nlen + state.ndist) {
  13768. strm.msg = 'invalid bit length repeat';
  13769. state.mode = BAD;
  13770. break;
  13771. }
  13772. while (copy--) {
  13773. state.lens[state.have++] = len;
  13774. }
  13775. }
  13776. }
  13777. /* handle error breaks in while */
  13778. if (state.mode === BAD) { break; }
  13779. /* check for end-of-block code (better have one) */
  13780. if (state.lens[256] === 0) {
  13781. strm.msg = 'invalid code -- missing end-of-block';
  13782. state.mode = BAD;
  13783. break;
  13784. }
  13785. /* build code tables -- note: do not change the lenbits or distbits
  13786. values here (9 and 6) without reading the comments in inftrees.h
  13787. concerning the ENOUGH constants, which depend on those values */
  13788. state.lenbits = 9;
  13789. opts = {bits: state.lenbits};
  13790. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  13791. // We have separate tables & no pointers. 2 commented lines below not needed.
  13792. // state.next_index = opts.table_index;
  13793. state.lenbits = opts.bits;
  13794. // state.lencode = state.next;
  13795. if (ret) {
  13796. strm.msg = 'invalid literal/lengths set';
  13797. state.mode = BAD;
  13798. break;
  13799. }
  13800. state.distbits = 6;
  13801. //state.distcode.copy(state.codes);
  13802. // Switch to use dynamic table
  13803. state.distcode = state.distdyn;
  13804. opts = {bits: state.distbits};
  13805. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  13806. // We have separate tables & no pointers. 2 commented lines below not needed.
  13807. // state.next_index = opts.table_index;
  13808. state.distbits = opts.bits;
  13809. // state.distcode = state.next;
  13810. if (ret) {
  13811. strm.msg = 'invalid distances set';
  13812. state.mode = BAD;
  13813. break;
  13814. }
  13815. //Tracev((stderr, 'inflate: codes ok\n'));
  13816. state.mode = LEN_;
  13817. if (flush === Z_TREES) { break inf_leave; }
  13818. /* falls through */
  13819. case LEN_:
  13820. state.mode = LEN;
  13821. /* falls through */
  13822. case LEN:
  13823. if (have >= 6 && left >= 258) {
  13824. //--- RESTORE() ---
  13825. strm.next_out = put;
  13826. strm.avail_out = left;
  13827. strm.next_in = next;
  13828. strm.avail_in = have;
  13829. state.hold = hold;
  13830. state.bits = bits;
  13831. //---
  13832. inflate_fast(strm, _out);
  13833. //--- LOAD() ---
  13834. put = strm.next_out;
  13835. output = strm.output;
  13836. left = strm.avail_out;
  13837. next = strm.next_in;
  13838. input = strm.input;
  13839. have = strm.avail_in;
  13840. hold = state.hold;
  13841. bits = state.bits;
  13842. //---
  13843. if (state.mode === TYPE) {
  13844. state.back = -1;
  13845. }
  13846. break;
  13847. }
  13848. state.back = 0;
  13849. for (;;) {
  13850. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  13851. here_bits = here >>> 24;
  13852. here_op = (here >>> 16) & 0xff;
  13853. here_val = here & 0xffff;
  13854. if (here_bits <= bits) { break; }
  13855. //--- PULLBYTE() ---//
  13856. if (have === 0) { break inf_leave; }
  13857. have--;
  13858. hold += input[next++] << bits;
  13859. bits += 8;
  13860. //---//
  13861. }
  13862. if (here_op && (here_op & 0xf0) === 0) {
  13863. last_bits = here_bits;
  13864. last_op = here_op;
  13865. last_val = here_val;
  13866. for (;;) {
  13867. here = state.lencode[last_val +
  13868. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  13869. here_bits = here >>> 24;
  13870. here_op = (here >>> 16) & 0xff;
  13871. here_val = here & 0xffff;
  13872. if ((last_bits + here_bits) <= bits) { break; }
  13873. //--- PULLBYTE() ---//
  13874. if (have === 0) { break inf_leave; }
  13875. have--;
  13876. hold += input[next++] << bits;
  13877. bits += 8;
  13878. //---//
  13879. }
  13880. //--- DROPBITS(last.bits) ---//
  13881. hold >>>= last_bits;
  13882. bits -= last_bits;
  13883. //---//
  13884. state.back += last_bits;
  13885. }
  13886. //--- DROPBITS(here.bits) ---//
  13887. hold >>>= here_bits;
  13888. bits -= here_bits;
  13889. //---//
  13890. state.back += here_bits;
  13891. state.length = here_val;
  13892. if (here_op === 0) {
  13893. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  13894. // "inflate: literal '%c'\n" :
  13895. // "inflate: literal 0x%02x\n", here.val));
  13896. state.mode = LIT;
  13897. break;
  13898. }
  13899. if (here_op & 32) {
  13900. //Tracevv((stderr, "inflate: end of block\n"));
  13901. state.back = -1;
  13902. state.mode = TYPE;
  13903. break;
  13904. }
  13905. if (here_op & 64) {
  13906. strm.msg = 'invalid literal/length code';
  13907. state.mode = BAD;
  13908. break;
  13909. }
  13910. state.extra = here_op & 15;
  13911. state.mode = LENEXT;
  13912. /* falls through */
  13913. case LENEXT:
  13914. if (state.extra) {
  13915. //=== NEEDBITS(state.extra);
  13916. n = state.extra;
  13917. while (bits < n) {
  13918. if (have === 0) { break inf_leave; }
  13919. have--;
  13920. hold += input[next++] << bits;
  13921. bits += 8;
  13922. }
  13923. //===//
  13924. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  13925. //--- DROPBITS(state.extra) ---//
  13926. hold >>>= state.extra;
  13927. bits -= state.extra;
  13928. //---//
  13929. state.back += state.extra;
  13930. }
  13931. //Tracevv((stderr, "inflate: length %u\n", state.length));
  13932. state.was = state.length;
  13933. state.mode = DIST;
  13934. /* falls through */
  13935. case DIST:
  13936. for (;;) {
  13937. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  13938. here_bits = here >>> 24;
  13939. here_op = (here >>> 16) & 0xff;
  13940. here_val = here & 0xffff;
  13941. if ((here_bits) <= bits) { break; }
  13942. //--- PULLBYTE() ---//
  13943. if (have === 0) { break inf_leave; }
  13944. have--;
  13945. hold += input[next++] << bits;
  13946. bits += 8;
  13947. //---//
  13948. }
  13949. if ((here_op & 0xf0) === 0) {
  13950. last_bits = here_bits;
  13951. last_op = here_op;
  13952. last_val = here_val;
  13953. for (;;) {
  13954. here = state.distcode[last_val +
  13955. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  13956. here_bits = here >>> 24;
  13957. here_op = (here >>> 16) & 0xff;
  13958. here_val = here & 0xffff;
  13959. if ((last_bits + here_bits) <= bits) { break; }
  13960. //--- PULLBYTE() ---//
  13961. if (have === 0) { break inf_leave; }
  13962. have--;
  13963. hold += input[next++] << bits;
  13964. bits += 8;
  13965. //---//
  13966. }
  13967. //--- DROPBITS(last.bits) ---//
  13968. hold >>>= last_bits;
  13969. bits -= last_bits;
  13970. //---//
  13971. state.back += last_bits;
  13972. }
  13973. //--- DROPBITS(here.bits) ---//
  13974. hold >>>= here_bits;
  13975. bits -= here_bits;
  13976. //---//
  13977. state.back += here_bits;
  13978. if (here_op & 64) {
  13979. strm.msg = 'invalid distance code';
  13980. state.mode = BAD;
  13981. break;
  13982. }
  13983. state.offset = here_val;
  13984. state.extra = (here_op) & 15;
  13985. state.mode = DISTEXT;
  13986. /* falls through */
  13987. case DISTEXT:
  13988. if (state.extra) {
  13989. //=== NEEDBITS(state.extra);
  13990. n = state.extra;
  13991. while (bits < n) {
  13992. if (have === 0) { break inf_leave; }
  13993. have--;
  13994. hold += input[next++] << bits;
  13995. bits += 8;
  13996. }
  13997. //===//
  13998. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  13999. //--- DROPBITS(state.extra) ---//
  14000. hold >>>= state.extra;
  14001. bits -= state.extra;
  14002. //---//
  14003. state.back += state.extra;
  14004. }
  14005. //#ifdef INFLATE_STRICT
  14006. if (state.offset > state.dmax) {
  14007. strm.msg = 'invalid distance too far back';
  14008. state.mode = BAD;
  14009. break;
  14010. }
  14011. //#endif
  14012. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  14013. state.mode = MATCH;
  14014. /* falls through */
  14015. case MATCH:
  14016. if (left === 0) { break inf_leave; }
  14017. copy = _out - left;
  14018. if (state.offset > copy) { /* copy from window */
  14019. copy = state.offset - copy;
  14020. if (copy > state.whave) {
  14021. if (state.sane) {
  14022. strm.msg = 'invalid distance too far back';
  14023. state.mode = BAD;
  14024. break;
  14025. }
  14026. // (!) This block is disabled in zlib defailts,
  14027. // don't enable it for binary compatibility
  14028. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  14029. // Trace((stderr, "inflate.c too far\n"));
  14030. // copy -= state.whave;
  14031. // if (copy > state.length) { copy = state.length; }
  14032. // if (copy > left) { copy = left; }
  14033. // left -= copy;
  14034. // state.length -= copy;
  14035. // do {
  14036. // output[put++] = 0;
  14037. // } while (--copy);
  14038. // if (state.length === 0) { state.mode = LEN; }
  14039. // break;
  14040. //#endif
  14041. }
  14042. if (copy > state.wnext) {
  14043. copy -= state.wnext;
  14044. from = state.wsize - copy;
  14045. }
  14046. else {
  14047. from = state.wnext - copy;
  14048. }
  14049. if (copy > state.length) { copy = state.length; }
  14050. from_source = state.window;
  14051. }
  14052. else { /* copy from output */
  14053. from_source = output;
  14054. from = put - state.offset;
  14055. copy = state.length;
  14056. }
  14057. if (copy > left) { copy = left; }
  14058. left -= copy;
  14059. state.length -= copy;
  14060. do {
  14061. output[put++] = from_source[from++];
  14062. } while (--copy);
  14063. if (state.length === 0) { state.mode = LEN; }
  14064. break;
  14065. case LIT:
  14066. if (left === 0) { break inf_leave; }
  14067. output[put++] = state.length;
  14068. left--;
  14069. state.mode = LEN;
  14070. break;
  14071. case CHECK:
  14072. if (state.wrap) {
  14073. //=== NEEDBITS(32);
  14074. while (bits < 32) {
  14075. if (have === 0) { break inf_leave; }
  14076. have--;
  14077. // Use '|' insdead of '+' to make sure that result is signed
  14078. hold |= input[next++] << bits;
  14079. bits += 8;
  14080. }
  14081. //===//
  14082. _out -= left;
  14083. strm.total_out += _out;
  14084. state.total += _out;
  14085. if (_out) {
  14086. strm.adler = state.check =
  14087. /*UPDATE(state.check, put - _out, _out);*/
  14088. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  14089. }
  14090. _out = left;
  14091. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  14092. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  14093. strm.msg = 'incorrect data check';
  14094. state.mode = BAD;
  14095. break;
  14096. }
  14097. //=== INITBITS();
  14098. hold = 0;
  14099. bits = 0;
  14100. //===//
  14101. //Tracev((stderr, "inflate: check matches trailer\n"));
  14102. }
  14103. state.mode = LENGTH;
  14104. /* falls through */
  14105. case LENGTH:
  14106. if (state.wrap && state.flags) {
  14107. //=== NEEDBITS(32);
  14108. while (bits < 32) {
  14109. if (have === 0) { break inf_leave; }
  14110. have--;
  14111. hold += input[next++] << bits;
  14112. bits += 8;
  14113. }
  14114. //===//
  14115. if (hold !== (state.total & 0xffffffff)) {
  14116. strm.msg = 'incorrect length check';
  14117. state.mode = BAD;
  14118. break;
  14119. }
  14120. //=== INITBITS();
  14121. hold = 0;
  14122. bits = 0;
  14123. //===//
  14124. //Tracev((stderr, "inflate: length matches trailer\n"));
  14125. }
  14126. state.mode = DONE;
  14127. /* falls through */
  14128. case DONE:
  14129. ret = Z_STREAM_END;
  14130. break inf_leave;
  14131. case BAD:
  14132. ret = Z_DATA_ERROR;
  14133. break inf_leave;
  14134. case MEM:
  14135. return Z_MEM_ERROR;
  14136. case SYNC:
  14137. /* falls through */
  14138. default:
  14139. return Z_STREAM_ERROR;
  14140. }
  14141. }
  14142. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  14143. /*
  14144. Return from inflate(), updating the total counts and the check value.
  14145. If there was no progress during the inflate() call, return a buffer
  14146. error. Call updatewindow() to create and/or update the window state.
  14147. Note: a memory error from inflate() is non-recoverable.
  14148. */
  14149. //--- RESTORE() ---
  14150. strm.next_out = put;
  14151. strm.avail_out = left;
  14152. strm.next_in = next;
  14153. strm.avail_in = have;
  14154. state.hold = hold;
  14155. state.bits = bits;
  14156. //---
  14157. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  14158. (state.mode < CHECK || flush !== Z_FINISH))) {
  14159. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  14160. state.mode = MEM;
  14161. return Z_MEM_ERROR;
  14162. }
  14163. }
  14164. _in -= strm.avail_in;
  14165. _out -= strm.avail_out;
  14166. strm.total_in += _in;
  14167. strm.total_out += _out;
  14168. state.total += _out;
  14169. if (state.wrap && _out) {
  14170. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  14171. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  14172. }
  14173. strm.data_type = state.bits + (state.last ? 64 : 0) +
  14174. (state.mode === TYPE ? 128 : 0) +
  14175. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  14176. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  14177. ret = Z_BUF_ERROR;
  14178. }
  14179. return ret;
  14180. }
  14181. function inflateEnd(strm) {
  14182. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  14183. return Z_STREAM_ERROR;
  14184. }
  14185. var state = strm.state;
  14186. if (state.window) {
  14187. state.window = null;
  14188. }
  14189. strm.state = null;
  14190. return Z_OK;
  14191. }
  14192. function inflateGetHeader(strm, head) {
  14193. var state;
  14194. /* check state */
  14195. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14196. state = strm.state;
  14197. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  14198. /* save header structure */
  14199. state.head = head;
  14200. head.done = false;
  14201. return Z_OK;
  14202. }
  14203. exports.inflateReset = inflateReset;
  14204. exports.inflateReset2 = inflateReset2;
  14205. exports.inflateResetKeep = inflateResetKeep;
  14206. exports.inflateInit = inflateInit;
  14207. exports.inflateInit2 = inflateInit2;
  14208. exports.inflate = inflate;
  14209. exports.inflateEnd = inflateEnd;
  14210. exports.inflateGetHeader = inflateGetHeader;
  14211. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  14212. /* Not implemented
  14213. exports.inflateCopy = inflateCopy;
  14214. exports.inflateGetDictionary = inflateGetDictionary;
  14215. exports.inflateMark = inflateMark;
  14216. exports.inflatePrime = inflatePrime;
  14217. exports.inflateSetDictionary = inflateSetDictionary;
  14218. exports.inflateSync = inflateSync;
  14219. exports.inflateSyncPoint = inflateSyncPoint;
  14220. exports.inflateUndermine = inflateUndermine;
  14221. */
  14222. },{"../utils/common":38,"./adler32":40,"./crc32":42,"./inffast":45,"./inftrees":47}],47:[function(require,module,exports){
  14223. 'use strict';
  14224. var utils = require('../utils/common');
  14225. var MAXBITS = 15;
  14226. var ENOUGH_LENS = 852;
  14227. var ENOUGH_DISTS = 592;
  14228. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  14229. var CODES = 0;
  14230. var LENS = 1;
  14231. var DISTS = 2;
  14232. var lbase = [ /* Length codes 257..285 base */
  14233. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  14234. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  14235. ];
  14236. var lext = [ /* Length codes 257..285 extra */
  14237. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  14238. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  14239. ];
  14240. var dbase = [ /* Distance codes 0..29 base */
  14241. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  14242. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  14243. 8193, 12289, 16385, 24577, 0, 0
  14244. ];
  14245. var dext = [ /* Distance codes 0..29 extra */
  14246. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  14247. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  14248. 28, 28, 29, 29, 64, 64
  14249. ];
  14250. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  14251. {
  14252. var bits = opts.bits;
  14253. //here = opts.here; /* table entry for duplication */
  14254. var len = 0; /* a code's length in bits */
  14255. var sym = 0; /* index of code symbols */
  14256. var min = 0, max = 0; /* minimum and maximum code lengths */
  14257. var root = 0; /* number of index bits for root table */
  14258. var curr = 0; /* number of index bits for current table */
  14259. var drop = 0; /* code bits to drop for sub-table */
  14260. var left = 0; /* number of prefix codes available */
  14261. var used = 0; /* code entries in table used */
  14262. var huff = 0; /* Huffman code */
  14263. var incr; /* for incrementing code, index */
  14264. var fill; /* index for replicating entries */
  14265. var low; /* low bits for current root entry */
  14266. var mask; /* mask for low root bits */
  14267. var next; /* next available space in table */
  14268. var base = null; /* base value table to use */
  14269. var base_index = 0;
  14270. // var shoextra; /* extra bits table to use */
  14271. var end; /* use base and extra for symbol > end */
  14272. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  14273. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  14274. var extra = null;
  14275. var extra_index = 0;
  14276. var here_bits, here_op, here_val;
  14277. /*
  14278. Process a set of code lengths to create a canonical Huffman code. The
  14279. code lengths are lens[0..codes-1]. Each length corresponds to the
  14280. symbols 0..codes-1. The Huffman code is generated by first sorting the
  14281. symbols by length from short to long, and retaining the symbol order
  14282. for codes with equal lengths. Then the code starts with all zero bits
  14283. for the first code of the shortest length, and the codes are integer
  14284. increments for the same length, and zeros are appended as the length
  14285. increases. For the deflate format, these bits are stored backwards
  14286. from their more natural integer increment ordering, and so when the
  14287. decoding tables are built in the large loop below, the integer codes
  14288. are incremented backwards.
  14289. This routine assumes, but does not check, that all of the entries in
  14290. lens[] are in the range 0..MAXBITS. The caller must assure this.
  14291. 1..MAXBITS is interpreted as that code length. zero means that that
  14292. symbol does not occur in this code.
  14293. The codes are sorted by computing a count of codes for each length,
  14294. creating from that a table of starting indices for each length in the
  14295. sorted table, and then entering the symbols in order in the sorted
  14296. table. The sorted table is work[], with that space being provided by
  14297. the caller.
  14298. The length counts are used for other purposes as well, i.e. finding
  14299. the minimum and maximum length codes, determining if there are any
  14300. codes at all, checking for a valid set of lengths, and looking ahead
  14301. at length counts to determine sub-table sizes when building the
  14302. decoding tables.
  14303. */
  14304. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  14305. for (len = 0; len <= MAXBITS; len++) {
  14306. count[len] = 0;
  14307. }
  14308. for (sym = 0; sym < codes; sym++) {
  14309. count[lens[lens_index + sym]]++;
  14310. }
  14311. /* bound code lengths, force root to be within code lengths */
  14312. root = bits;
  14313. for (max = MAXBITS; max >= 1; max--) {
  14314. if (count[max] !== 0) { break; }
  14315. }
  14316. if (root > max) {
  14317. root = max;
  14318. }
  14319. if (max === 0) { /* no symbols to code at all */
  14320. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  14321. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  14322. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  14323. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  14324. //table.op[opts.table_index] = 64;
  14325. //table.bits[opts.table_index] = 1;
  14326. //table.val[opts.table_index++] = 0;
  14327. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  14328. opts.bits = 1;
  14329. return 0; /* no symbols, but wait for decoding to report error */
  14330. }
  14331. for (min = 1; min < max; min++) {
  14332. if (count[min] !== 0) { break; }
  14333. }
  14334. if (root < min) {
  14335. root = min;
  14336. }
  14337. /* check for an over-subscribed or incomplete set of lengths */
  14338. left = 1;
  14339. for (len = 1; len <= MAXBITS; len++) {
  14340. left <<= 1;
  14341. left -= count[len];
  14342. if (left < 0) {
  14343. return -1;
  14344. } /* over-subscribed */
  14345. }
  14346. if (left > 0 && (type === CODES || max !== 1)) {
  14347. return -1; /* incomplete set */
  14348. }
  14349. /* generate offsets into symbol table for each length for sorting */
  14350. offs[1] = 0;
  14351. for (len = 1; len < MAXBITS; len++) {
  14352. offs[len + 1] = offs[len] + count[len];
  14353. }
  14354. /* sort symbols by length, by symbol order within each length */
  14355. for (sym = 0; sym < codes; sym++) {
  14356. if (lens[lens_index + sym] !== 0) {
  14357. work[offs[lens[lens_index + sym]]++] = sym;
  14358. }
  14359. }
  14360. /*
  14361. Create and fill in decoding tables. In this loop, the table being
  14362. filled is at next and has curr index bits. The code being used is huff
  14363. with length len. That code is converted to an index by dropping drop
  14364. bits off of the bottom. For codes where len is less than drop + curr,
  14365. those top drop + curr - len bits are incremented through all values to
  14366. fill the table with replicated entries.
  14367. root is the number of index bits for the root table. When len exceeds
  14368. root, sub-tables are created pointed to by the root entry with an index
  14369. of the low root bits of huff. This is saved in low to check for when a
  14370. new sub-table should be started. drop is zero when the root table is
  14371. being filled, and drop is root when sub-tables are being filled.
  14372. When a new sub-table is needed, it is necessary to look ahead in the
  14373. code lengths to determine what size sub-table is needed. The length
  14374. counts are used for this, and so count[] is decremented as codes are
  14375. entered in the tables.
  14376. used keeps track of how many table entries have been allocated from the
  14377. provided *table space. It is checked for LENS and DIST tables against
  14378. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  14379. the initial root table size constants. See the comments in inftrees.h
  14380. for more information.
  14381. sym increments through all symbols, and the loop terminates when
  14382. all codes of length max, i.e. all codes, have been processed. This
  14383. routine permits incomplete codes, so another loop after this one fills
  14384. in the rest of the decoding tables with invalid code markers.
  14385. */
  14386. /* set up for code type */
  14387. // poor man optimization - use if-else instead of switch,
  14388. // to avoid deopts in old v8
  14389. if (type === CODES) {
  14390. base = extra = work; /* dummy value--not used */
  14391. end = 19;
  14392. } else if (type === LENS) {
  14393. base = lbase;
  14394. base_index -= 257;
  14395. extra = lext;
  14396. extra_index -= 257;
  14397. end = 256;
  14398. } else { /* DISTS */
  14399. base = dbase;
  14400. extra = dext;
  14401. end = -1;
  14402. }
  14403. /* initialize opts for loop */
  14404. huff = 0; /* starting code */
  14405. sym = 0; /* starting code symbol */
  14406. len = min; /* starting code length */
  14407. next = table_index; /* current table to fill in */
  14408. curr = root; /* current table index bits */
  14409. drop = 0; /* current bits to drop from code for index */
  14410. low = -1; /* trigger new sub-table when len > root */
  14411. used = 1 << root; /* use root table entries */
  14412. mask = used - 1; /* mask for comparing low */
  14413. /* check available table space */
  14414. if ((type === LENS && used > ENOUGH_LENS) ||
  14415. (type === DISTS && used > ENOUGH_DISTS)) {
  14416. return 1;
  14417. }
  14418. var i=0;
  14419. /* process all codes and make table entries */
  14420. for (;;) {
  14421. i++;
  14422. /* create table entry */
  14423. here_bits = len - drop;
  14424. if (work[sym] < end) {
  14425. here_op = 0;
  14426. here_val = work[sym];
  14427. }
  14428. else if (work[sym] > end) {
  14429. here_op = extra[extra_index + work[sym]];
  14430. here_val = base[base_index + work[sym]];
  14431. }
  14432. else {
  14433. here_op = 32 + 64; /* end of block */
  14434. here_val = 0;
  14435. }
  14436. /* replicate for those indices with low len bits equal to huff */
  14437. incr = 1 << (len - drop);
  14438. fill = 1 << curr;
  14439. min = fill; /* save offset to next table */
  14440. do {
  14441. fill -= incr;
  14442. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  14443. } while (fill !== 0);
  14444. /* backwards increment the len-bit code huff */
  14445. incr = 1 << (len - 1);
  14446. while (huff & incr) {
  14447. incr >>= 1;
  14448. }
  14449. if (incr !== 0) {
  14450. huff &= incr - 1;
  14451. huff += incr;
  14452. } else {
  14453. huff = 0;
  14454. }
  14455. /* go to next symbol, update count, len */
  14456. sym++;
  14457. if (--count[len] === 0) {
  14458. if (len === max) { break; }
  14459. len = lens[lens_index + work[sym]];
  14460. }
  14461. /* create new sub-table if needed */
  14462. if (len > root && (huff & mask) !== low) {
  14463. /* if first time, transition to sub-tables */
  14464. if (drop === 0) {
  14465. drop = root;
  14466. }
  14467. /* increment past last table */
  14468. next += min; /* here min is 1 << curr */
  14469. /* determine length of next table */
  14470. curr = len - drop;
  14471. left = 1 << curr;
  14472. while (curr + drop < max) {
  14473. left -= count[curr + drop];
  14474. if (left <= 0) { break; }
  14475. curr++;
  14476. left <<= 1;
  14477. }
  14478. /* check for enough space */
  14479. used += 1 << curr;
  14480. if ((type === LENS && used > ENOUGH_LENS) ||
  14481. (type === DISTS && used > ENOUGH_DISTS)) {
  14482. return 1;
  14483. }
  14484. /* point entry in root table to sub-table */
  14485. low = huff & mask;
  14486. /*table.op[low] = curr;
  14487. table.bits[low] = root;
  14488. table.val[low] = next - opts.table_index;*/
  14489. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  14490. }
  14491. }
  14492. /* fill in remaining table entry if code is incomplete (guaranteed to have
  14493. at most one remaining entry, since if the code is incomplete, the
  14494. maximum code length that was allowed to get this far is one bit) */
  14495. if (huff !== 0) {
  14496. //table.op[next + huff] = 64; /* invalid code marker */
  14497. //table.bits[next + huff] = len - drop;
  14498. //table.val[next + huff] = 0;
  14499. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  14500. }
  14501. /* set return parameters */
  14502. //opts.table_index += used;
  14503. opts.bits = root;
  14504. return 0;
  14505. };
  14506. },{"../utils/common":38}],48:[function(require,module,exports){
  14507. 'use strict';
  14508. module.exports = {
  14509. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  14510. '1': 'stream end', /* Z_STREAM_END 1 */
  14511. '0': '', /* Z_OK 0 */
  14512. '-1': 'file error', /* Z_ERRNO (-1) */
  14513. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  14514. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  14515. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  14516. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  14517. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  14518. };
  14519. },{}],49:[function(require,module,exports){
  14520. 'use strict';
  14521. var utils = require('../utils/common');
  14522. /* Public constants ==========================================================*/
  14523. /* ===========================================================================*/
  14524. //var Z_FILTERED = 1;
  14525. //var Z_HUFFMAN_ONLY = 2;
  14526. //var Z_RLE = 3;
  14527. var Z_FIXED = 4;
  14528. //var Z_DEFAULT_STRATEGY = 0;
  14529. /* Possible values of the data_type field (though see inflate()) */
  14530. var Z_BINARY = 0;
  14531. var Z_TEXT = 1;
  14532. //var Z_ASCII = 1; // = Z_TEXT
  14533. var Z_UNKNOWN = 2;
  14534. /*============================================================================*/
  14535. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  14536. // From zutil.h
  14537. var STORED_BLOCK = 0;
  14538. var STATIC_TREES = 1;
  14539. var DYN_TREES = 2;
  14540. /* The three kinds of block type */
  14541. var MIN_MATCH = 3;
  14542. var MAX_MATCH = 258;
  14543. /* The minimum and maximum match lengths */
  14544. // From deflate.h
  14545. /* ===========================================================================
  14546. * Internal compression state.
  14547. */
  14548. var LENGTH_CODES = 29;
  14549. /* number of length codes, not counting the special END_BLOCK code */
  14550. var LITERALS = 256;
  14551. /* number of literal bytes 0..255 */
  14552. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14553. /* number of Literal or Length codes, including the END_BLOCK code */
  14554. var D_CODES = 30;
  14555. /* number of distance codes */
  14556. var BL_CODES = 19;
  14557. /* number of codes used to transfer the bit lengths */
  14558. var HEAP_SIZE = 2*L_CODES + 1;
  14559. /* maximum heap size */
  14560. var MAX_BITS = 15;
  14561. /* All codes must not exceed MAX_BITS bits */
  14562. var Buf_size = 16;
  14563. /* size of bit buffer in bi_buf */
  14564. /* ===========================================================================
  14565. * Constants
  14566. */
  14567. var MAX_BL_BITS = 7;
  14568. /* Bit length codes must not exceed MAX_BL_BITS bits */
  14569. var END_BLOCK = 256;
  14570. /* end of block literal code */
  14571. var REP_3_6 = 16;
  14572. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  14573. var REPZ_3_10 = 17;
  14574. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  14575. var REPZ_11_138 = 18;
  14576. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  14577. var extra_lbits = /* extra bits for each length code */
  14578. [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];
  14579. var extra_dbits = /* extra bits for each distance code */
  14580. [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];
  14581. var extra_blbits = /* extra bits for each bit length code */
  14582. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  14583. var bl_order =
  14584. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  14585. /* The lengths of the bit length codes are sent in order of decreasing
  14586. * probability, to avoid transmitting the lengths for unused bit length codes.
  14587. */
  14588. /* ===========================================================================
  14589. * Local data. These are initialized only once.
  14590. */
  14591. // We pre-fill arrays with 0 to avoid uninitialized gaps
  14592. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  14593. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  14594. var static_ltree = new Array((L_CODES+2) * 2);
  14595. zero(static_ltree);
  14596. /* The static literal tree. Since the bit lengths are imposed, there is no
  14597. * need for the L_CODES extra codes used during heap construction. However
  14598. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  14599. * below).
  14600. */
  14601. var static_dtree = new Array(D_CODES * 2);
  14602. zero(static_dtree);
  14603. /* The static distance tree. (Actually a trivial tree since all codes use
  14604. * 5 bits.)
  14605. */
  14606. var _dist_code = new Array(DIST_CODE_LEN);
  14607. zero(_dist_code);
  14608. /* Distance codes. The first 256 values correspond to the distances
  14609. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  14610. * the 15 bit distances.
  14611. */
  14612. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  14613. zero(_length_code);
  14614. /* length code for each normalized match length (0 == MIN_MATCH) */
  14615. var base_length = new Array(LENGTH_CODES);
  14616. zero(base_length);
  14617. /* First normalized length for each code (0 = MIN_MATCH) */
  14618. var base_dist = new Array(D_CODES);
  14619. zero(base_dist);
  14620. /* First normalized distance for each code (0 = distance of 1) */
  14621. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  14622. this.static_tree = static_tree; /* static tree or NULL */
  14623. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  14624. this.extra_base = extra_base; /* base index for extra_bits */
  14625. this.elems = elems; /* max number of elements in the tree */
  14626. this.max_length = max_length; /* max bit length for the codes */
  14627. // show if `static_tree` has data or dummy - needed for monomorphic objects
  14628. this.has_stree = static_tree && static_tree.length;
  14629. };
  14630. var static_l_desc;
  14631. var static_d_desc;
  14632. var static_bl_desc;
  14633. var TreeDesc = function(dyn_tree, stat_desc) {
  14634. this.dyn_tree = dyn_tree; /* the dynamic tree */
  14635. this.max_code = 0; /* largest code with non zero frequency */
  14636. this.stat_desc = stat_desc; /* the corresponding static tree */
  14637. };
  14638. function d_code(dist) {
  14639. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  14640. }
  14641. /* ===========================================================================
  14642. * Output a short LSB first on the stream.
  14643. * IN assertion: there is enough room in pendingBuf.
  14644. */
  14645. function put_short (s, w) {
  14646. // put_byte(s, (uch)((w) & 0xff));
  14647. // put_byte(s, (uch)((ush)(w) >> 8));
  14648. s.pending_buf[s.pending++] = (w) & 0xff;
  14649. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  14650. }
  14651. /* ===========================================================================
  14652. * Send a value on a given number of bits.
  14653. * IN assertion: length <= 16 and value fits in length bits.
  14654. */
  14655. function send_bits(s, value, length) {
  14656. if (s.bi_valid > (Buf_size - length)) {
  14657. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  14658. put_short(s, s.bi_buf);
  14659. s.bi_buf = value >> (Buf_size - s.bi_valid);
  14660. s.bi_valid += length - Buf_size;
  14661. } else {
  14662. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  14663. s.bi_valid += length;
  14664. }
  14665. }
  14666. function send_code(s, c, tree) {
  14667. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  14668. }
  14669. /* ===========================================================================
  14670. * Reverse the first len bits of a code, using straightforward code (a faster
  14671. * method would use a table)
  14672. * IN assertion: 1 <= len <= 15
  14673. */
  14674. function bi_reverse(code, len) {
  14675. var res = 0;
  14676. do {
  14677. res |= code & 1;
  14678. code >>>= 1;
  14679. res <<= 1;
  14680. } while (--len > 0);
  14681. return res >>> 1;
  14682. }
  14683. /* ===========================================================================
  14684. * Flush the bit buffer, keeping at most 7 bits in it.
  14685. */
  14686. function bi_flush(s) {
  14687. if (s.bi_valid === 16) {
  14688. put_short(s, s.bi_buf);
  14689. s.bi_buf = 0;
  14690. s.bi_valid = 0;
  14691. } else if (s.bi_valid >= 8) {
  14692. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  14693. s.bi_buf >>= 8;
  14694. s.bi_valid -= 8;
  14695. }
  14696. }
  14697. /* ===========================================================================
  14698. * Compute the optimal bit lengths for a tree and update the total bit length
  14699. * for the current block.
  14700. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  14701. * above are the tree nodes sorted by increasing frequency.
  14702. * OUT assertions: the field len is set to the optimal bit length, the
  14703. * array bl_count contains the frequencies for each bit length.
  14704. * The length opt_len is updated; static_len is also updated if stree is
  14705. * not null.
  14706. */
  14707. function gen_bitlen(s, desc)
  14708. // deflate_state *s;
  14709. // tree_desc *desc; /* the tree descriptor */
  14710. {
  14711. var tree = desc.dyn_tree;
  14712. var max_code = desc.max_code;
  14713. var stree = desc.stat_desc.static_tree;
  14714. var has_stree = desc.stat_desc.has_stree;
  14715. var extra = desc.stat_desc.extra_bits;
  14716. var base = desc.stat_desc.extra_base;
  14717. var max_length = desc.stat_desc.max_length;
  14718. var h; /* heap index */
  14719. var n, m; /* iterate over the tree elements */
  14720. var bits; /* bit length */
  14721. var xbits; /* extra bits */
  14722. var f; /* frequency */
  14723. var overflow = 0; /* number of elements with bit length too large */
  14724. for (bits = 0; bits <= MAX_BITS; bits++) {
  14725. s.bl_count[bits] = 0;
  14726. }
  14727. /* In a first pass, compute the optimal bit lengths (which may
  14728. * overflow in the case of the bit length tree).
  14729. */
  14730. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  14731. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  14732. n = s.heap[h];
  14733. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  14734. if (bits > max_length) {
  14735. bits = max_length;
  14736. overflow++;
  14737. }
  14738. tree[n*2 + 1]/*.Len*/ = bits;
  14739. /* We overwrite tree[n].Dad which is no longer needed */
  14740. if (n > max_code) { continue; } /* not a leaf node */
  14741. s.bl_count[bits]++;
  14742. xbits = 0;
  14743. if (n >= base) {
  14744. xbits = extra[n-base];
  14745. }
  14746. f = tree[n * 2]/*.Freq*/;
  14747. s.opt_len += f * (bits + xbits);
  14748. if (has_stree) {
  14749. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  14750. }
  14751. }
  14752. if (overflow === 0) { return; }
  14753. // Trace((stderr,"\nbit length overflow\n"));
  14754. /* This happens for example on obj2 and pic of the Calgary corpus */
  14755. /* Find the first bit length which could increase: */
  14756. do {
  14757. bits = max_length-1;
  14758. while (s.bl_count[bits] === 0) { bits--; }
  14759. s.bl_count[bits]--; /* move one leaf down the tree */
  14760. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  14761. s.bl_count[max_length]--;
  14762. /* The brother of the overflow item also moves one step up,
  14763. * but this does not affect bl_count[max_length]
  14764. */
  14765. overflow -= 2;
  14766. } while (overflow > 0);
  14767. /* Now recompute all bit lengths, scanning in increasing frequency.
  14768. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  14769. * lengths instead of fixing only the wrong ones. This idea is taken
  14770. * from 'ar' written by Haruhiko Okumura.)
  14771. */
  14772. for (bits = max_length; bits !== 0; bits--) {
  14773. n = s.bl_count[bits];
  14774. while (n !== 0) {
  14775. m = s.heap[--h];
  14776. if (m > max_code) { continue; }
  14777. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  14778. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  14779. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  14780. tree[m*2 + 1]/*.Len*/ = bits;
  14781. }
  14782. n--;
  14783. }
  14784. }
  14785. }
  14786. /* ===========================================================================
  14787. * Generate the codes for a given tree and bit counts (which need not be
  14788. * optimal).
  14789. * IN assertion: the array bl_count contains the bit length statistics for
  14790. * the given tree and the field len is set for all tree elements.
  14791. * OUT assertion: the field code is set for all tree elements of non
  14792. * zero code length.
  14793. */
  14794. function gen_codes(tree, max_code, bl_count)
  14795. // ct_data *tree; /* the tree to decorate */
  14796. // int max_code; /* largest code with non zero frequency */
  14797. // ushf *bl_count; /* number of codes at each bit length */
  14798. {
  14799. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  14800. var code = 0; /* running code value */
  14801. var bits; /* bit index */
  14802. var n; /* code index */
  14803. /* The distribution counts are first used to generate the code values
  14804. * without bit reversal.
  14805. */
  14806. for (bits = 1; bits <= MAX_BITS; bits++) {
  14807. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  14808. }
  14809. /* Check that the bit counts in bl_count are consistent. The last code
  14810. * must be all ones.
  14811. */
  14812. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  14813. // "inconsistent bit counts");
  14814. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  14815. for (n = 0; n <= max_code; n++) {
  14816. var len = tree[n*2 + 1]/*.Len*/;
  14817. if (len === 0) { continue; }
  14818. /* Now reverse the bits */
  14819. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  14820. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  14821. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  14822. }
  14823. }
  14824. /* ===========================================================================
  14825. * Initialize the various 'constant' tables.
  14826. */
  14827. function tr_static_init() {
  14828. var n; /* iterates over tree elements */
  14829. var bits; /* bit counter */
  14830. var length; /* length value */
  14831. var code; /* code value */
  14832. var dist; /* distance index */
  14833. var bl_count = new Array(MAX_BITS+1);
  14834. /* number of codes at each bit length for an optimal tree */
  14835. // do check in _tr_init()
  14836. //if (static_init_done) return;
  14837. /* For some embedded targets, global variables are not initialized: */
  14838. /*#ifdef NO_INIT_GLOBAL_POINTERS
  14839. static_l_desc.static_tree = static_ltree;
  14840. static_l_desc.extra_bits = extra_lbits;
  14841. static_d_desc.static_tree = static_dtree;
  14842. static_d_desc.extra_bits = extra_dbits;
  14843. static_bl_desc.extra_bits = extra_blbits;
  14844. #endif*/
  14845. /* Initialize the mapping length (0..255) -> length code (0..28) */
  14846. length = 0;
  14847. for (code = 0; code < LENGTH_CODES-1; code++) {
  14848. base_length[code] = length;
  14849. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  14850. _length_code[length++] = code;
  14851. }
  14852. }
  14853. //Assert (length == 256, "tr_static_init: length != 256");
  14854. /* Note that the length 255 (match length 258) can be represented
  14855. * in two different ways: code 284 + 5 bits or code 285, so we
  14856. * overwrite length_code[255] to use the best encoding:
  14857. */
  14858. _length_code[length-1] = code;
  14859. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  14860. dist = 0;
  14861. for (code = 0 ; code < 16; code++) {
  14862. base_dist[code] = dist;
  14863. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  14864. _dist_code[dist++] = code;
  14865. }
  14866. }
  14867. //Assert (dist == 256, "tr_static_init: dist != 256");
  14868. dist >>= 7; /* from now on, all distances are divided by 128 */
  14869. for (; code < D_CODES; code++) {
  14870. base_dist[code] = dist << 7;
  14871. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  14872. _dist_code[256 + dist++] = code;
  14873. }
  14874. }
  14875. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  14876. /* Construct the codes of the static literal tree */
  14877. for (bits = 0; bits <= MAX_BITS; bits++) {
  14878. bl_count[bits] = 0;
  14879. }
  14880. n = 0;
  14881. while (n <= 143) {
  14882. static_ltree[n*2 + 1]/*.Len*/ = 8;
  14883. n++;
  14884. bl_count[8]++;
  14885. }
  14886. while (n <= 255) {
  14887. static_ltree[n*2 + 1]/*.Len*/ = 9;
  14888. n++;
  14889. bl_count[9]++;
  14890. }
  14891. while (n <= 279) {
  14892. static_ltree[n*2 + 1]/*.Len*/ = 7;
  14893. n++;
  14894. bl_count[7]++;
  14895. }
  14896. while (n <= 287) {
  14897. static_ltree[n*2 + 1]/*.Len*/ = 8;
  14898. n++;
  14899. bl_count[8]++;
  14900. }
  14901. /* Codes 286 and 287 do not exist, but we must include them in the
  14902. * tree construction to get a canonical Huffman tree (longest code
  14903. * all ones)
  14904. */
  14905. gen_codes(static_ltree, L_CODES+1, bl_count);
  14906. /* The static distance tree is trivial: */
  14907. for (n = 0; n < D_CODES; n++) {
  14908. static_dtree[n*2 + 1]/*.Len*/ = 5;
  14909. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  14910. }
  14911. // Now data ready and we can init static trees
  14912. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  14913. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  14914. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  14915. //static_init_done = true;
  14916. }
  14917. /* ===========================================================================
  14918. * Initialize a new block.
  14919. */
  14920. function init_block(s) {
  14921. var n; /* iterates over tree elements */
  14922. /* Initialize the trees. */
  14923. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  14924. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  14925. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  14926. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  14927. s.opt_len = s.static_len = 0;
  14928. s.last_lit = s.matches = 0;
  14929. }
  14930. /* ===========================================================================
  14931. * Flush the bit buffer and align the output on a byte boundary
  14932. */
  14933. function bi_windup(s)
  14934. {
  14935. if (s.bi_valid > 8) {
  14936. put_short(s, s.bi_buf);
  14937. } else if (s.bi_valid > 0) {
  14938. //put_byte(s, (Byte)s->bi_buf);
  14939. s.pending_buf[s.pending++] = s.bi_buf;
  14940. }
  14941. s.bi_buf = 0;
  14942. s.bi_valid = 0;
  14943. }
  14944. /* ===========================================================================
  14945. * Copy a stored block, storing first the length and its
  14946. * one's complement if requested.
  14947. */
  14948. function copy_block(s, buf, len, header)
  14949. //DeflateState *s;
  14950. //charf *buf; /* the input data */
  14951. //unsigned len; /* its length */
  14952. //int header; /* true if block header must be written */
  14953. {
  14954. bi_windup(s); /* align on byte boundary */
  14955. if (header) {
  14956. put_short(s, len);
  14957. put_short(s, ~len);
  14958. }
  14959. // while (len--) {
  14960. // put_byte(s, *buf++);
  14961. // }
  14962. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  14963. s.pending += len;
  14964. }
  14965. /* ===========================================================================
  14966. * Compares to subtrees, using the tree depth as tie breaker when
  14967. * the subtrees have equal frequency. This minimizes the worst case length.
  14968. */
  14969. function smaller(tree, n, m, depth) {
  14970. var _n2 = n*2;
  14971. var _m2 = m*2;
  14972. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  14973. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  14974. }
  14975. /* ===========================================================================
  14976. * Restore the heap property by moving down the tree starting at node k,
  14977. * exchanging a node with the smallest of its two sons if necessary, stopping
  14978. * when the heap property is re-established (each father smaller than its
  14979. * two sons).
  14980. */
  14981. function pqdownheap(s, tree, k)
  14982. // deflate_state *s;
  14983. // ct_data *tree; /* the tree to restore */
  14984. // int k; /* node to move down */
  14985. {
  14986. var v = s.heap[k];
  14987. var j = k << 1; /* left son of k */
  14988. while (j <= s.heap_len) {
  14989. /* Set j to the smallest of the two sons: */
  14990. if (j < s.heap_len &&
  14991. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  14992. j++;
  14993. }
  14994. /* Exit if v is smaller than both sons */
  14995. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  14996. /* Exchange v with the smallest son */
  14997. s.heap[k] = s.heap[j];
  14998. k = j;
  14999. /* And continue down the tree, setting j to the left son of k */
  15000. j <<= 1;
  15001. }
  15002. s.heap[k] = v;
  15003. }
  15004. // inlined manually
  15005. // var SMALLEST = 1;
  15006. /* ===========================================================================
  15007. * Send the block data compressed using the given Huffman trees
  15008. */
  15009. function compress_block(s, ltree, dtree)
  15010. // deflate_state *s;
  15011. // const ct_data *ltree; /* literal tree */
  15012. // const ct_data *dtree; /* distance tree */
  15013. {
  15014. var dist; /* distance of matched string */
  15015. var lc; /* match length or unmatched char (if dist == 0) */
  15016. var lx = 0; /* running index in l_buf */
  15017. var code; /* the code to send */
  15018. var extra; /* number of extra bits to send */
  15019. if (s.last_lit !== 0) {
  15020. do {
  15021. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  15022. lc = s.pending_buf[s.l_buf + lx];
  15023. lx++;
  15024. if (dist === 0) {
  15025. send_code(s, lc, ltree); /* send a literal byte */
  15026. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  15027. } else {
  15028. /* Here, lc is the match length - MIN_MATCH */
  15029. code = _length_code[lc];
  15030. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  15031. extra = extra_lbits[code];
  15032. if (extra !== 0) {
  15033. lc -= base_length[code];
  15034. send_bits(s, lc, extra); /* send the extra length bits */
  15035. }
  15036. dist--; /* dist is now the match distance - 1 */
  15037. code = d_code(dist);
  15038. //Assert (code < D_CODES, "bad d_code");
  15039. send_code(s, code, dtree); /* send the distance code */
  15040. extra = extra_dbits[code];
  15041. if (extra !== 0) {
  15042. dist -= base_dist[code];
  15043. send_bits(s, dist, extra); /* send the extra distance bits */
  15044. }
  15045. } /* literal or match pair ? */
  15046. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  15047. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  15048. // "pendingBuf overflow");
  15049. } while (lx < s.last_lit);
  15050. }
  15051. send_code(s, END_BLOCK, ltree);
  15052. }
  15053. /* ===========================================================================
  15054. * Construct one Huffman tree and assigns the code bit strings and lengths.
  15055. * Update the total bit length for the current block.
  15056. * IN assertion: the field freq is set for all tree elements.
  15057. * OUT assertions: the fields len and code are set to the optimal bit length
  15058. * and corresponding code. The length opt_len is updated; static_len is
  15059. * also updated if stree is not null. The field max_code is set.
  15060. */
  15061. function build_tree(s, desc)
  15062. // deflate_state *s;
  15063. // tree_desc *desc; /* the tree descriptor */
  15064. {
  15065. var tree = desc.dyn_tree;
  15066. var stree = desc.stat_desc.static_tree;
  15067. var has_stree = desc.stat_desc.has_stree;
  15068. var elems = desc.stat_desc.elems;
  15069. var n, m; /* iterate over heap elements */
  15070. var max_code = -1; /* largest code with non zero frequency */
  15071. var node; /* new node being created */
  15072. /* Construct the initial heap, with least frequent element in
  15073. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  15074. * heap[0] is not used.
  15075. */
  15076. s.heap_len = 0;
  15077. s.heap_max = HEAP_SIZE;
  15078. for (n = 0; n < elems; n++) {
  15079. if (tree[n * 2]/*.Freq*/ !== 0) {
  15080. s.heap[++s.heap_len] = max_code = n;
  15081. s.depth[n] = 0;
  15082. } else {
  15083. tree[n*2 + 1]/*.Len*/ = 0;
  15084. }
  15085. }
  15086. /* The pkzip format requires that at least one distance code exists,
  15087. * and that at least one bit should be sent even if there is only one
  15088. * possible code. So to avoid special checks later on we force at least
  15089. * two codes of non zero frequency.
  15090. */
  15091. while (s.heap_len < 2) {
  15092. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  15093. tree[node * 2]/*.Freq*/ = 1;
  15094. s.depth[node] = 0;
  15095. s.opt_len--;
  15096. if (has_stree) {
  15097. s.static_len -= stree[node*2 + 1]/*.Len*/;
  15098. }
  15099. /* node is 0 or 1 so it does not have extra bits */
  15100. }
  15101. desc.max_code = max_code;
  15102. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  15103. * establish sub-heaps of increasing lengths:
  15104. */
  15105. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  15106. /* Construct the Huffman tree by repeatedly combining the least two
  15107. * frequent nodes.
  15108. */
  15109. node = elems; /* next internal node of the tree */
  15110. do {
  15111. //pqremove(s, tree, n); /* n = node of least frequency */
  15112. /*** pqremove ***/
  15113. n = s.heap[1/*SMALLEST*/];
  15114. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  15115. pqdownheap(s, tree, 1/*SMALLEST*/);
  15116. /***/
  15117. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  15118. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  15119. s.heap[--s.heap_max] = m;
  15120. /* Create a new node father of n and m */
  15121. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  15122. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  15123. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  15124. /* and insert the new node in the heap */
  15125. s.heap[1/*SMALLEST*/] = node++;
  15126. pqdownheap(s, tree, 1/*SMALLEST*/);
  15127. } while (s.heap_len >= 2);
  15128. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  15129. /* At this point, the fields freq and dad are set. We can now
  15130. * generate the bit lengths.
  15131. */
  15132. gen_bitlen(s, desc);
  15133. /* The field len is now set, we can generate the bit codes */
  15134. gen_codes(tree, max_code, s.bl_count);
  15135. }
  15136. /* ===========================================================================
  15137. * Scan a literal or distance tree to determine the frequencies of the codes
  15138. * in the bit length tree.
  15139. */
  15140. function scan_tree(s, tree, max_code)
  15141. // deflate_state *s;
  15142. // ct_data *tree; /* the tree to be scanned */
  15143. // int max_code; /* and its largest code of non zero frequency */
  15144. {
  15145. var n; /* iterates over all tree elements */
  15146. var prevlen = -1; /* last emitted length */
  15147. var curlen; /* length of current code */
  15148. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  15149. var count = 0; /* repeat count of the current code */
  15150. var max_count = 7; /* max repeat count */
  15151. var min_count = 4; /* min repeat count */
  15152. if (nextlen === 0) {
  15153. max_count = 138;
  15154. min_count = 3;
  15155. }
  15156. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  15157. for (n = 0; n <= max_code; n++) {
  15158. curlen = nextlen;
  15159. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  15160. if (++count < max_count && curlen === nextlen) {
  15161. continue;
  15162. } else if (count < min_count) {
  15163. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  15164. } else if (curlen !== 0) {
  15165. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  15166. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  15167. } else if (count <= 10) {
  15168. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  15169. } else {
  15170. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  15171. }
  15172. count = 0;
  15173. prevlen = curlen;
  15174. if (nextlen === 0) {
  15175. max_count = 138;
  15176. min_count = 3;
  15177. } else if (curlen === nextlen) {
  15178. max_count = 6;
  15179. min_count = 3;
  15180. } else {
  15181. max_count = 7;
  15182. min_count = 4;
  15183. }
  15184. }
  15185. }
  15186. /* ===========================================================================
  15187. * Send a literal or distance tree in compressed form, using the codes in
  15188. * bl_tree.
  15189. */
  15190. function send_tree(s, tree, max_code)
  15191. // deflate_state *s;
  15192. // ct_data *tree; /* the tree to be scanned */
  15193. // int max_code; /* and its largest code of non zero frequency */
  15194. {
  15195. var n; /* iterates over all tree elements */
  15196. var prevlen = -1; /* last emitted length */
  15197. var curlen; /* length of current code */
  15198. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  15199. var count = 0; /* repeat count of the current code */
  15200. var max_count = 7; /* max repeat count */
  15201. var min_count = 4; /* min repeat count */
  15202. /* tree[max_code+1].Len = -1; */ /* guard already set */
  15203. if (nextlen === 0) {
  15204. max_count = 138;
  15205. min_count = 3;
  15206. }
  15207. for (n = 0; n <= max_code; n++) {
  15208. curlen = nextlen;
  15209. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  15210. if (++count < max_count && curlen === nextlen) {
  15211. continue;
  15212. } else if (count < min_count) {
  15213. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  15214. } else if (curlen !== 0) {
  15215. if (curlen !== prevlen) {
  15216. send_code(s, curlen, s.bl_tree);
  15217. count--;
  15218. }
  15219. //Assert(count >= 3 && count <= 6, " 3_6?");
  15220. send_code(s, REP_3_6, s.bl_tree);
  15221. send_bits(s, count-3, 2);
  15222. } else if (count <= 10) {
  15223. send_code(s, REPZ_3_10, s.bl_tree);
  15224. send_bits(s, count-3, 3);
  15225. } else {
  15226. send_code(s, REPZ_11_138, s.bl_tree);
  15227. send_bits(s, count-11, 7);
  15228. }
  15229. count = 0;
  15230. prevlen = curlen;
  15231. if (nextlen === 0) {
  15232. max_count = 138;
  15233. min_count = 3;
  15234. } else if (curlen === nextlen) {
  15235. max_count = 6;
  15236. min_count = 3;
  15237. } else {
  15238. max_count = 7;
  15239. min_count = 4;
  15240. }
  15241. }
  15242. }
  15243. /* ===========================================================================
  15244. * Construct the Huffman tree for the bit lengths and return the index in
  15245. * bl_order of the last bit length code to send.
  15246. */
  15247. function build_bl_tree(s) {
  15248. var max_blindex; /* index of last bit length code of non zero freq */
  15249. /* Determine the bit length frequencies for literal and distance trees */
  15250. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  15251. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  15252. /* Build the bit length tree: */
  15253. build_tree(s, s.bl_desc);
  15254. /* opt_len now includes the length of the tree representations, except
  15255. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  15256. */
  15257. /* Determine the number of bit length codes to send. The pkzip format
  15258. * requires that at least 4 bit length codes be sent. (appnote.txt says
  15259. * 3 but the actual value used is 4.)
  15260. */
  15261. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  15262. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  15263. break;
  15264. }
  15265. }
  15266. /* Update opt_len to include the bit length tree and counts */
  15267. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  15268. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  15269. // s->opt_len, s->static_len));
  15270. return max_blindex;
  15271. }
  15272. /* ===========================================================================
  15273. * Send the header for a block using dynamic Huffman trees: the counts, the
  15274. * lengths of the bit length codes, the literal tree and the distance tree.
  15275. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  15276. */
  15277. function send_all_trees(s, lcodes, dcodes, blcodes)
  15278. // deflate_state *s;
  15279. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  15280. {
  15281. var rank; /* index in bl_order */
  15282. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  15283. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  15284. // "too many codes");
  15285. //Tracev((stderr, "\nbl counts: "));
  15286. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  15287. send_bits(s, dcodes-1, 5);
  15288. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  15289. for (rank = 0; rank < blcodes; rank++) {
  15290. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  15291. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  15292. }
  15293. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  15294. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  15295. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  15296. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  15297. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  15298. }
  15299. /* ===========================================================================
  15300. * Check if the data type is TEXT or BINARY, using the following algorithm:
  15301. * - TEXT if the two conditions below are satisfied:
  15302. * a) There are no non-portable control characters belonging to the
  15303. * "black list" (0..6, 14..25, 28..31).
  15304. * b) There is at least one printable character belonging to the
  15305. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  15306. * - BINARY otherwise.
  15307. * - The following partially-portable control characters form a
  15308. * "gray list" that is ignored in this detection algorithm:
  15309. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  15310. * IN assertion: the fields Freq of dyn_ltree are set.
  15311. */
  15312. function detect_data_type(s) {
  15313. /* black_mask is the bit mask of black-listed bytes
  15314. * set bits 0..6, 14..25, and 28..31
  15315. * 0xf3ffc07f = binary 11110011111111111100000001111111
  15316. */
  15317. var black_mask = 0xf3ffc07f;
  15318. var n;
  15319. /* Check for non-textual ("black-listed") bytes. */
  15320. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  15321. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  15322. return Z_BINARY;
  15323. }
  15324. }
  15325. /* Check for textual ("white-listed") bytes. */
  15326. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  15327. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  15328. return Z_TEXT;
  15329. }
  15330. for (n = 32; n < LITERALS; n++) {
  15331. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  15332. return Z_TEXT;
  15333. }
  15334. }
  15335. /* There are no "black-listed" or "white-listed" bytes:
  15336. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  15337. */
  15338. return Z_BINARY;
  15339. }
  15340. var static_init_done = false;
  15341. /* ===========================================================================
  15342. * Initialize the tree data structures for a new zlib stream.
  15343. */
  15344. function _tr_init(s)
  15345. {
  15346. if (!static_init_done) {
  15347. tr_static_init();
  15348. static_init_done = true;
  15349. }
  15350. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  15351. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  15352. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  15353. s.bi_buf = 0;
  15354. s.bi_valid = 0;
  15355. /* Initialize the first block of the first file: */
  15356. init_block(s);
  15357. }
  15358. /* ===========================================================================
  15359. * Send a stored block
  15360. */
  15361. function _tr_stored_block(s, buf, stored_len, last)
  15362. //DeflateState *s;
  15363. //charf *buf; /* input block */
  15364. //ulg stored_len; /* length of input block */
  15365. //int last; /* one if this is the last block for a file */
  15366. {
  15367. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  15368. copy_block(s, buf, stored_len, true); /* with header */
  15369. }
  15370. /* ===========================================================================
  15371. * Send one empty static block to give enough lookahead for inflate.
  15372. * This takes 10 bits, of which 7 may remain in the bit buffer.
  15373. */
  15374. function _tr_align(s) {
  15375. send_bits(s, STATIC_TREES<<1, 3);
  15376. send_code(s, END_BLOCK, static_ltree);
  15377. bi_flush(s);
  15378. }
  15379. /* ===========================================================================
  15380. * Determine the best encoding for the current block: dynamic trees, static
  15381. * trees or store, and output the encoded block to the zip file.
  15382. */
  15383. function _tr_flush_block(s, buf, stored_len, last)
  15384. //DeflateState *s;
  15385. //charf *buf; /* input block, or NULL if too old */
  15386. //ulg stored_len; /* length of input block */
  15387. //int last; /* one if this is the last block for a file */
  15388. {
  15389. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  15390. var max_blindex = 0; /* index of last bit length code of non zero freq */
  15391. /* Build the Huffman trees unless a stored block is forced */
  15392. if (s.level > 0) {
  15393. /* Check if the file is binary or text */
  15394. if (s.strm.data_type === Z_UNKNOWN) {
  15395. s.strm.data_type = detect_data_type(s);
  15396. }
  15397. /* Construct the literal and distance trees */
  15398. build_tree(s, s.l_desc);
  15399. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  15400. // s->static_len));
  15401. build_tree(s, s.d_desc);
  15402. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  15403. // s->static_len));
  15404. /* At this point, opt_len and static_len are the total bit lengths of
  15405. * the compressed block data, excluding the tree representations.
  15406. */
  15407. /* Build the bit length tree for the above two trees, and get the index
  15408. * in bl_order of the last bit length code to send.
  15409. */
  15410. max_blindex = build_bl_tree(s);
  15411. /* Determine the best encoding. Compute the block lengths in bytes. */
  15412. opt_lenb = (s.opt_len+3+7) >>> 3;
  15413. static_lenb = (s.static_len+3+7) >>> 3;
  15414. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  15415. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  15416. // s->last_lit));
  15417. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  15418. } else {
  15419. // Assert(buf != (char*)0, "lost buf");
  15420. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  15421. }
  15422. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  15423. /* 4: two words for the lengths */
  15424. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  15425. * Otherwise we can't have processed more than WSIZE input bytes since
  15426. * the last block flush, because compression would have been
  15427. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  15428. * transform a block into a stored block.
  15429. */
  15430. _tr_stored_block(s, buf, stored_len, last);
  15431. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  15432. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  15433. compress_block(s, static_ltree, static_dtree);
  15434. } else {
  15435. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  15436. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  15437. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  15438. }
  15439. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  15440. /* The above check is made mod 2^32, for files larger than 512 MB
  15441. * and uLong implemented on 32 bits.
  15442. */
  15443. init_block(s);
  15444. if (last) {
  15445. bi_windup(s);
  15446. }
  15447. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  15448. // s->compressed_len-7*last));
  15449. }
  15450. /* ===========================================================================
  15451. * Save the match info and tally the frequency counts. Return true if
  15452. * the current block must be flushed.
  15453. */
  15454. function _tr_tally(s, dist, lc)
  15455. // deflate_state *s;
  15456. // unsigned dist; /* distance of matched string */
  15457. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  15458. {
  15459. //var out_length, in_length, dcode;
  15460. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  15461. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  15462. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  15463. s.last_lit++;
  15464. if (dist === 0) {
  15465. /* lc is the unmatched char */
  15466. s.dyn_ltree[lc*2]/*.Freq*/++;
  15467. } else {
  15468. s.matches++;
  15469. /* Here, lc is the match length - MIN_MATCH */
  15470. dist--; /* dist = match distance - 1 */
  15471. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  15472. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  15473. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  15474. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  15475. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  15476. }
  15477. // (!) This block is disabled in zlib defailts,
  15478. // don't enable it for binary compatibility
  15479. //#ifdef TRUNCATE_BLOCK
  15480. // /* Try to guess if it is profitable to stop the current block here */
  15481. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  15482. // /* Compute an upper bound for the compressed length */
  15483. // out_length = s.last_lit*8;
  15484. // in_length = s.strstart - s.block_start;
  15485. //
  15486. // for (dcode = 0; dcode < D_CODES; dcode++) {
  15487. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  15488. // }
  15489. // out_length >>>= 3;
  15490. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  15491. // // s->last_lit, in_length, out_length,
  15492. // // 100L - out_length*100L/in_length));
  15493. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  15494. // return true;
  15495. // }
  15496. // }
  15497. //#endif
  15498. return (s.last_lit === s.lit_bufsize-1);
  15499. /* We avoid equality with lit_bufsize because of wraparound at 64K
  15500. * on 16 bit machines and because stored blocks are restricted to
  15501. * 64K-1 bytes.
  15502. */
  15503. }
  15504. exports._tr_init = _tr_init;
  15505. exports._tr_stored_block = _tr_stored_block;
  15506. exports._tr_flush_block = _tr_flush_block;
  15507. exports._tr_tally = _tr_tally;
  15508. exports._tr_align = _tr_align;
  15509. },{"../utils/common":38}],50:[function(require,module,exports){
  15510. 'use strict';
  15511. function ZStream() {
  15512. /* next input byte */
  15513. this.input = null; // JS specific, because we have no pointers
  15514. this.next_in = 0;
  15515. /* number of bytes available at input */
  15516. this.avail_in = 0;
  15517. /* total number of input bytes read so far */
  15518. this.total_in = 0;
  15519. /* next output byte should be put there */
  15520. this.output = null; // JS specific, because we have no pointers
  15521. this.next_out = 0;
  15522. /* remaining free space at output */
  15523. this.avail_out = 0;
  15524. /* total number of bytes output so far */
  15525. this.total_out = 0;
  15526. /* last error message, NULL if no error */
  15527. this.msg = ''/*Z_NULL*/;
  15528. /* not visible by applications */
  15529. this.state = null;
  15530. /* best guess about the data type: binary or text */
  15531. this.data_type = 2/*Z_UNKNOWN*/;
  15532. /* adler32 value of the uncompressed data */
  15533. this.adler = 0;
  15534. }
  15535. module.exports = ZStream;
  15536. },{}],51:[function(require,module,exports){
  15537. module.exports = function arrayEquals(array) {
  15538. // if the other array is a falsy value, return
  15539. if (!array)
  15540. return false;
  15541. // compare lengths - can save a lot of time
  15542. if (this.length != array.length)
  15543. return false;
  15544. for (var i = 0, l = this.length; i < l; i++) {
  15545. // Check if we have nested arrays
  15546. if (this[i] instanceof Array && array[i] instanceof Array) {
  15547. // recurse into the nested arrays
  15548. if (!arrayEquals.apply(this[i], [array[i]]))
  15549. return false;
  15550. } else if (this[i] != array[i]) {
  15551. // Warning - two different object instances will never be equal:
  15552. // {x:20} != {x:20}
  15553. return false;
  15554. }
  15555. }
  15556. return true;
  15557. }
  15558. },{}],52:[function(require,module,exports){
  15559. exports.Interop = require('./interop');
  15560. },{"./interop":53}],53:[function(require,module,exports){
  15561. "use strict";
  15562. var transform = require('./transform');
  15563. var arrayEquals = require('./array-equals');
  15564. function Interop() {
  15565. /**
  15566. * This map holds the most recent Unified Plan offer/answer SDP that was
  15567. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  15568. * the SDP string as values.
  15569. *
  15570. * @type {{}}
  15571. */
  15572. this.cache = {};
  15573. }
  15574. module.exports = Interop;
  15575. /**
  15576. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  15577. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  15578. * application.
  15579. *
  15580. * @param desc
  15581. * @returns {*}
  15582. */
  15583. Interop.prototype.toPlanB = function(desc) {
  15584. //#region Preliminary input validation.
  15585. if (typeof desc !== 'object' || desc === null ||
  15586. typeof desc.sdp !== 'string') {
  15587. console.warn('An empty description was passed as an argument.');
  15588. return desc;
  15589. }
  15590. // Objectify the SDP for easier manipulation.
  15591. var session = transform.parse(desc.sdp);
  15592. // If the SDP contains no media, there's nothing to transform.
  15593. if (typeof session.media === 'undefined' ||
  15594. !Array.isArray(session.media) || session.media.length === 0) {
  15595. console.warn('The description has no media.');
  15596. return desc;
  15597. }
  15598. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  15599. // SDP has a video, an audio and a data "channel" at most.
  15600. if (session.media.length <= 3 && session.media.every(function(m) {
  15601. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  15602. })) {
  15603. console.warn('This description does not look like Unified Plan.');
  15604. return desc;
  15605. }
  15606. //#endregion
  15607. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  15608. // -> Unified Plan transformation.
  15609. this.cache[desc.type] = desc.sdp;
  15610. //#region Convert from Unified Plan to Plan B.
  15611. // We rebuild the session.media array.
  15612. var media = session.media;
  15613. session.media = [];
  15614. // Associative array that maps channel types to channel objects for fast
  15615. // access to channel objects by their type, e.g. type2bl['audio']->channel
  15616. // obj.
  15617. var type2bl = {};
  15618. // Used to build the group:BUNDLE value after the channels construction
  15619. // loop.
  15620. var types = [];
  15621. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  15622. media.forEach(function(unifiedLine) {
  15623. // rtcp-mux is required in the Plan B SDP.
  15624. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  15625. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  15626. unifiedLine.direction !== 'inactive') {
  15627. throw new Error('Cannot convert to Plan B because m-lines ' +
  15628. 'without the rtcp-mux attribute were found.');
  15629. }
  15630. if (unifiedLine.type === 'application') {
  15631. session.media.push(unifiedLine);
  15632. types.push(unifiedLine.mid);
  15633. return;
  15634. }
  15635. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  15636. // as the channel basis.
  15637. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  15638. type2bl[unifiedLine.type] = unifiedLine;
  15639. }
  15640. // Add sources to the channel and handle a=msid.
  15641. if (typeof unifiedLine.sources === 'object') {
  15642. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  15643. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  15644. type2bl[unifiedLine.type].sources = {};
  15645. // Assign the sources to the channel.
  15646. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  15647. if (typeof unifiedLine.msid !== 'undefined') {
  15648. // In Plan B the msid is an SSRC attribute. Also, we don't
  15649. // care about the obsolete label and mslabel attributes.
  15650. //
  15651. // Note that it is not guaranteed that the unifiedLine will have
  15652. // an msid. recvonly channels in particular don't have one.
  15653. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  15654. }
  15655. // NOTE ssrcs in ssrc groups will share msids, as
  15656. // draft-uberti-rtcweb-plan-00 mandates.
  15657. });
  15658. }
  15659. // Add ssrc groups to the channel.
  15660. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  15661. Array.isArray(unifiedLine.ssrcGroups)) {
  15662. // Create the ssrcGroups array, if it's not defined.
  15663. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  15664. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  15665. type2bl[unifiedLine.type].ssrcGroups = [];
  15666. }
  15667. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  15668. }
  15669. if (type2bl[unifiedLine.type] === unifiedLine) {
  15670. // Copy ICE related stuff from the principal media line.
  15671. unifiedLine.candidates = media[0].candidates;
  15672. unifiedLine.iceUfrag = media[0].iceUfrag;
  15673. unifiedLine.icePwd = media[0].icePwd;
  15674. unifiedLine.fingerprint = media[0].fingerprint;
  15675. // Plan B mids are in ['audio', 'video', 'data']
  15676. unifiedLine.mid = unifiedLine.type;
  15677. // Plan B doesn't support/need the bundle-only attribute.
  15678. delete unifiedLine.bundleOnly;
  15679. // In Plan B the msid is an SSRC attribute.
  15680. delete unifiedLine.msid;
  15681. // Used to build the group:BUNDLE value after this loop.
  15682. types.push(unifiedLine.type);
  15683. // Add the channel to the new media array.
  15684. session.media.push(unifiedLine);
  15685. }
  15686. });
  15687. // We regenerate the BUNDLE group with the new mids.
  15688. session.groups.some(function(group) {
  15689. if (group.type === 'BUNDLE') {
  15690. group.mids = types.join(' ');
  15691. return true;
  15692. }
  15693. });
  15694. // msid semantic
  15695. session.msidSemantic = {
  15696. semantic: 'WMS',
  15697. token: '*'
  15698. };
  15699. var resStr = transform.write(session);
  15700. return new RTCSessionDescription({
  15701. type: desc.type,
  15702. sdp: resStr
  15703. });
  15704. //#endregion
  15705. };
  15706. /**
  15707. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  15708. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  15709. * to FF.
  15710. *
  15711. * @param desc
  15712. * @returns {*}
  15713. */
  15714. Interop.prototype.toUnifiedPlan = function(desc) {
  15715. //#region Preliminary input validation.
  15716. if (typeof desc !== 'object' || desc === null ||
  15717. typeof desc.sdp !== 'string') {
  15718. console.warn('An empty description was passed as an argument.');
  15719. return desc;
  15720. }
  15721. var session = transform.parse(desc.sdp);
  15722. // If the SDP contains no media, there's nothing to transform.
  15723. if (typeof session.media === 'undefined' ||
  15724. !Array.isArray(session.media) || session.media.length === 0) {
  15725. console.warn('The description has no media.');
  15726. return desc;
  15727. }
  15728. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  15729. // a video, an audio and a data "channel" at most.
  15730. if (session.media.length > 3 || !session.media.every(function(m) {
  15731. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  15732. })) {
  15733. console.warn('This description does not look like Plan B.');
  15734. return desc;
  15735. }
  15736. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  15737. var mids = [];
  15738. session.media.forEach(function(m) {
  15739. mids.push(m.mid);
  15740. });
  15741. var hasBundle = false;
  15742. if (typeof session.groups !== 'undefined' &&
  15743. Array.isArray(session.groups)) {
  15744. hasBundle = session.groups.every(function(g) {
  15745. return g.type !== 'BUNDLE' ||
  15746. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  15747. });
  15748. }
  15749. if (!hasBundle) {
  15750. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  15751. " are not bundled were found.");
  15752. }
  15753. //#endregion
  15754. //#region Convert from Plan B to Unified Plan.
  15755. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  15756. // rebuild an equivalent Unified Plan offer/answer.
  15757. //
  15758. // For example, if this is a local answer (in Unified Plan style) that we
  15759. // convert to Plan B prior to handing it over to the application (the
  15760. // PeerConnection wrapper called us, for instance, after a successful
  15761. // createAnswer), we want to remember the m-line at which we've seen the
  15762. // (local) SSRC. That's because when the application wants to do call the
  15763. // SLD method, forcing us to do the inverse transformation (from Plan B to
  15764. // Unified Plan), we need to know to which m-line to assign the (local)
  15765. // SSRC. We also need to know all the other m-lines that the original
  15766. // answer had and include them in the transformed answer as well.
  15767. //
  15768. // Another example is if this is a remote offer that we convert to Plan B
  15769. // prior to giving it to the application, we want to remember the mid at
  15770. // which we've seen the (remote) SSRC.
  15771. //
  15772. // In the iteration that follows, we use the cached Unified Plan (if it
  15773. // exists) to assign mids to ssrcs.
  15774. var cached;
  15775. if (typeof this.cache[desc.type] !== 'undefined') {
  15776. cached = transform.parse(this.cache[desc.type]);
  15777. }
  15778. // A helper map that sends mids to m-line objects. We use it later to
  15779. // rebuild the Unified Plan style session.media array.
  15780. var mid2ul = {};
  15781. session.media.forEach(function(bLine) {
  15782. if ((typeof bLine.rtcpMux !== 'string' ||
  15783. bLine.rtcpMux !== 'rtcp-mux') &&
  15784. bLine.direction !== 'inactive') {
  15785. throw new Error("Cannot convert to Unified Plan because m-lines " +
  15786. "without the rtcp-mux attribute were found.");
  15787. }
  15788. if (bLine.type === 'application') {
  15789. mid2ul[bLine.mid] = bLine;
  15790. return;
  15791. }
  15792. // With rtcp-mux and bundle all the channels should have the same ICE
  15793. // stuff.
  15794. var sources = bLine.sources;
  15795. var ssrcGroups = bLine.ssrcGroups;
  15796. var candidates = bLine.candidates;
  15797. var iceUfrag = bLine.iceUfrag;
  15798. var icePwd = bLine.icePwd;
  15799. var fingerprint = bLine.fingerprint;
  15800. var port = bLine.port;
  15801. // We'll use the "bLine" object as a prototype for each new "mLine"
  15802. // that we create, but first we need to clean it up a bit.
  15803. delete bLine.sources;
  15804. delete bLine.ssrcGroups;
  15805. delete bLine.candidates;
  15806. delete bLine.iceUfrag;
  15807. delete bLine.icePwd;
  15808. delete bLine.fingerprint;
  15809. delete bLine.port;
  15810. delete bLine.mid;
  15811. // inverted ssrc group map
  15812. var ssrc2group = {};
  15813. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  15814. ssrcGroups.forEach(function (ssrcGroup) {
  15815. // TODO(gp) find out how to receive simulcast with FF. For the
  15816. // time being, hide it.
  15817. if (ssrcGroup.semantics === 'SIM') {
  15818. return;
  15819. }
  15820. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  15821. Array.isArray(ssrcGroup.ssrcs)) {
  15822. ssrcGroup.ssrcs.forEach(function (ssrc) {
  15823. if (typeof ssrc2group[ssrc] === 'undefined') {
  15824. ssrc2group[ssrc] = [];
  15825. }
  15826. ssrc2group[ssrc].push(ssrcGroup);
  15827. });
  15828. }
  15829. });
  15830. }
  15831. // ssrc to m-line index.
  15832. var ssrc2ml = {};
  15833. if (typeof sources === 'object') {
  15834. // Explode the Plan B channel sources with one m-line per source.
  15835. Object.keys(sources).forEach(function(ssrc) {
  15836. // The (unified) m-line for this SSRC. We either create it from
  15837. // scratch or, if it's a grouped SSRC, we re-use a related
  15838. // mline. In other words, if the source is grouped with another
  15839. // source, put the two together in the same m-line.
  15840. var unifiedLine;
  15841. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  15842. Array.isArray(ssrc2group[ssrc])) {
  15843. ssrc2group[ssrc].some(function (ssrcGroup) {
  15844. // ssrcGroup.ssrcs *is* an Array, no need to check
  15845. // again here.
  15846. return ssrcGroup.ssrcs.some(function (related) {
  15847. if (typeof ssrc2ml[related] === 'object') {
  15848. unifiedLine = ssrc2ml[related];
  15849. return true;
  15850. }
  15851. });
  15852. });
  15853. }
  15854. if (typeof unifiedLine === 'object') {
  15855. // the m-line already exists. Just add the source.
  15856. unifiedLine.sources[ssrc] = sources[ssrc];
  15857. delete sources[ssrc].msid;
  15858. } else {
  15859. // Use the "bLine" as a prototype for the "unifiedLine".
  15860. unifiedLine = Object.create(bLine);
  15861. ssrc2ml[ssrc] = unifiedLine;
  15862. if (typeof sources[ssrc].msid !== 'undefined') {
  15863. // Assign the msid of the source to the m-line. Note
  15864. // that it is not guaranteed that the source will have
  15865. // msid. In particular "recvonly" sources don't have an
  15866. // msid. Note that "recvonly" is a term only defined
  15867. // for m-lines.
  15868. unifiedLine.msid = sources[ssrc].msid;
  15869. delete sources[ssrc].msid;
  15870. }
  15871. // We assign one SSRC per media line.
  15872. unifiedLine.sources = {};
  15873. unifiedLine.sources[ssrc] = sources[ssrc];
  15874. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  15875. // Use the cached Unified Plan SDP (if it exists) to assign
  15876. // SSRCs to mids.
  15877. if (typeof cached !== 'undefined' &&
  15878. typeof cached.media !== 'undefined' &&
  15879. Array.isArray(cached.media)) {
  15880. cached.media.forEach(function (m) {
  15881. if (typeof m.sources === 'object') {
  15882. Object.keys(m.sources).forEach(function (s) {
  15883. if (s === ssrc) {
  15884. unifiedLine.mid = m.mid;
  15885. }
  15886. });
  15887. }
  15888. });
  15889. }
  15890. if (typeof unifiedLine.mid === 'undefined') {
  15891. // If this is an SSRC that we see for the first time
  15892. // assign it a new mid. This is typically the case when
  15893. // this method is called to transform a remote
  15894. // description for the first time or when there is a
  15895. // new SSRC in the remote description because a new
  15896. // peer has joined the conference. Local SSRCs should
  15897. // have already been added to the map in the toPlanB
  15898. // method.
  15899. //
  15900. // Because FF generates answers in Unified Plan style,
  15901. // we MUST already have a cached answer with all the
  15902. // local SSRCs mapped to some m-line/mid.
  15903. if (desc.type === 'answer') {
  15904. throw new Error("An unmapped SSRC was found.");
  15905. }
  15906. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  15907. }
  15908. // Include the candidates in the 1st media line.
  15909. unifiedLine.candidates = candidates;
  15910. unifiedLine.iceUfrag = iceUfrag;
  15911. unifiedLine.icePwd = icePwd;
  15912. unifiedLine.fingerprint = fingerprint;
  15913. unifiedLine.port = port;
  15914. mid2ul[unifiedLine.mid] = unifiedLine;
  15915. }
  15916. });
  15917. }
  15918. });
  15919. // Rebuild the media array in the right order and add the missing mLines
  15920. // (missing from the Plan B SDP).
  15921. session.media = [];
  15922. mids = []; // reuse
  15923. if (desc.type === 'answer') {
  15924. // The media lines in the answer must match the media lines in the
  15925. // offer. The order is important too. Here we assume that Firefox is the
  15926. // answerer, so we merely have to use the reconstructed (unified) answer
  15927. // to update the cached (unified) answer accordingly.
  15928. //
  15929. // In the general case, one would have to use the cached (unified) offer
  15930. // to find the m-lines that are missing from the reconstructed answer,
  15931. // potentially grabbing them from the cached (unified) answer. One has
  15932. // to be carefull with this approach because inactive m-lines do not
  15933. // always have an mid, making it tricky (impossible?) to find where
  15934. // exactly and which m-lines are missing from the reconstructed answer.
  15935. for (var i = 0; i < cached.media.length; i++) {
  15936. var unifiedLine = cached.media[i];
  15937. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  15938. // The mid isn't in the reconstructed (unified) answer.
  15939. // This is either a (unified) m-line containing a remote
  15940. // track only, or a (unified) m-line containing a remote
  15941. // track and a local track that has been removed.
  15942. // In either case, it MUST exist in the cached
  15943. // (unified) answer.
  15944. //
  15945. // In case this is a removed local track, clean-up
  15946. // the (unified) m-line and make sure it's 'recvonly' or
  15947. // 'inactive'.
  15948. delete unifiedLine.msid;
  15949. delete unifiedLine.sources;
  15950. delete unifiedLine.ssrcGroups;
  15951. if (!unifiedLine.direction
  15952. || unifiedLine.direction === 'sendrecv')
  15953. unifiedLine.direction = 'recvonly';
  15954. if (!unifiedLine.direction
  15955. || unifiedLine.direction === 'sendonly')
  15956. unifiedLine.direction = 'inactive';
  15957. } else {
  15958. // This is an (unified) m-line/channel that contains a local
  15959. // track (sendrecv or sendonly channel) or it's a unified
  15960. // recvonly m-line/channel. In either case, since we're
  15961. // going from PlanB -> Unified Plan this m-line MUST
  15962. // exist in the cached answer.
  15963. }
  15964. session.media.push(unifiedLine);
  15965. if (typeof unifiedLine.mid === 'string') {
  15966. // inactive lines don't/may not have an mid.
  15967. mids.push(unifiedLine.mid);
  15968. }
  15969. }
  15970. } else {
  15971. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  15972. // under any circumstances. If we are no longer interested in sending a
  15973. // track, we just remove the msid and ssrc attributes and set it to
  15974. // either a=recvonly (as the reofferer, we must use recvonly if the
  15975. // other side was previously sending on the m-section, but we can also
  15976. // leave the possibility open if it wasn't previously in use), or
  15977. // a=inacive.
  15978. if (typeof cached !== 'undefined' &&
  15979. typeof cached.media !== 'undefined' &&
  15980. Array.isArray(cached.media)) {
  15981. cached.media.forEach(function(unifiedLine) {
  15982. mids.push(unifiedLine.mid);
  15983. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  15984. session.media.push(mid2ul[unifiedLine.mid]);
  15985. } else {
  15986. delete unifiedLine.msid;
  15987. delete unifiedLine.sources;
  15988. delete unifiedLine.ssrcGroups;
  15989. if (!unifiedLine.direction
  15990. || unifiedLine.direction === 'sendrecv')
  15991. unifiedLine.direction = 'recvonly';
  15992. if (!unifiedLine.direction
  15993. || unifiedLine.direction === 'sendonly')
  15994. unifiedLine.direction = 'inactive';
  15995. session.media.push(unifiedLine);
  15996. }
  15997. });
  15998. }
  15999. // Add all the remaining (new) m-lines of the transformed SDP.
  16000. Object.keys(mid2ul).forEach(function(mid) {
  16001. if (mids.indexOf(mid) === -1) {
  16002. mids.push(mid);
  16003. if (typeof mid2ul[mid].direction === 'recvonly') {
  16004. // This is a remote recvonly channel. Add its SSRC to the
  16005. // appropriate sendrecv or sendonly channel.
  16006. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  16007. session.media.some(function (unifiedLine) {
  16008. if ((unifiedLine.direction === 'sendrecv' ||
  16009. unifiedLine.direction === 'sendonly') &&
  16010. unifiedLine.type === mid2ul[mid].type) {
  16011. // mid2ul[mid] shouldn't have any ssrc-groups
  16012. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  16013. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  16014. });
  16015. return true;
  16016. }
  16017. });
  16018. } else {
  16019. session.media.push(mid2ul[mid]);
  16020. }
  16021. }
  16022. });
  16023. }
  16024. // We regenerate the BUNDLE group (since we regenerated the mids)
  16025. session.groups.some(function(group) {
  16026. if (group.type === 'BUNDLE') {
  16027. group.mids = mids.join(' ');
  16028. return true;
  16029. }
  16030. });
  16031. // msid semantic
  16032. session.msidSemantic = {
  16033. semantic: 'WMS',
  16034. token: '*'
  16035. };
  16036. var resStr = transform.write(session);
  16037. // Cache the transformed SDP (Unified Plan) for later re-use in this
  16038. // function.
  16039. this.cache[desc.type] = resStr;
  16040. return new RTCSessionDescription({
  16041. type: desc.type,
  16042. sdp: resStr
  16043. });
  16044. //#endregion
  16045. };
  16046. },{"./array-equals":51,"./transform":54}],54:[function(require,module,exports){
  16047. var transform = require('sdp-transform');
  16048. exports.write = function(session, opts) {
  16049. if (typeof session !== 'undefined' &&
  16050. typeof session.media !== 'undefined' &&
  16051. Array.isArray(session.media)) {
  16052. session.media.forEach(function (mLine) {
  16053. // expand sources to ssrcs
  16054. if (typeof mLine.sources !== 'undefined' &&
  16055. Object.keys(mLine.sources).length !== 0) {
  16056. mLine.ssrcs = [];
  16057. Object.keys(mLine.sources).forEach(function (ssrc) {
  16058. var source = mLine.sources[ssrc];
  16059. Object.keys(source).forEach(function (attribute) {
  16060. mLine.ssrcs.push({
  16061. id: ssrc,
  16062. attribute: attribute,
  16063. value: source[attribute]
  16064. });
  16065. });
  16066. });
  16067. delete mLine.sources;
  16068. }
  16069. // join ssrcs in ssrc groups
  16070. if (typeof mLine.ssrcGroups !== 'undefined' &&
  16071. Array.isArray(mLine.ssrcGroups)) {
  16072. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  16073. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  16074. Array.isArray(ssrcGroup.ssrcs)) {
  16075. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  16076. }
  16077. });
  16078. }
  16079. });
  16080. }
  16081. // join group mids
  16082. if (typeof session !== 'undefined' &&
  16083. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  16084. session.groups.forEach(function (g) {
  16085. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  16086. g.mids = g.mids.join(' ');
  16087. }
  16088. });
  16089. }
  16090. return transform.write(session, opts);
  16091. };
  16092. exports.parse = function(sdp) {
  16093. var session = transform.parse(sdp);
  16094. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  16095. Array.isArray(session.media)) {
  16096. session.media.forEach(function (mLine) {
  16097. // group sources attributes by ssrc
  16098. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  16099. mLine.sources = {};
  16100. mLine.ssrcs.forEach(function (ssrc) {
  16101. if (!mLine.sources[ssrc.id])
  16102. mLine.sources[ssrc.id] = {};
  16103. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  16104. });
  16105. delete mLine.ssrcs;
  16106. }
  16107. // split ssrcs in ssrc groups
  16108. if (typeof mLine.ssrcGroups !== 'undefined' &&
  16109. Array.isArray(mLine.ssrcGroups)) {
  16110. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  16111. if (typeof ssrcGroup.ssrcs === 'string') {
  16112. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  16113. }
  16114. });
  16115. }
  16116. });
  16117. }
  16118. // split group mids
  16119. if (typeof session !== 'undefined' &&
  16120. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  16121. session.groups.forEach(function (g) {
  16122. if (typeof g.mids === 'string') {
  16123. g.mids = g.mids.split(' ');
  16124. }
  16125. });
  16126. }
  16127. return session;
  16128. };
  16129. },{"sdp-transform":56}],55:[function(require,module,exports){
  16130. var grammar = module.exports = {
  16131. v: [{
  16132. name: 'version',
  16133. reg: /^(\d*)$/
  16134. }],
  16135. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  16136. // NB: sessionId will be a String in most cases because it is huge
  16137. name: 'origin',
  16138. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  16139. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  16140. format: "%s %s %d %s IP%d %s"
  16141. }],
  16142. // default parsing of these only (though some of these feel outdated)
  16143. s: [{ name: 'name' }],
  16144. i: [{ name: 'description' }],
  16145. u: [{ name: 'uri' }],
  16146. e: [{ name: 'email' }],
  16147. p: [{ name: 'phone' }],
  16148. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  16149. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  16150. //k: [{}], // outdated thing ignored
  16151. t: [{ //t=0 0
  16152. name: 'timing',
  16153. reg: /^(\d*) (\d*)/,
  16154. names: ['start', 'stop'],
  16155. format: "%d %d"
  16156. }],
  16157. c: [{ //c=IN IP4 10.47.197.26
  16158. name: 'connection',
  16159. reg: /^IN IP(\d) (\S*)/,
  16160. names: ['version', 'ip'],
  16161. format: "IN IP%d %s"
  16162. }],
  16163. b: [{ //b=AS:4000
  16164. push: 'bandwidth',
  16165. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  16166. names: ['type', 'limit'],
  16167. format: "%s:%s"
  16168. }],
  16169. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  16170. // NB: special - pushes to session
  16171. // TODO: rtp/fmtp should be filtered by the payloads found here?
  16172. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  16173. names: ['type', 'port', 'protocol', 'payloads'],
  16174. format: "%s %d %s %s"
  16175. }],
  16176. a: [
  16177. { //a=rtpmap:110 opus/48000/2
  16178. push: 'rtp',
  16179. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  16180. names: ['payload', 'codec', 'rate', 'encoding'],
  16181. format: function (o) {
  16182. return (o.encoding) ?
  16183. "rtpmap:%d %s/%s/%s":
  16184. "rtpmap:%d %s/%s";
  16185. }
  16186. },
  16187. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  16188. push: 'fmtp',
  16189. reg: /^fmtp:(\d*) (\S*)/,
  16190. names: ['payload', 'config'],
  16191. format: "fmtp:%d %s"
  16192. },
  16193. { //a=control:streamid=0
  16194. name: 'control',
  16195. reg: /^control:(.*)/,
  16196. format: "control:%s"
  16197. },
  16198. { //a=rtcp:65179 IN IP4 193.84.77.194
  16199. name: 'rtcp',
  16200. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  16201. names: ['port', 'netType', 'ipVer', 'address'],
  16202. format: function (o) {
  16203. return (o.address != null) ?
  16204. "rtcp:%d %s IP%d %s":
  16205. "rtcp:%d";
  16206. }
  16207. },
  16208. { //a=rtcp-fb:98 trr-int 100
  16209. push: 'rtcpFbTrrInt',
  16210. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  16211. names: ['payload', 'value'],
  16212. format: "rtcp-fb:%d trr-int %d"
  16213. },
  16214. { //a=rtcp-fb:98 nack rpsi
  16215. push: 'rtcpFb',
  16216. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  16217. names: ['payload', 'type', 'subtype'],
  16218. format: function (o) {
  16219. return (o.subtype != null) ?
  16220. "rtcp-fb:%s %s %s":
  16221. "rtcp-fb:%s %s";
  16222. }
  16223. },
  16224. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  16225. //a=extmap:1/recvonly URI-gps-string
  16226. push: 'ext',
  16227. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  16228. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  16229. format: function (o) {
  16230. return (o.config != null) ?
  16231. "extmap:%s %s %s":
  16232. "extmap:%s %s";
  16233. }
  16234. },
  16235. {
  16236. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  16237. push: 'crypto',
  16238. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  16239. names: ['id', 'suite', 'config', 'sessionConfig'],
  16240. format: function (o) {
  16241. return (o.sessionConfig != null) ?
  16242. "crypto:%d %s %s %s":
  16243. "crypto:%d %s %s";
  16244. }
  16245. },
  16246. { //a=setup:actpass
  16247. name: 'setup',
  16248. reg: /^setup:(\w*)/,
  16249. format: "setup:%s"
  16250. },
  16251. { //a=mid:1
  16252. name: 'mid',
  16253. reg: /^mid:([^\s]*)/,
  16254. format: "mid:%s"
  16255. },
  16256. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  16257. name: 'msid',
  16258. reg: /^msid:(.*)/,
  16259. format: "msid:%s"
  16260. },
  16261. { //a=ptime:20
  16262. name: 'ptime',
  16263. reg: /^ptime:(\d*)/,
  16264. format: "ptime:%d"
  16265. },
  16266. { //a=maxptime:60
  16267. name: 'maxptime',
  16268. reg: /^maxptime:(\d*)/,
  16269. format: "maxptime:%d"
  16270. },
  16271. { //a=sendrecv
  16272. name: 'direction',
  16273. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  16274. },
  16275. { //a=ice-lite
  16276. name: 'icelite',
  16277. reg: /^(ice-lite)/
  16278. },
  16279. { //a=ice-ufrag:F7gI
  16280. name: 'iceUfrag',
  16281. reg: /^ice-ufrag:(\S*)/,
  16282. format: "ice-ufrag:%s"
  16283. },
  16284. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  16285. name: 'icePwd',
  16286. reg: /^ice-pwd:(\S*)/,
  16287. format: "ice-pwd:%s"
  16288. },
  16289. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  16290. name: 'fingerprint',
  16291. reg: /^fingerprint:(\S*) (\S*)/,
  16292. names: ['type', 'hash'],
  16293. format: "fingerprint:%s %s"
  16294. },
  16295. {
  16296. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  16297. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  16298. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  16299. push:'candidates',
  16300. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  16301. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  16302. format: function (o) {
  16303. var str = "candidate:%s %d %s %d %s %d typ %s";
  16304. // NB: candidate has two optional chunks, so %void middle one if it's missing
  16305. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  16306. if (o.generation != null) {
  16307. str += " generation %d";
  16308. }
  16309. return str;
  16310. }
  16311. },
  16312. { //a=end-of-candidates (keep after the candidates line for readability)
  16313. name: 'endOfCandidates',
  16314. reg: /^(end-of-candidates)/
  16315. },
  16316. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  16317. name: 'remoteCandidates',
  16318. reg: /^remote-candidates:(.*)/,
  16319. format: "remote-candidates:%s"
  16320. },
  16321. { //a=ice-options:google-ice
  16322. name: 'iceOptions',
  16323. reg: /^ice-options:(\S*)/,
  16324. format: "ice-options:%s"
  16325. },
  16326. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  16327. push: "ssrcs",
  16328. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  16329. names: ['id', 'attribute', 'value'],
  16330. format: "ssrc:%d %s:%s"
  16331. },
  16332. { //a=ssrc-group:FEC 1 2
  16333. push: "ssrcGroups",
  16334. reg: /^ssrc-group:(\w*) (.*)/,
  16335. names: ['semantics', 'ssrcs'],
  16336. format: "ssrc-group:%s %s"
  16337. },
  16338. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  16339. name: "msidSemantic",
  16340. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  16341. names: ['semantic', 'token'],
  16342. format: "msid-semantic: %s %s" // space after ":" is not accidental
  16343. },
  16344. { //a=group:BUNDLE audio video
  16345. push: 'groups',
  16346. reg: /^group:(\w*) (.*)/,
  16347. names: ['type', 'mids'],
  16348. format: "group:%s %s"
  16349. },
  16350. { //a=rtcp-mux
  16351. name: 'rtcpMux',
  16352. reg: /^(rtcp-mux)/
  16353. },
  16354. { //a=rtcp-rsize
  16355. name: 'rtcpRsize',
  16356. reg: /^(rtcp-rsize)/
  16357. },
  16358. { // any a= that we don't understand is kepts verbatim on media.invalid
  16359. push: 'invalid',
  16360. names: ["value"]
  16361. }
  16362. ]
  16363. };
  16364. // set sensible defaults to avoid polluting the grammar with boring details
  16365. Object.keys(grammar).forEach(function (key) {
  16366. var objs = grammar[key];
  16367. objs.forEach(function (obj) {
  16368. if (!obj.reg) {
  16369. obj.reg = /(.*)/;
  16370. }
  16371. if (!obj.format) {
  16372. obj.format = "%s";
  16373. }
  16374. });
  16375. });
  16376. },{}],56:[function(require,module,exports){
  16377. var parser = require('./parser');
  16378. var writer = require('./writer');
  16379. exports.write = writer;
  16380. exports.parse = parser.parse;
  16381. exports.parseFmtpConfig = parser.parseFmtpConfig;
  16382. exports.parsePayloads = parser.parsePayloads;
  16383. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  16384. },{"./parser":57,"./writer":58}],57:[function(require,module,exports){
  16385. var toIntIfInt = function (v) {
  16386. return String(Number(v)) === v ? Number(v) : v;
  16387. };
  16388. var attachProperties = function (match, location, names, rawName) {
  16389. if (rawName && !names) {
  16390. location[rawName] = toIntIfInt(match[1]);
  16391. }
  16392. else {
  16393. for (var i = 0; i < names.length; i += 1) {
  16394. if (match[i+1] != null) {
  16395. location[names[i]] = toIntIfInt(match[i+1]);
  16396. }
  16397. }
  16398. }
  16399. };
  16400. var parseReg = function (obj, location, content) {
  16401. var needsBlank = obj.name && obj.names;
  16402. if (obj.push && !location[obj.push]) {
  16403. location[obj.push] = [];
  16404. }
  16405. else if (needsBlank && !location[obj.name]) {
  16406. location[obj.name] = {};
  16407. }
  16408. var keyLocation = obj.push ?
  16409. {} : // blank object that will be pushed
  16410. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  16411. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  16412. if (obj.push) {
  16413. location[obj.push].push(keyLocation);
  16414. }
  16415. };
  16416. var grammar = require('./grammar');
  16417. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  16418. exports.parse = function (sdp) {
  16419. var session = {}
  16420. , media = []
  16421. , location = session; // points at where properties go under (one of the above)
  16422. // parse lines we understand
  16423. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  16424. var type = l[0];
  16425. var content = l.slice(2);
  16426. if (type === 'm') {
  16427. media.push({rtp: [], fmtp: []});
  16428. location = media[media.length-1]; // point at latest media line
  16429. }
  16430. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  16431. var obj = grammar[type][j];
  16432. if (obj.reg.test(content)) {
  16433. return parseReg(obj, location, content);
  16434. }
  16435. }
  16436. });
  16437. session.media = media; // link it up
  16438. return session;
  16439. };
  16440. var fmtpReducer = function (acc, expr) {
  16441. var s = expr.split('=');
  16442. if (s.length === 2) {
  16443. acc[s[0]] = toIntIfInt(s[1]);
  16444. }
  16445. return acc;
  16446. };
  16447. exports.parseFmtpConfig = function (str) {
  16448. return str.split(';').reduce(fmtpReducer, {});
  16449. };
  16450. exports.parsePayloads = function (str) {
  16451. return str.split(' ').map(Number);
  16452. };
  16453. exports.parseRemoteCandidates = function (str) {
  16454. var candidates = [];
  16455. var parts = str.split(' ').map(toIntIfInt);
  16456. for (var i = 0; i < parts.length; i += 3) {
  16457. candidates.push({
  16458. component: parts[i],
  16459. ip: parts[i + 1],
  16460. port: parts[i + 2]
  16461. });
  16462. }
  16463. return candidates;
  16464. };
  16465. },{"./grammar":55}],58:[function(require,module,exports){
  16466. var grammar = require('./grammar');
  16467. // customized util.format - discards excess arguments and can void middle ones
  16468. var formatRegExp = /%[sdv%]/g;
  16469. var format = function (formatStr) {
  16470. var i = 1;
  16471. var args = arguments;
  16472. var len = args.length;
  16473. return formatStr.replace(formatRegExp, function (x) {
  16474. if (i >= len) {
  16475. return x; // missing argument
  16476. }
  16477. var arg = args[i];
  16478. i += 1;
  16479. switch (x) {
  16480. case '%%':
  16481. return '%';
  16482. case '%s':
  16483. return String(arg);
  16484. case '%d':
  16485. return Number(arg);
  16486. case '%v':
  16487. return '';
  16488. }
  16489. });
  16490. // NB: we discard excess arguments - they are typically undefined from makeLine
  16491. };
  16492. var makeLine = function (type, obj, location) {
  16493. var str = obj.format instanceof Function ?
  16494. (obj.format(obj.push ? location : location[obj.name])) :
  16495. obj.format;
  16496. var args = [type + '=' + str];
  16497. if (obj.names) {
  16498. for (var i = 0; i < obj.names.length; i += 1) {
  16499. var n = obj.names[i];
  16500. if (obj.name) {
  16501. args.push(location[obj.name][n]);
  16502. }
  16503. else { // for mLine and push attributes
  16504. args.push(location[obj.names[i]]);
  16505. }
  16506. }
  16507. }
  16508. else {
  16509. args.push(location[obj.name]);
  16510. }
  16511. return format.apply(null, args);
  16512. };
  16513. // RFC specified order
  16514. // TODO: extend this with all the rest
  16515. var defaultOuterOrder = [
  16516. 'v', 'o', 's', 'i',
  16517. 'u', 'e', 'p', 'c',
  16518. 'b', 't', 'r', 'z', 'a'
  16519. ];
  16520. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  16521. module.exports = function (session, opts) {
  16522. opts = opts || {};
  16523. // ensure certain properties exist
  16524. if (session.version == null) {
  16525. session.version = 0; // "v=0" must be there (only defined version atm)
  16526. }
  16527. if (session.name == null) {
  16528. session.name = " "; // "s= " must be there if no meaningful name set
  16529. }
  16530. session.media.forEach(function (mLine) {
  16531. if (mLine.payloads == null) {
  16532. mLine.payloads = "";
  16533. }
  16534. });
  16535. var outerOrder = opts.outerOrder || defaultOuterOrder;
  16536. var innerOrder = opts.innerOrder || defaultInnerOrder;
  16537. var sdp = [];
  16538. // loop through outerOrder for matching properties on session
  16539. outerOrder.forEach(function (type) {
  16540. grammar[type].forEach(function (obj) {
  16541. if (obj.name in session && session[obj.name] != null) {
  16542. sdp.push(makeLine(type, obj, session));
  16543. }
  16544. else if (obj.push in session && session[obj.push] != null) {
  16545. session[obj.push].forEach(function (el) {
  16546. sdp.push(makeLine(type, obj, el));
  16547. });
  16548. }
  16549. });
  16550. });
  16551. // then for each media line, follow the innerOrder
  16552. session.media.forEach(function (mLine) {
  16553. sdp.push(makeLine('m', grammar.m[0], mLine));
  16554. innerOrder.forEach(function (type) {
  16555. grammar[type].forEach(function (obj) {
  16556. if (obj.name in mLine && mLine[obj.name] != null) {
  16557. sdp.push(makeLine(type, obj, mLine));
  16558. }
  16559. else if (obj.push in mLine && mLine[obj.push] != null) {
  16560. mLine[obj.push].forEach(function (el) {
  16561. sdp.push(makeLine(type, obj, el));
  16562. });
  16563. }
  16564. });
  16565. });
  16566. });
  16567. return sdp.join('\r\n') + '\r\n';
  16568. };
  16569. },{"./grammar":55}],59:[function(require,module,exports){
  16570. var transform = require('sdp-transform');
  16571. var transformUtils = require('./transform-utils');
  16572. var parseSsrcs = transformUtils.parseSsrcs;
  16573. var writeSsrcs = transformUtils.writeSsrcs;
  16574. //region Constants
  16575. var DEFAULT_NUM_OF_LAYERS = 3;
  16576. //endregion
  16577. //region Ctor
  16578. function Simulcast(options) {
  16579. this.options = options ? options : {};
  16580. if (!this.options.numOfLayers) {
  16581. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  16582. }
  16583. this.layers = [];
  16584. }
  16585. //endregion
  16586. //region Stateless private utility functions
  16587. /**
  16588. * Returns a random integer between min (included) and max (excluded)
  16589. * Using Math.round() gives a non-uniform distribution!
  16590. * @returns {number}
  16591. */
  16592. function generateSSRC() {
  16593. var min = 0, max = 0xffffffff;
  16594. return Math.floor(Math.random() * (max - min)) + min;
  16595. };
  16596. function processVideo(session, action) {
  16597. if (session == null || !Array.isArray(session.media)) {
  16598. return;
  16599. }
  16600. session.media.forEach(function (mLine) {
  16601. if (mLine.type === 'video') {
  16602. action(mLine);
  16603. }
  16604. });
  16605. }
  16606. function validateDescription(desc)
  16607. {
  16608. return desc && desc != null
  16609. && desc.type && desc.type != ''
  16610. && desc.sdp && desc.sdp != '';
  16611. }
  16612. function explodeRemoteSimulcast(mLine) {
  16613. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16614. return;
  16615. }
  16616. var sources = parseSsrcs(mLine);
  16617. var order = [];
  16618. // Find the SIM group and explode its sources.
  16619. var j = mLine.ssrcGroups.length;
  16620. while (j--) {
  16621. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  16622. continue;
  16623. }
  16624. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  16625. for (var i = 0; i < simulcastSsrcs.length; i++) {
  16626. var ssrc = simulcastSsrcs[i];
  16627. order.push(ssrc);
  16628. var parts = sources[ssrc].msid.split(' ');
  16629. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  16630. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  16631. // Remove all the groups that this SSRC participates in.
  16632. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16633. if (relatedGroup.semantics === 'SIM') {
  16634. return;
  16635. }
  16636. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  16637. if (relatedSsrcs.indexOf(ssrc) === -1) {
  16638. return;
  16639. }
  16640. // Nuke all the related SSRCs.
  16641. relatedSsrcs.forEach(function (relatedSSRC) {
  16642. sources[relatedSSRC].msid = sources[ssrc].msid;
  16643. sources[relatedSSRC].cname = sources[ssrc].cname;
  16644. if (relatedSSRC !== ssrc) {
  16645. order.push(relatedSSRC);
  16646. }
  16647. });
  16648. // Schedule the related group for nuking.
  16649. })
  16650. }
  16651. mLine.ssrcs = writeSsrcs(sources, order);
  16652. mLine.ssrcGroups.splice(j, 1);
  16653. };
  16654. }
  16655. function squeezeRemoteSimulcast(mLine) {
  16656. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16657. return;
  16658. }
  16659. var sources = parseSsrcs(mLine);
  16660. // Find the SIM group and nuke it.
  16661. mLine.ssrcGroups.some(function (simulcastGroup) {
  16662. if (simulcastGroup.semantics !== 'SIM') {
  16663. return false;
  16664. }
  16665. // Schedule the SIM group for nuking.
  16666. simulcastGroup.nuke = true;
  16667. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  16668. // Nuke all the higher layer SSRCs.
  16669. for (var i = 1; i < simulcastSsrcs.length; i++) {
  16670. var ssrc = simulcastSsrcs[i];
  16671. delete sources[ssrc];
  16672. // Remove all the groups that this SSRC participates in.
  16673. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16674. if (relatedGroup.semantics === 'SIM') {
  16675. return;
  16676. }
  16677. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  16678. if (relatedSsrcs.indexOf(ssrc) === -1) {
  16679. return;
  16680. }
  16681. // Nuke all the related SSRCs.
  16682. relatedSsrcs.forEach(function (relatedSSRC) {
  16683. delete sources[relatedSSRC];
  16684. });
  16685. // Schedule the related group for nuking.
  16686. relatedGroup.nuke = true;
  16687. })
  16688. }
  16689. return true;
  16690. });
  16691. mLine.ssrcs = writeSsrcs(sources);
  16692. // Nuke all the scheduled groups.
  16693. var i = mLine.ssrcGroups.length;
  16694. while (i--) {
  16695. if (mLine.ssrcGroups[i].nuke) {
  16696. mLine.ssrcGroups.splice(i, 1);
  16697. }
  16698. }
  16699. }
  16700. function removeGoogConference(mLine) {
  16701. if (!mLine || !Array.isArray(mLine.invalid)) {
  16702. return;
  16703. }
  16704. var i = mLine.invalid.length;
  16705. while (i--) {
  16706. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  16707. mLine.invalid.splice(i, 1);
  16708. }
  16709. }
  16710. }
  16711. function assertGoogConference(mLine) {
  16712. if (!mLine) {
  16713. return;
  16714. }
  16715. if (!Array.isArray(mLine.invalid)) {
  16716. mLine.invalid = [];
  16717. }
  16718. if (!mLine.invalid.some(
  16719. function (i) { return i.value === 'x-google-flag:conference' })) {
  16720. mLine.invalid.push({'value': 'x-google-flag:conference'});
  16721. }
  16722. }
  16723. //endregion
  16724. //region "Private" functions
  16725. /**
  16726. *
  16727. * @param mLine
  16728. * @private
  16729. */
  16730. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  16731. if (!mLine || mLine.type !== 'video') {
  16732. return;
  16733. }
  16734. var sources = parseSsrcs(mLine);
  16735. if (Object.keys(sources).length === 0) {
  16736. // no sources, disable simulcast.
  16737. if (this.layers.length !== 0) {
  16738. this.layers = [];
  16739. }
  16740. return;
  16741. }
  16742. // find the base layer (we'll reuse its msid and cname).
  16743. var baseLayerSSRC = Object.keys(sources)[0];
  16744. var baseLayer = sources[baseLayerSSRC];
  16745. // todo(gp) handle screen sharing.
  16746. // check if base CNAME has changed and reinitialise layers.
  16747. if (this.layers.length > 0
  16748. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  16749. this.layers = [];
  16750. }
  16751. // (re)initialise layers
  16752. if (this.layers.length < 1) {
  16753. // first push the base layer.
  16754. this.layers.push({
  16755. ssrc: baseLayerSSRC,
  16756. msid: baseLayer.msid,
  16757. cname: baseLayer.cname
  16758. });
  16759. var rtx = false; // RFC 4588
  16760. if (Array.isArray(mLine.rtp)) {
  16761. rtx = mLine.rtp.some(
  16762. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  16763. }
  16764. if (rtx) {
  16765. this.layers[0].rtx = generateSSRC();
  16766. }
  16767. // now push additional layers.
  16768. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  16769. var layer = { ssrc: generateSSRC() };
  16770. if (rtx) {
  16771. layer.rtx = generateSSRC();
  16772. }
  16773. this.layers.push(layer);
  16774. }
  16775. }
  16776. };
  16777. /**
  16778. *
  16779. * @param mLine
  16780. * @private
  16781. */
  16782. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  16783. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  16784. var sources = {};
  16785. var msid = this.layers[0].msid;
  16786. var cname = this.layers[0].cname;
  16787. var simulcastSsrcs = [];
  16788. var ssrcGroups = [];
  16789. for (var i = 0; i < this.layers.length; i++) {
  16790. var layer = this.layers[i];
  16791. sources[layer.ssrc] = { msid: msid, cname: cname };
  16792. simulcastSsrcs.push(layer.ssrc);
  16793. if (layer.rtx) {
  16794. sources[layer.rtx] = {
  16795. msid: msid,
  16796. cname: cname
  16797. }
  16798. ssrcGroups.push({
  16799. semantics: 'FID',
  16800. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  16801. });
  16802. }
  16803. }
  16804. ssrcGroups.push({
  16805. semantics: 'SIM',
  16806. ssrcs: simulcastSsrcs.join(' ')
  16807. });
  16808. mLine.ssrcGroups = ssrcGroups;
  16809. mLine.ssrcs = writeSsrcs(sources);
  16810. }
  16811. }
  16812. //endregion
  16813. //region "Public" functions
  16814. Simulcast.prototype.isSupported = function () {
  16815. return window.chrome;
  16816. // TODO this needs improvements. For example I doubt that Chrome in Android
  16817. // has simulcast support. Also, only recent versions of Chromium have native
  16818. // simulcast support.
  16819. }
  16820. /**
  16821. *
  16822. * @param desc
  16823. * @returns {RTCSessionDescription}
  16824. */
  16825. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  16826. if (!validateDescription(desc)) {
  16827. return desc;
  16828. }
  16829. var session = transform.parse(desc.sdp);
  16830. var self = this;
  16831. processVideo(session, function (mLine) {
  16832. // Handle simulcast reception.
  16833. if (self.options.explodeRemoteSimulcast) {
  16834. explodeRemoteSimulcast(mLine);
  16835. } else {
  16836. squeezeRemoteSimulcast(mLine);
  16837. }
  16838. // If native simulcast is enabled, we must append the x-goog-conference
  16839. // attribute to the SDP.
  16840. if (self.layers.length < 1) {
  16841. removeGoogConference(mLine);
  16842. } else {
  16843. assertGoogConference(mLine);
  16844. }
  16845. });
  16846. return new RTCSessionDescription({
  16847. type: desc.type,
  16848. sdp: transform.write(session)
  16849. });
  16850. };
  16851. /**
  16852. *
  16853. * @param desc
  16854. * @returns {RTCSessionDescription}
  16855. */
  16856. Simulcast.prototype.mungeLocalDescription = function (desc) {
  16857. if (!validateDescription(desc) || !this.isSupported()) {
  16858. return desc;
  16859. }
  16860. var session = transform.parse(desc.sdp);
  16861. var self = this;
  16862. processVideo(session, function (mLine) {
  16863. // Initialize native simulcast layers, if not already done.
  16864. self._maybeInitializeLayers(mLine);
  16865. // Update the SDP with the simulcast layers.
  16866. self._restoreSimulcastView(mLine);
  16867. });
  16868. return new RTCSessionDescription({
  16869. type: desc.type,
  16870. sdp: transform.write(session)
  16871. });
  16872. };
  16873. //endregion
  16874. module.exports = Simulcast;
  16875. },{"./transform-utils":60,"sdp-transform":62}],60:[function(require,module,exports){
  16876. exports.writeSsrcs = function(sources, order) {
  16877. var ssrcs = [];
  16878. // expand sources to ssrcs
  16879. if (typeof sources !== 'undefined' &&
  16880. Object.keys(sources).length !== 0) {
  16881. if (Array.isArray(order)) {
  16882. for (var i = 0; i < order.length; i++) {
  16883. var ssrc = order[i];
  16884. var source = sources[ssrc];
  16885. Object.keys(source).forEach(function (attribute) {
  16886. ssrcs.push({
  16887. id: ssrc,
  16888. attribute: attribute,
  16889. value: source[attribute]
  16890. });
  16891. });
  16892. }
  16893. } else {
  16894. Object.keys(sources).forEach(function (ssrc) {
  16895. var source = sources[ssrc];
  16896. Object.keys(source).forEach(function (attribute) {
  16897. ssrcs.push({
  16898. id: ssrc,
  16899. attribute: attribute,
  16900. value: source[attribute]
  16901. });
  16902. });
  16903. });
  16904. }
  16905. }
  16906. return ssrcs;
  16907. };
  16908. exports.parseSsrcs = function (mLine) {
  16909. var sources = {};
  16910. // group sources attributes by ssrc.
  16911. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  16912. mLine.ssrcs.forEach(function (ssrc) {
  16913. if (!sources[ssrc.id])
  16914. sources[ssrc.id] = {};
  16915. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  16916. });
  16917. }
  16918. return sources;
  16919. };
  16920. },{}],61:[function(require,module,exports){
  16921. arguments[4][55][0].apply(exports,arguments)
  16922. },{"dup":55}],62:[function(require,module,exports){
  16923. arguments[4][56][0].apply(exports,arguments)
  16924. },{"./parser":63,"./writer":64,"dup":56}],63:[function(require,module,exports){
  16925. arguments[4][57][0].apply(exports,arguments)
  16926. },{"./grammar":61,"dup":57}],64:[function(require,module,exports){
  16927. arguments[4][58][0].apply(exports,arguments)
  16928. },{"./grammar":61,"dup":58}],65:[function(require,module,exports){
  16929. var grammar = module.exports = {
  16930. v: [{
  16931. name: 'version',
  16932. reg: /^(\d*)$/
  16933. }],
  16934. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  16935. // NB: sessionId will be a String in most cases because it is huge
  16936. name: 'origin',
  16937. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  16938. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  16939. format: "%s %s %d %s IP%d %s"
  16940. }],
  16941. // default parsing of these only (though some of these feel outdated)
  16942. s: [{ name: 'name' }],
  16943. i: [{ name: 'description' }],
  16944. u: [{ name: 'uri' }],
  16945. e: [{ name: 'email' }],
  16946. p: [{ name: 'phone' }],
  16947. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  16948. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  16949. //k: [{}], // outdated thing ignored
  16950. t: [{ //t=0 0
  16951. name: 'timing',
  16952. reg: /^(\d*) (\d*)/,
  16953. names: ['start', 'stop'],
  16954. format: "%d %d"
  16955. }],
  16956. c: [{ //c=IN IP4 10.47.197.26
  16957. name: 'connection',
  16958. reg: /^IN IP(\d) (\S*)/,
  16959. names: ['version', 'ip'],
  16960. format: "IN IP%d %s"
  16961. }],
  16962. b: [{ //b=AS:4000
  16963. push: 'bandwidth',
  16964. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  16965. names: ['type', 'limit'],
  16966. format: "%s:%s"
  16967. }],
  16968. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  16969. // NB: special - pushes to session
  16970. // TODO: rtp/fmtp should be filtered by the payloads found here?
  16971. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  16972. names: ['type', 'port', 'protocol', 'payloads'],
  16973. format: "%s %d %s %s"
  16974. }],
  16975. a: [
  16976. { //a=rtpmap:110 opus/48000/2
  16977. push: 'rtp',
  16978. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  16979. names: ['payload', 'codec', 'rate', 'encoding'],
  16980. format: function (o) {
  16981. return (o.encoding) ?
  16982. "rtpmap:%d %s/%s/%s":
  16983. "rtpmap:%d %s/%s";
  16984. }
  16985. },
  16986. {
  16987. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  16988. //a=fmtp:111 minptime=10; useinbandfec=1
  16989. push: 'fmtp',
  16990. reg: /^fmtp:(\d*) ([\S| ]*)/,
  16991. names: ['payload', 'config'],
  16992. format: "fmtp:%d %s"
  16993. },
  16994. { //a=control:streamid=0
  16995. name: 'control',
  16996. reg: /^control:(.*)/,
  16997. format: "control:%s"
  16998. },
  16999. { //a=rtcp:65179 IN IP4 193.84.77.194
  17000. name: 'rtcp',
  17001. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  17002. names: ['port', 'netType', 'ipVer', 'address'],
  17003. format: function (o) {
  17004. return (o.address != null) ?
  17005. "rtcp:%d %s IP%d %s":
  17006. "rtcp:%d";
  17007. }
  17008. },
  17009. { //a=rtcp-fb:98 trr-int 100
  17010. push: 'rtcpFbTrrInt',
  17011. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  17012. names: ['payload', 'value'],
  17013. format: "rtcp-fb:%d trr-int %d"
  17014. },
  17015. { //a=rtcp-fb:98 nack rpsi
  17016. push: 'rtcpFb',
  17017. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  17018. names: ['payload', 'type', 'subtype'],
  17019. format: function (o) {
  17020. return (o.subtype != null) ?
  17021. "rtcp-fb:%s %s %s":
  17022. "rtcp-fb:%s %s";
  17023. }
  17024. },
  17025. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  17026. //a=extmap:1/recvonly URI-gps-string
  17027. push: 'ext',
  17028. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  17029. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  17030. format: function (o) {
  17031. return (o.config != null) ?
  17032. "extmap:%s %s %s":
  17033. "extmap:%s %s";
  17034. }
  17035. },
  17036. {
  17037. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  17038. push: 'crypto',
  17039. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  17040. names: ['id', 'suite', 'config', 'sessionConfig'],
  17041. format: function (o) {
  17042. return (o.sessionConfig != null) ?
  17043. "crypto:%d %s %s %s":
  17044. "crypto:%d %s %s";
  17045. }
  17046. },
  17047. { //a=setup:actpass
  17048. name: 'setup',
  17049. reg: /^setup:(\w*)/,
  17050. format: "setup:%s"
  17051. },
  17052. { //a=mid:1
  17053. name: 'mid',
  17054. reg: /^mid:([^\s]*)/,
  17055. format: "mid:%s"
  17056. },
  17057. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  17058. name: 'msid',
  17059. reg: /^msid:(.*)/,
  17060. format: "msid:%s"
  17061. },
  17062. { //a=ptime:20
  17063. name: 'ptime',
  17064. reg: /^ptime:(\d*)/,
  17065. format: "ptime:%d"
  17066. },
  17067. { //a=maxptime:60
  17068. name: 'maxptime',
  17069. reg: /^maxptime:(\d*)/,
  17070. format: "maxptime:%d"
  17071. },
  17072. { //a=sendrecv
  17073. name: 'direction',
  17074. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  17075. },
  17076. { //a=ice-lite
  17077. name: 'icelite',
  17078. reg: /^(ice-lite)/
  17079. },
  17080. { //a=ice-ufrag:F7gI
  17081. name: 'iceUfrag',
  17082. reg: /^ice-ufrag:(\S*)/,
  17083. format: "ice-ufrag:%s"
  17084. },
  17085. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  17086. name: 'icePwd',
  17087. reg: /^ice-pwd:(\S*)/,
  17088. format: "ice-pwd:%s"
  17089. },
  17090. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  17091. name: 'fingerprint',
  17092. reg: /^fingerprint:(\S*) (\S*)/,
  17093. names: ['type', 'hash'],
  17094. format: "fingerprint:%s %s"
  17095. },
  17096. {
  17097. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  17098. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  17099. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  17100. push:'candidates',
  17101. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  17102. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  17103. format: function (o) {
  17104. var str = "candidate:%s %d %s %d %s %d typ %s";
  17105. // NB: candidate has two optional chunks, so %void middle one if it's missing
  17106. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  17107. if (o.generation != null) {
  17108. str += " generation %d";
  17109. }
  17110. return str;
  17111. }
  17112. },
  17113. { //a=end-of-candidates (keep after the candidates line for readability)
  17114. name: 'endOfCandidates',
  17115. reg: /^(end-of-candidates)/
  17116. },
  17117. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  17118. name: 'remoteCandidates',
  17119. reg: /^remote-candidates:(.*)/,
  17120. format: "remote-candidates:%s"
  17121. },
  17122. { //a=ice-options:google-ice
  17123. name: 'iceOptions',
  17124. reg: /^ice-options:(\S*)/,
  17125. format: "ice-options:%s"
  17126. },
  17127. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  17128. push: "ssrcs",
  17129. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  17130. names: ['id', 'attribute', 'value'],
  17131. format: "ssrc:%d %s:%s"
  17132. },
  17133. { //a=ssrc-group:FEC 1 2
  17134. push: "ssrcGroups",
  17135. reg: /^ssrc-group:(\w*) (.*)/,
  17136. names: ['semantics', 'ssrcs'],
  17137. format: "ssrc-group:%s %s"
  17138. },
  17139. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  17140. name: "msidSemantic",
  17141. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  17142. names: ['semantic', 'token'],
  17143. format: "msid-semantic: %s %s" // space after ":" is not accidental
  17144. },
  17145. { //a=group:BUNDLE audio video
  17146. push: 'groups',
  17147. reg: /^group:(\w*) (.*)/,
  17148. names: ['type', 'mids'],
  17149. format: "group:%s %s"
  17150. },
  17151. { //a=rtcp-mux
  17152. name: 'rtcpMux',
  17153. reg: /^(rtcp-mux)/
  17154. },
  17155. { //a=rtcp-rsize
  17156. name: 'rtcpRsize',
  17157. reg: /^(rtcp-rsize)/
  17158. },
  17159. { // any a= that we don't understand is kepts verbatim on media.invalid
  17160. push: 'invalid',
  17161. names: ["value"]
  17162. }
  17163. ]
  17164. };
  17165. // set sensible defaults to avoid polluting the grammar with boring details
  17166. Object.keys(grammar).forEach(function (key) {
  17167. var objs = grammar[key];
  17168. objs.forEach(function (obj) {
  17169. if (!obj.reg) {
  17170. obj.reg = /(.*)/;
  17171. }
  17172. if (!obj.format) {
  17173. obj.format = "%s";
  17174. }
  17175. });
  17176. });
  17177. },{}],66:[function(require,module,exports){
  17178. arguments[4][56][0].apply(exports,arguments)
  17179. },{"./parser":67,"./writer":68,"dup":56}],67:[function(require,module,exports){
  17180. var toIntIfInt = function (v) {
  17181. return String(Number(v)) === v ? Number(v) : v;
  17182. };
  17183. var attachProperties = function (match, location, names, rawName) {
  17184. if (rawName && !names) {
  17185. location[rawName] = toIntIfInt(match[1]);
  17186. }
  17187. else {
  17188. for (var i = 0; i < names.length; i += 1) {
  17189. if (match[i+1] != null) {
  17190. location[names[i]] = toIntIfInt(match[i+1]);
  17191. }
  17192. }
  17193. }
  17194. };
  17195. var parseReg = function (obj, location, content) {
  17196. var needsBlank = obj.name && obj.names;
  17197. if (obj.push && !location[obj.push]) {
  17198. location[obj.push] = [];
  17199. }
  17200. else if (needsBlank && !location[obj.name]) {
  17201. location[obj.name] = {};
  17202. }
  17203. var keyLocation = obj.push ?
  17204. {} : // blank object that will be pushed
  17205. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  17206. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  17207. if (obj.push) {
  17208. location[obj.push].push(keyLocation);
  17209. }
  17210. };
  17211. var grammar = require('./grammar');
  17212. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  17213. exports.parse = function (sdp) {
  17214. var session = {}
  17215. , media = []
  17216. , location = session; // points at where properties go under (one of the above)
  17217. // parse lines we understand
  17218. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  17219. var type = l[0];
  17220. var content = l.slice(2);
  17221. if (type === 'm') {
  17222. media.push({rtp: [], fmtp: []});
  17223. location = media[media.length-1]; // point at latest media line
  17224. }
  17225. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  17226. var obj = grammar[type][j];
  17227. if (obj.reg.test(content)) {
  17228. return parseReg(obj, location, content);
  17229. }
  17230. }
  17231. });
  17232. session.media = media; // link it up
  17233. return session;
  17234. };
  17235. var fmtpReducer = function (acc, expr) {
  17236. var s = expr.split('=');
  17237. if (s.length === 2) {
  17238. acc[s[0]] = toIntIfInt(s[1]);
  17239. }
  17240. return acc;
  17241. };
  17242. exports.parseFmtpConfig = function (str) {
  17243. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  17244. };
  17245. exports.parsePayloads = function (str) {
  17246. return str.split(' ').map(Number);
  17247. };
  17248. exports.parseRemoteCandidates = function (str) {
  17249. var candidates = [];
  17250. var parts = str.split(' ').map(toIntIfInt);
  17251. for (var i = 0; i < parts.length; i += 3) {
  17252. candidates.push({
  17253. component: parts[i],
  17254. ip: parts[i + 1],
  17255. port: parts[i + 2]
  17256. });
  17257. }
  17258. return candidates;
  17259. };
  17260. },{"./grammar":65}],68:[function(require,module,exports){
  17261. arguments[4][58][0].apply(exports,arguments)
  17262. },{"./grammar":65,"dup":58}],69:[function(require,module,exports){
  17263. var MediaStreamType = {
  17264. VIDEO_TYPE: "Video",
  17265. AUDIO_TYPE: "Audio"
  17266. };
  17267. module.exports = MediaStreamType;
  17268. },{}],70:[function(require,module,exports){
  17269. var RTCEvents = {
  17270. RTC_READY: "rtc.ready",
  17271. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  17272. LASTN_CHANGED: "rtc.lastn_changed",
  17273. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  17274. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  17275. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  17276. AUDIO_MUTE: "rtc.audio_mute",
  17277. VIDEO_MUTE: "rtc.video_mute"
  17278. };
  17279. module.exports = RTCEvents;
  17280. },{}],71:[function(require,module,exports){
  17281. var Resolutions = {
  17282. "1080": {
  17283. width: 1920,
  17284. height: 1080,
  17285. order: 7
  17286. },
  17287. "fullhd": {
  17288. width: 1920,
  17289. height: 1080,
  17290. order: 7
  17291. },
  17292. "720": {
  17293. width: 1280,
  17294. height: 720,
  17295. order: 6
  17296. },
  17297. "hd": {
  17298. width: 1280,
  17299. height: 720,
  17300. order: 6
  17301. },
  17302. "960": {
  17303. width: 960,
  17304. height: 720,
  17305. order: 5
  17306. },
  17307. "640": {
  17308. width: 640,
  17309. height: 480,
  17310. order: 4
  17311. },
  17312. "vga": {
  17313. width: 640,
  17314. height: 480,
  17315. order: 4
  17316. },
  17317. "360": {
  17318. width: 640,
  17319. height: 360,
  17320. order: 3
  17321. },
  17322. "320": {
  17323. width: 320,
  17324. height: 240,
  17325. order: 2
  17326. },
  17327. "180": {
  17328. width: 320,
  17329. height: 180,
  17330. order: 1
  17331. }
  17332. };
  17333. module.exports = Resolutions;
  17334. },{}],72:[function(require,module,exports){
  17335. var StreamEventTypes = {
  17336. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  17337. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  17338. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  17339. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  17340. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  17341. };
  17342. module.exports = StreamEventTypes;
  17343. },{}],73:[function(require,module,exports){
  17344. var AuthenticationEvents = {
  17345. /**
  17346. * Event callback arguments:
  17347. * function(authenticationEnabled, userIdentity)
  17348. * authenticationEnabled - indicates whether authentication has been enabled
  17349. * in this session
  17350. * userIdentity - if user has been logged in then it contains user name. If
  17351. * contains 'null' or 'undefined' then user is not logged in.
  17352. */
  17353. IDENTITY_UPDATED: "authentication.identity_updated"
  17354. };
  17355. module.exports = AuthenticationEvents;
  17356. },{}],74:[function(require,module,exports){
  17357. var DesktopSharingEventTypes = {
  17358. INIT: "ds.init",
  17359. SWITCHING_DONE: "ds.switching_done",
  17360. NEW_STREAM_CREATED: "ds.new_stream_created"
  17361. };
  17362. module.exports = DesktopSharingEventTypes;
  17363. },{}],75:[function(require,module,exports){
  17364. var XMPPEvents = {
  17365. CONNECTION_FAILED: "xmpp.connection.failed",
  17366. // Indicates an interrupted connection event.
  17367. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  17368. // Indicates a restored connection event.
  17369. CONNECTION_RESTORED: "xmpp.connection.restored",
  17370. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  17371. CALL_INCOMING: "xmpp.callincoming.jingle",
  17372. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  17373. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  17374. KICKED: "xmpp.kicked",
  17375. BRIDGE_DOWN: "xmpp.bridge_down",
  17376. USER_ID_CHANGED: "xmpp.user_id_changed",
  17377. // We joined the MUC
  17378. MUC_JOINED: "xmpp.muc_joined",
  17379. // A member joined the MUC
  17380. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  17381. // A member left the MUC
  17382. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  17383. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  17384. MUC_DESTROYED: "xmpp.muc_destroyed",
  17385. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  17386. REMOTE_STATS: "xmpp.remote_stats",
  17387. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  17388. PRESENCE_STATUS: "xmpp.presence_status",
  17389. RESERVATION_ERROR: "xmpp.room_reservation_error",
  17390. SUBJECT_CHANGED: "xmpp.subject_changed",
  17391. MESSAGE_RECEIVED: "xmpp.message_received",
  17392. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  17393. PASSWORD_REQUIRED: "xmpp.password_required",
  17394. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  17395. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  17396. ETHERPAD: "xmpp.etherpad",
  17397. DEVICE_AVAILABLE: "xmpp.device_available",
  17398. VIDEO_TYPE: "xmpp.video_type",
  17399. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  17400. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  17401. AUDIO_MUTED: "xmpp.audio_muted",
  17402. VIDEO_MUTED: "xmpp.video_muted",
  17403. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  17404. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  17405. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  17406. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  17407. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  17408. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  17409. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  17410. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  17411. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  17412. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  17413. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  17414. // xmpp is connected and obtained user media
  17415. READY_TO_JOIN: 'xmpp.ready_to_join',
  17416. FOCUS_LEFT: "xmpp.focus_left",
  17417. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received"
  17418. };
  17419. module.exports = XMPPEvents;
  17420. },{}],76:[function(require,module,exports){
  17421. // Copyright Joyent, Inc. and other Node contributors.
  17422. //
  17423. // Permission is hereby granted, free of charge, to any person obtaining a
  17424. // copy of this software and associated documentation files (the
  17425. // "Software"), to deal in the Software without restriction, including
  17426. // without limitation the rights to use, copy, modify, merge, publish,
  17427. // distribute, sublicense, and/or sell copies of the Software, and to permit
  17428. // persons to whom the Software is furnished to do so, subject to the
  17429. // following conditions:
  17430. //
  17431. // The above copyright notice and this permission notice shall be included
  17432. // in all copies or substantial portions of the Software.
  17433. //
  17434. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  17435. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17436. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  17437. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  17438. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  17439. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  17440. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  17441. function EventEmitter() {
  17442. this._events = this._events || {};
  17443. this._maxListeners = this._maxListeners || undefined;
  17444. }
  17445. module.exports = EventEmitter;
  17446. // Backwards-compat with node 0.10.x
  17447. EventEmitter.EventEmitter = EventEmitter;
  17448. EventEmitter.prototype._events = undefined;
  17449. EventEmitter.prototype._maxListeners = undefined;
  17450. // By default EventEmitters will print a warning if more than 10 listeners are
  17451. // added to it. This is a useful default which helps finding memory leaks.
  17452. EventEmitter.defaultMaxListeners = 10;
  17453. // Obviously not all Emitters should be limited to 10. This function allows
  17454. // that to be increased. Set to zero for unlimited.
  17455. EventEmitter.prototype.setMaxListeners = function(n) {
  17456. if (!isNumber(n) || n < 0 || isNaN(n))
  17457. throw TypeError('n must be a positive number');
  17458. this._maxListeners = n;
  17459. return this;
  17460. };
  17461. EventEmitter.prototype.emit = function(type) {
  17462. var er, handler, len, args, i, listeners;
  17463. if (!this._events)
  17464. this._events = {};
  17465. // If there is no 'error' event listener then throw.
  17466. if (type === 'error') {
  17467. if (!this._events.error ||
  17468. (isObject(this._events.error) && !this._events.error.length)) {
  17469. er = arguments[1];
  17470. if (er instanceof Error) {
  17471. throw er; // Unhandled 'error' event
  17472. }
  17473. throw TypeError('Uncaught, unspecified "error" event.');
  17474. }
  17475. }
  17476. handler = this._events[type];
  17477. if (isUndefined(handler))
  17478. return false;
  17479. if (isFunction(handler)) {
  17480. switch (arguments.length) {
  17481. // fast cases
  17482. case 1:
  17483. handler.call(this);
  17484. break;
  17485. case 2:
  17486. handler.call(this, arguments[1]);
  17487. break;
  17488. case 3:
  17489. handler.call(this, arguments[1], arguments[2]);
  17490. break;
  17491. // slower
  17492. default:
  17493. len = arguments.length;
  17494. args = new Array(len - 1);
  17495. for (i = 1; i < len; i++)
  17496. args[i - 1] = arguments[i];
  17497. handler.apply(this, args);
  17498. }
  17499. } else if (isObject(handler)) {
  17500. len = arguments.length;
  17501. args = new Array(len - 1);
  17502. for (i = 1; i < len; i++)
  17503. args[i - 1] = arguments[i];
  17504. listeners = handler.slice();
  17505. len = listeners.length;
  17506. for (i = 0; i < len; i++)
  17507. listeners[i].apply(this, args);
  17508. }
  17509. return true;
  17510. };
  17511. EventEmitter.prototype.addListener = function(type, listener) {
  17512. var m;
  17513. if (!isFunction(listener))
  17514. throw TypeError('listener must be a function');
  17515. if (!this._events)
  17516. this._events = {};
  17517. // To avoid recursion in the case that type === "newListener"! Before
  17518. // adding it to the listeners, first emit "newListener".
  17519. if (this._events.newListener)
  17520. this.emit('newListener', type,
  17521. isFunction(listener.listener) ?
  17522. listener.listener : listener);
  17523. if (!this._events[type])
  17524. // Optimize the case of one listener. Don't need the extra array object.
  17525. this._events[type] = listener;
  17526. else if (isObject(this._events[type]))
  17527. // If we've already got an array, just append.
  17528. this._events[type].push(listener);
  17529. else
  17530. // Adding the second element, need to change to array.
  17531. this._events[type] = [this._events[type], listener];
  17532. // Check for listener leak
  17533. if (isObject(this._events[type]) && !this._events[type].warned) {
  17534. var m;
  17535. if (!isUndefined(this._maxListeners)) {
  17536. m = this._maxListeners;
  17537. } else {
  17538. m = EventEmitter.defaultMaxListeners;
  17539. }
  17540. if (m && m > 0 && this._events[type].length > m) {
  17541. this._events[type].warned = true;
  17542. console.error('(node) warning: possible EventEmitter memory ' +
  17543. 'leak detected. %d listeners added. ' +
  17544. 'Use emitter.setMaxListeners() to increase limit.',
  17545. this._events[type].length);
  17546. if (typeof console.trace === 'function') {
  17547. // not supported in IE 10
  17548. console.trace();
  17549. }
  17550. }
  17551. }
  17552. return this;
  17553. };
  17554. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  17555. EventEmitter.prototype.once = function(type, listener) {
  17556. if (!isFunction(listener))
  17557. throw TypeError('listener must be a function');
  17558. var fired = false;
  17559. function g() {
  17560. this.removeListener(type, g);
  17561. if (!fired) {
  17562. fired = true;
  17563. listener.apply(this, arguments);
  17564. }
  17565. }
  17566. g.listener = listener;
  17567. this.on(type, g);
  17568. return this;
  17569. };
  17570. // emits a 'removeListener' event iff the listener was removed
  17571. EventEmitter.prototype.removeListener = function(type, listener) {
  17572. var list, position, length, i;
  17573. if (!isFunction(listener))
  17574. throw TypeError('listener must be a function');
  17575. if (!this._events || !this._events[type])
  17576. return this;
  17577. list = this._events[type];
  17578. length = list.length;
  17579. position = -1;
  17580. if (list === listener ||
  17581. (isFunction(list.listener) && list.listener === listener)) {
  17582. delete this._events[type];
  17583. if (this._events.removeListener)
  17584. this.emit('removeListener', type, listener);
  17585. } else if (isObject(list)) {
  17586. for (i = length; i-- > 0;) {
  17587. if (list[i] === listener ||
  17588. (list[i].listener && list[i].listener === listener)) {
  17589. position = i;
  17590. break;
  17591. }
  17592. }
  17593. if (position < 0)
  17594. return this;
  17595. if (list.length === 1) {
  17596. list.length = 0;
  17597. delete this._events[type];
  17598. } else {
  17599. list.splice(position, 1);
  17600. }
  17601. if (this._events.removeListener)
  17602. this.emit('removeListener', type, listener);
  17603. }
  17604. return this;
  17605. };
  17606. EventEmitter.prototype.removeAllListeners = function(type) {
  17607. var key, listeners;
  17608. if (!this._events)
  17609. return this;
  17610. // not listening for removeListener, no need to emit
  17611. if (!this._events.removeListener) {
  17612. if (arguments.length === 0)
  17613. this._events = {};
  17614. else if (this._events[type])
  17615. delete this._events[type];
  17616. return this;
  17617. }
  17618. // emit removeListener for all listeners on all events
  17619. if (arguments.length === 0) {
  17620. for (key in this._events) {
  17621. if (key === 'removeListener') continue;
  17622. this.removeAllListeners(key);
  17623. }
  17624. this.removeAllListeners('removeListener');
  17625. this._events = {};
  17626. return this;
  17627. }
  17628. listeners = this._events[type];
  17629. if (isFunction(listeners)) {
  17630. this.removeListener(type, listeners);
  17631. } else {
  17632. // LIFO order
  17633. while (listeners.length)
  17634. this.removeListener(type, listeners[listeners.length - 1]);
  17635. }
  17636. delete this._events[type];
  17637. return this;
  17638. };
  17639. EventEmitter.prototype.listeners = function(type) {
  17640. var ret;
  17641. if (!this._events || !this._events[type])
  17642. ret = [];
  17643. else if (isFunction(this._events[type]))
  17644. ret = [this._events[type]];
  17645. else
  17646. ret = this._events[type].slice();
  17647. return ret;
  17648. };
  17649. EventEmitter.listenerCount = function(emitter, type) {
  17650. var ret;
  17651. if (!emitter._events || !emitter._events[type])
  17652. ret = 0;
  17653. else if (isFunction(emitter._events[type]))
  17654. ret = 1;
  17655. else
  17656. ret = emitter._events[type].length;
  17657. return ret;
  17658. };
  17659. function isFunction(arg) {
  17660. return typeof arg === 'function';
  17661. }
  17662. function isNumber(arg) {
  17663. return typeof arg === 'number';
  17664. }
  17665. function isObject(arg) {
  17666. return typeof arg === 'object' && arg !== null;
  17667. }
  17668. function isUndefined(arg) {
  17669. return arg === void 0;
  17670. }
  17671. },{}],77:[function(require,module,exports){
  17672. // shim for using process in browser
  17673. var process = module.exports = {};
  17674. var queue = [];
  17675. var draining = false;
  17676. function drainQueue() {
  17677. if (draining) {
  17678. return;
  17679. }
  17680. draining = true;
  17681. var currentQueue;
  17682. var len = queue.length;
  17683. while(len) {
  17684. currentQueue = queue;
  17685. queue = [];
  17686. var i = -1;
  17687. while (++i < len) {
  17688. currentQueue[i]();
  17689. }
  17690. len = queue.length;
  17691. }
  17692. draining = false;
  17693. }
  17694. process.nextTick = function (fun) {
  17695. queue.push(fun);
  17696. if (!draining) {
  17697. setTimeout(drainQueue, 0);
  17698. }
  17699. };
  17700. process.title = 'browser';
  17701. process.browser = true;
  17702. process.env = {};
  17703. process.argv = [];
  17704. process.version = ''; // empty string to avoid regexp issues
  17705. function noop() {}
  17706. process.on = noop;
  17707. process.addListener = noop;
  17708. process.once = noop;
  17709. process.off = noop;
  17710. process.removeListener = noop;
  17711. process.removeAllListeners = noop;
  17712. process.emit = noop;
  17713. process.binding = function (name) {
  17714. throw new Error('process.binding is not supported');
  17715. };
  17716. // TODO(shtylman)
  17717. process.cwd = function () { return '/' };
  17718. process.chdir = function (dir) {
  17719. throw new Error('process.chdir is not supported');
  17720. };
  17721. process.umask = function() { return 0; };
  17722. },{}]},{},[7])(7)
  17723. });