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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135
  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 room = null;
  3. /**
  4. * Creates a JitsiConference object with the given name and properties.
  5. * Note: this constructor is not a part of the public API (objects should be
  6. * created using JitsiConnection.createConference).
  7. * @param options.config properties / settings related to the conference that will be created.
  8. * @param options.name the name of the conference
  9. * @param options.connection the JitsiConnection object for this JitsiConference.
  10. * @constructor
  11. */
  12. function JitsiConference(options) {
  13. this.options = options;
  14. this.connection = this.options.connection;
  15. this.xmpp = this.connection.xmpp;
  16. }
  17. /**
  18. * Joins the conference.
  19. */
  20. JitsiConference.prototype.join = function () {
  21. room = this.xmpp.joinRoom(this.options.name, null, null);
  22. }
  23. /**
  24. * Leaves the conference.
  25. */
  26. JitsiConference.prototype.leave = function () {
  27. this.xmpp.leaveRoom(room.roomjid);
  28. room = null;
  29. }
  30. /**
  31. * Creates the media tracks and returns them via the callback.
  32. * @param options Object with properties / settings specifying the tracks which should be created.
  33. * should be created or some additional configurations about resolution for example.
  34. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>} A promise that returns an array of created JitsiTracks if resolved,
  35. * or a JitsiConferenceError if rejected.
  36. */
  37. JitsiConference.prototype.createLocalTracks = function (options) {
  38. }
  39. /**
  40. * Returns the local tracks.
  41. */
  42. JitsiConference.prototype.getLocalTracks = function () {
  43. };
  44. /**
  45. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  46. * in JitsiConferenceEvents.
  47. * @param eventId the event ID.
  48. * @param handler handler for the event.
  49. *
  50. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  51. */
  52. JitsiConference.prototype.on = function (eventId, handler) {
  53. this.xmpp.addListener(eventId, handler);
  54. }
  55. /**
  56. * Removes event listener
  57. * @param eventId the event ID.
  58. * @param [handler] optional, the specific handler to unbind
  59. *
  60. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  61. */
  62. JitsiConference.prototype.off = function (eventId, handler) {
  63. this.xmpp.removeListener(event, listener);
  64. }
  65. // Common aliases for event emitter
  66. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on
  67. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off
  68. /**
  69. * Receives notifications from another participants for commands / custom events(send by sendPresenceCommand method).
  70. * @param command {String} the name of the command
  71. * @param handler {Function} handler for the command
  72. */
  73. JitsiConference.prototype.addCommandListener = function (command, handler) {
  74. }
  75. /**
  76. * Removes command listener
  77. * @param command {String} the name of the command
  78. */
  79. JitsiConference.prototype.removeCommandListener = function (command) {
  80. }
  81. /**
  82. * Sends text message to the other participants in the conference
  83. * @param message the text message.
  84. */
  85. JitsiConference.prototype.sendTextMessage = function (message) {
  86. room.sendMessage(message);
  87. }
  88. /**
  89. * Send presence command.
  90. * @param name the name of the command.
  91. * @param values Object with keys and values that will be send.
  92. * @param persistent if false the command will be sent only one time
  93. * @param successCallback will be called when the command is successfully send.
  94. * @param errorCallback will be called when the command is not sent successfully.
  95. * @returns {Promise.<{void}, JitsiConferenceError>} A promise that returns an array of created streams if resolved,
  96. * or an JitsiConferenceError if rejected.
  97. */
  98. JitsiConference.prototype.sendCommand = function (name, values, persistent) {
  99. }
  100. /**
  101. * Sets the display name for this conference.
  102. * @param name the display name to set
  103. */
  104. JitsiConference.prototype.setDisplayName = function(name) {
  105. room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  106. }
  107. /**
  108. * Elects the participant with the given id to be the selected participant or the speaker.
  109. * @param id the identifier of the participant
  110. */
  111. JitsiConference.prototype.selectParticipant = function(participantId) {
  112. }
  113. /**
  114. * Returns the list of participants for this conference.
  115. * @return Object a list of participant identifiers containing all conference participants.
  116. */
  117. JitsiConference.prototype.getParticipants = function() {
  118. }
  119. /**
  120. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  121. * null if there isn't one).
  122. * @param id the id of the participant.
  123. */
  124. JitsiConference.prototype.getParticipantById = function(id) {
  125. }
  126. module.exports = JitsiConference;
  127. },{}],2:[function(require,module,exports){
  128. /**
  129. * Enumeration with the errors for the conference.
  130. * @type {{string: string}}
  131. */
  132. var JitsiConferenceErrors = {
  133. /**
  134. * Indicates that a password is required in order to join the conference.
  135. */
  136. PASSWORD_REQUIRED: "conference.passwordRequired",
  137. /**
  138. * Indicates that a connection error occurred when trying to join a conference.
  139. */
  140. CONNECTION_ERROR: "conference.connectionError",
  141. /**
  142. * Indicates that there is no available videobridge.
  143. */
  144. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  145. /**
  146. * Many more errors TBD here.
  147. */
  148. };
  149. module.exports = JitsiConferenceErrors;
  150. },{}],3:[function(require,module,exports){
  151. /**
  152. * Enumeration with the events for the conference.
  153. * @type {{string: string}}
  154. */
  155. var JitsiConferenceEvents = {
  156. /**
  157. * A new media track was added to the conference.
  158. */
  159. TRACK_ADDED: "conference.trackAdded",
  160. /**
  161. * The media track was removed to the conference.
  162. */
  163. TRACK_REMOVED: "conference.trackRemoved",
  164. /**
  165. * The active speaker was changed.
  166. */
  167. ACTIVE_SPEAKER_CHANGED: "conference.activeSpeaker",
  168. /**
  169. * A new user joinned the conference.
  170. */
  171. USER_JOINED: "conference.userJoined",
  172. /**
  173. * A user has left the conference.
  174. */
  175. USER_LEFT: "conference.userLeft",
  176. /**
  177. * New text message was received.
  178. */
  179. MESSAGE_RECEIVED: "conference.messageReceived",
  180. /**
  181. * A user has changed it display name
  182. */
  183. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  184. /**
  185. * A participant avatar has changed.
  186. */
  187. AVATAR_CHANGED: "conference.avatarChanged",
  188. /**
  189. * New connection statistics are received.
  190. */
  191. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  192. /**
  193. * The Last N set is changed.
  194. */
  195. LAST_N_CHANGED: "conference.lastNChanged",
  196. /**
  197. * A media track was muted.
  198. */
  199. TRACK_MUTED: "conference.trackMuted",
  200. /**
  201. * A media track was unmuted.
  202. */
  203. TRACK_UNMUTED: "conference.trackUnmuted",
  204. /**
  205. * Audio levels of a media track was changed.
  206. */
  207. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  208. /**
  209. * Indicates that the connection to the conference has been interrupted for some reason.
  210. */
  211. CONNECTION_INTERRUPTED: "conference.connecionInterrupted",
  212. /**
  213. * Indicates that the connection to the conference has been restored.
  214. */
  215. CONNECTION_ESTABLISHED: "conference.connecionEstablished"
  216. };
  217. module.exports = JitsiConferenceEvents;
  218. },{}],4:[function(require,module,exports){
  219. var JitsiConference = require("./JitsiConference");
  220. var XMPP = require("./modules/xmpp/xmpp");
  221. /**
  222. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  223. * JitsiConference interface.
  224. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  225. * @param token secret generated by the provider of Jitsi Meet video conferencing services.
  226. * The token will be send to the provider from the Jitsi Meet server deployment for authorization of the current client.
  227. * @param options Object with properties / settings related to connection with the server.
  228. * @constructor
  229. */
  230. function JitsiConnection(appID, token, options) {
  231. this.appID = appID;
  232. this.token = token;
  233. this.options = options;
  234. this.xmpp = new XMPP(options);
  235. }
  236. /**
  237. * Connect the client with the server.
  238. * @param options {object} connecting options (for example authentications parameters).
  239. */
  240. JitsiConnection.prototype.connect = function (options) {
  241. if(!options)
  242. options = {};
  243. this.xmpp.connect(options.id, options.password);
  244. }
  245. /**
  246. * Disconnect the client from the server.
  247. */
  248. JitsiConnection.prototype.disconnect = function () {
  249. this.xmpp.disconnect();
  250. }
  251. /**
  252. * This method allows renewal of the tokens if they are expiring.
  253. * @param token the new token.
  254. */
  255. JitsiConnection.prototype.setToken = function (token) {
  256. this.token = token;
  257. }
  258. /**
  259. * Creates and joins new conference.
  260. * @param name the name of the conference; if null - a generated name will be provided from the api
  261. * @param options Object with properties / settings related to the conference that will be created.
  262. * @returns {JitsiConference} returns the new conference object.
  263. */
  264. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  265. return new JitsiConference({name: name, config: options, connection: this});
  266. }
  267. /**
  268. * Subscribes the passed listener to the event.
  269. * @param event {JitsiConnectionEvents} the connection event.
  270. * @param listener {Function} the function that will receive the event
  271. */
  272. JitsiConnection.prototype.addEventListener = function (event, listener) {
  273. this.xmpp.addListener(event, listener);
  274. }
  275. /**
  276. * Unsubscribes the passed handler.
  277. * @param event {JitsiConnectionEvents} the connection event.
  278. * @param listener {Function} the function that will receive the event
  279. */
  280. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  281. this.xmpp.removeListener(event, listener);
  282. }
  283. module.exports = JitsiConnection;
  284. },{"./JitsiConference":1,"./modules/xmpp/xmpp":29}],5:[function(require,module,exports){
  285. /**
  286. * Enumeration with the errors for the connection.
  287. * @type {{string: string}}
  288. */
  289. var JitsiConnectionErrors = {
  290. /**
  291. * Indicates that a password is required in order to join the conference.
  292. */
  293. PASSWORD_REQUIRED: "connection.passwordRequired",
  294. /**
  295. * Indicates that a connection error occurred when trying to join a conference.
  296. */
  297. CONNECTION_ERROR: "connection.connectionError",
  298. /**
  299. * Not specified errors.
  300. */
  301. OTHER_ERROR: "connection.otherError"
  302. };
  303. module.exports = JitsiConnectionErrors;
  304. },{}],6:[function(require,module,exports){
  305. /**
  306. * Enumeration with the events for the connection.
  307. * @type {{string: string}}
  308. */
  309. var JitsiConnnectionEvents = {
  310. /**
  311. * Indicates that the connection has been failed for some reason.
  312. */
  313. CONNECTION_FAILED: "connection.connecionFailed",
  314. /**
  315. * Indicates that the connection has been established.
  316. */
  317. CONNECTION_ESTABLISHED: "connection.connecionEstablished",
  318. /**
  319. * Indicates that the connection has been disconnected.
  320. */
  321. CONNECTION_DISCONNECTED: "connection.connecionDisconnected",
  322. /**
  323. * Indicates that the perfomed action cannot be executed because the
  324. * connection is not in the correct state(connected, disconnected, etc.)
  325. */
  326. WRONG_STATE: "connection.wrongState"
  327. };
  328. module.exports = JitsiConnnectionEvents;
  329. },{}],7:[function(require,module,exports){
  330. var JitsiConnection = require("./JitsiConnection");
  331. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  332. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  333. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  334. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  335. /**
  336. * Namespace for the interface of Jitsi Meet Library.
  337. */
  338. var LibJitsiMeet = {
  339. JitsiConnection: JitsiConnection,
  340. events: {
  341. conference: JitsiConferenceEvents,
  342. connection: JitsiConnectionEvents
  343. },
  344. errors: {
  345. conference: JitsiConferenceErrors,
  346. connection: JitsiConnectionErrors
  347. }
  348. }
  349. //Setups the promise object.
  350. require("es6-promise").polyfill();
  351. module.exports = LibJitsiMeet;
  352. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"es6-promise":31}],8:[function(require,module,exports){
  353. /* global config, APP, Strophe */
  354. // cache datachannels to avoid garbage collection
  355. // https://code.google.com/p/chromium/issues/detail?id=405545
  356. var RTCEvents = require("../../service/RTC/RTCEvents");
  357. var _dataChannels = [];
  358. var eventEmitter = null;
  359. var DataChannels = {
  360. /**
  361. * Callback triggered by PeerConnection when new data channel is opened
  362. * on the bridge.
  363. * @param event the event info object.
  364. */
  365. onDataChannel: function (event) {
  366. var dataChannel = event.channel;
  367. dataChannel.onopen = function () {
  368. console.info("Data channel opened by the Videobridge!", dataChannel);
  369. // Code sample for sending string and/or binary data
  370. // Sends String message to the bridge
  371. //dataChannel.send("Hello bridge!");
  372. // Sends 12 bytes binary message to the bridge
  373. //dataChannel.send(new ArrayBuffer(12));
  374. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  375. };
  376. dataChannel.onerror = function (error) {
  377. console.error("Data Channel Error:", error, dataChannel);
  378. };
  379. dataChannel.onmessage = function (event) {
  380. var data = event.data;
  381. // JSON
  382. var obj;
  383. try {
  384. obj = JSON.parse(data);
  385. }
  386. catch (e) {
  387. console.error(
  388. "Failed to parse data channel message as JSON: ",
  389. data,
  390. dataChannel);
  391. }
  392. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  393. var colibriClass = obj.colibriClass;
  394. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  395. // Endpoint ID from the Videobridge.
  396. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  397. console.info(
  398. "Data channel new dominant speaker event: ",
  399. dominantSpeakerEndpoint);
  400. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  401. }
  402. else if ("InLastNChangeEvent" === colibriClass) {
  403. var oldValue = obj.oldValue;
  404. var newValue = obj.newValue;
  405. // Make sure that oldValue and newValue are of type boolean.
  406. var type;
  407. if ((type = typeof oldValue) !== 'boolean') {
  408. if (type === 'string') {
  409. oldValue = (oldValue == "true");
  410. } else {
  411. oldValue = new Boolean(oldValue).valueOf();
  412. }
  413. }
  414. if ((type = typeof newValue) !== 'boolean') {
  415. if (type === 'string') {
  416. newValue = (newValue == "true");
  417. } else {
  418. newValue = new Boolean(newValue).valueOf();
  419. }
  420. }
  421. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  422. }
  423. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  424. // The new/latest list of last-n endpoint IDs.
  425. var lastNEndpoints = obj.lastNEndpoints;
  426. // The list of endpoint IDs which are entering the list of
  427. // last-n at this time i.e. were not in the old list of last-n
  428. // endpoint IDs.
  429. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  430. console.log(
  431. "Data channel new last-n event: ",
  432. lastNEndpoints, endpointsEnteringLastN, obj);
  433. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  434. lastNEndpoints, endpointsEnteringLastN, obj);
  435. }
  436. else {
  437. console.debug("Data channel JSON-formatted message: ", obj);
  438. }
  439. }
  440. };
  441. dataChannel.onclose = function () {
  442. console.info("The Data Channel closed", dataChannel);
  443. var idx = _dataChannels.indexOf(dataChannel);
  444. if (idx > -1)
  445. _dataChannels = _dataChannels.splice(idx, 1);
  446. };
  447. _dataChannels.push(dataChannel);
  448. },
  449. /**
  450. * Binds "ondatachannel" event listener to given PeerConnection instance.
  451. * @param peerConnection WebRTC peer connection instance.
  452. */
  453. init: function (peerConnection, emitter) {
  454. if(!config.openSctp)
  455. return;
  456. peerConnection.ondatachannel = this.onDataChannel;
  457. eventEmitter = emitter;
  458. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  459. // Although it's not a requirement to open separate channels from both bridge
  460. // and peer as single channel can be used for sending and receiving data.
  461. // So either channel opened by the bridge or the one opened here is enough
  462. // for communication with the bridge.
  463. /*var dataChannelOptions =
  464. {
  465. reliable: true
  466. };
  467. var dataChannel
  468. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  469. // Can be used only when is in open state
  470. dataChannel.onopen = function ()
  471. {
  472. dataChannel.send("My channel !!!");
  473. };
  474. dataChannel.onmessage = function (event)
  475. {
  476. var msgData = event.data;
  477. console.info("Got My Data Channel Message:", msgData, dataChannel);
  478. };*/
  479. },
  480. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  481. handlePinnedEndpointEvent: onPinnedEndpointChanged
  482. };
  483. function onSelectedEndpointChanged(userResource) {
  484. console.log('selected endpoint changed: ', userResource);
  485. if (_dataChannels && _dataChannels.length != 0) {
  486. _dataChannels.some(function (dataChannel) {
  487. if (dataChannel.readyState == 'open') {
  488. console.log('sending selected endpoint changed ' +
  489. 'notification to the bridge: ', userResource);
  490. dataChannel.send(JSON.stringify({
  491. 'colibriClass': 'SelectedEndpointChangedEvent',
  492. 'selectedEndpoint':
  493. (!userResource || userResource === null)?
  494. null : userResource
  495. }));
  496. return true;
  497. }
  498. });
  499. }
  500. }
  501. function onPinnedEndpointChanged(userResource) {
  502. console.log('pinned endpoint changed: ', userResource);
  503. if (_dataChannels && _dataChannels.length != 0) {
  504. _dataChannels.some(function (dataChannel) {
  505. if (dataChannel.readyState == 'open') {
  506. dataChannel.send(JSON.stringify({
  507. 'colibriClass': 'PinnedEndpointChangedEvent',
  508. 'pinnedEndpoint':
  509. (!userResource || userResource == null)?
  510. null : userResource
  511. }));
  512. return true;
  513. }
  514. });
  515. }
  516. }
  517. module.exports = DataChannels;
  518. },{"../../service/RTC/RTCEvents":67}],9:[function(require,module,exports){
  519. /* global APP */
  520. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  521. var RTCEvents = require("../../service/RTC/RTCEvents");
  522. var RTCBrowserType = require("./RTCBrowserType");
  523. /**
  524. * This implements 'onended' callback normally fired by WebRTC after the stream
  525. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  526. * @param stream original WebRTC stream object to which 'onended' handling
  527. * will be added.
  528. */
  529. function implementOnEndedHandling(stream) {
  530. var originalStop = stream.stop;
  531. stream.stop = function () {
  532. originalStop.apply(stream);
  533. if (!stream.ended) {
  534. stream.ended = true;
  535. stream.onended();
  536. }
  537. };
  538. }
  539. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  540. this.stream = stream;
  541. this.eventEmitter = eventEmitter;
  542. this.type = type;
  543. this.videoType = videoType;
  544. this.isGUMStream = true;
  545. if(isGUMStream === false)
  546. this.isGUMStream = isGUMStream;
  547. var self = this;
  548. if(type == "audio") {
  549. this.getTracks = function () {
  550. return self.stream.getAudioTracks();
  551. };
  552. } else {
  553. this.getTracks = function () {
  554. return self.stream.getVideoTracks();
  555. };
  556. }
  557. this.stream.onended = function () {
  558. self.streamEnded();
  559. };
  560. if (RTCBrowserType.isFirefox()) {
  561. implementOnEndedHandling(this.stream);
  562. }
  563. }
  564. LocalStream.prototype.streamEnded = function () {
  565. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  566. };
  567. LocalStream.prototype.getOriginalStream = function()
  568. {
  569. return this.stream;
  570. };
  571. LocalStream.prototype.isAudioStream = function () {
  572. return this.type === "audio";
  573. };
  574. LocalStream.prototype.setMute = function (mute)
  575. {
  576. var isAudio = this.isAudioStream();
  577. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  578. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  579. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  580. // FIXME FF does not support 'removeStream' method used to mute
  581. RTCBrowserType.isFirefox()) {
  582. var tracks = this.getTracks();
  583. for (var idx = 0; idx < tracks.length; idx++) {
  584. tracks[idx].enabled = !mute;
  585. }
  586. this.eventEmitter.emit(eventType, mute);
  587. } else {
  588. if (mute) {
  589. APP.xmpp.removeStream(this.stream);
  590. this.stream.stop();
  591. this.eventEmitter.emit(eventType, true);
  592. } else {
  593. var self = this;
  594. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  595. (this.isAudioStream() ? ["audio"] : ["video"]),
  596. function (stream) {
  597. if (isAudio) {
  598. APP.RTC.changeLocalAudio(stream,
  599. function () {
  600. self.eventEmitter.emit(eventType, false);
  601. });
  602. } else {
  603. APP.RTC.changeLocalVideo(stream, false,
  604. function () {
  605. self.eventEmitter.emit(eventType, false);
  606. });
  607. }
  608. });
  609. }
  610. }
  611. };
  612. LocalStream.prototype.isMuted = function () {
  613. var tracks = [];
  614. if (this.isAudioStream()) {
  615. tracks = this.stream.getAudioTracks();
  616. } else {
  617. if (this.stream.ended)
  618. return true;
  619. tracks = this.stream.getVideoTracks();
  620. }
  621. for (var idx = 0; idx < tracks.length; idx++) {
  622. if(tracks[idx].enabled)
  623. return false;
  624. }
  625. return true;
  626. };
  627. LocalStream.prototype.getId = function () {
  628. return this.stream.getTracks()[0].id;
  629. };
  630. module.exports = LocalStream;
  631. },{"../../service/RTC/RTCEvents":67,"../../service/RTC/StreamEventTypes.js":69,"./RTCBrowserType":12}],10:[function(require,module,exports){
  632. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  633. /**
  634. * Creates a MediaStream object for the given data, session id and ssrc.
  635. * It is a wrapper class for the MediaStream.
  636. *
  637. * @param data the data object from which we obtain the stream,
  638. * the peerjid, etc.
  639. * @param sid the session id
  640. * @param ssrc the ssrc corresponding to this MediaStream
  641. *
  642. * @constructor
  643. */
  644. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  645. // XXX(gp) to minimize headaches in the future, we should build our
  646. // abstractions around tracks and not streams. ORTC is track based API.
  647. // Mozilla expects m-lines to represent media tracks.
  648. //
  649. // Practically, what I'm saying is that we should have a MediaTrack class
  650. // and not a MediaStream class.
  651. //
  652. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  653. // a track might have an associated RTX and FEC sources.
  654. this.sid = sid;
  655. this.stream = data.stream;
  656. this.peerjid = data.peerjid;
  657. this.videoType = data.videoType;
  658. this.ssrc = ssrc;
  659. this.type = (this.stream.getVideoTracks().length > 0)?
  660. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  661. this.muted = false;
  662. this.eventEmitter = eventEmitter;
  663. }
  664. MediaStream.prototype.getOriginalStream = function() {
  665. return this.stream;
  666. };
  667. MediaStream.prototype.setMute = function (value) {
  668. this.stream.muted = value;
  669. this.muted = value;
  670. };
  671. module.exports = MediaStream;
  672. },{"../../service/RTC/MediaStreamTypes":66}],11:[function(require,module,exports){
  673. /* global APP */
  674. var EventEmitter = require("events");
  675. var RTCBrowserType = require("./RTCBrowserType");
  676. var RTCUtils = require("./RTCUtils.js");
  677. var LocalStream = require("./LocalStream.js");
  678. var DataChannels = require("./DataChannels");
  679. var MediaStream = require("./MediaStream.js");
  680. var DesktopSharingEventTypes
  681. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  682. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  683. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  684. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  685. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  686. var UIEvents = require("../../service/UI/UIEvents");
  687. var eventEmitter = new EventEmitter();
  688. function getMediaStreamUsage()
  689. {
  690. var result = {
  691. audio: true,
  692. video: true
  693. };
  694. /** There are some issues with the desktop sharing
  695. * when this property is enabled.
  696. * WARNING: We must change the implementation to start video/audio if we
  697. * receive from the focus that the peer is not muted.
  698. var isSecureConnection = window.location.protocol == "https:";
  699. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  700. {
  701. result = {
  702. audio: false,
  703. video: false
  704. };
  705. }
  706. **/
  707. return result;
  708. }
  709. var RTC = {
  710. rtcUtils: null,
  711. devices: {
  712. audio: true,
  713. video: true
  714. },
  715. localStreams: [],
  716. remoteStreams: {},
  717. localAudio: null,
  718. localVideo: null,
  719. addStreamListener: function (listener, eventType) {
  720. eventEmitter.on(eventType, listener);
  721. },
  722. addListener: function (type, listener) {
  723. eventEmitter.on(type, listener);
  724. },
  725. removeStreamListener: function (listener, eventType) {
  726. if(!(eventType instanceof StreamEventTypes))
  727. throw "Illegal argument";
  728. eventEmitter.removeListener(eventType, listener);
  729. },
  730. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  731. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  732. //in firefox we have only one stream object
  733. if(this.localStreams.length == 0 ||
  734. this.localStreams[0].getOriginalStream() != stream)
  735. this.localStreams.push(localStream);
  736. if(isMuted === true)
  737. localStream.setMute(true);
  738. if(type == "audio") {
  739. this.localAudio = localStream;
  740. } else {
  741. this.localVideo = localStream;
  742. }
  743. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  744. if(change)
  745. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  746. eventEmitter.emit(eventType, localStream, isMuted);
  747. return localStream;
  748. },
  749. removeLocalStream: function (stream) {
  750. for(var i = 0; i < this.localStreams.length; i++) {
  751. if(this.localStreams[i].getOriginalStream() === stream) {
  752. delete this.localStreams[i];
  753. return;
  754. }
  755. }
  756. },
  757. createRemoteStream: function (data, sid, thessrc) {
  758. var remoteStream = new MediaStream(data, sid, thessrc,
  759. RTCBrowserType.getBrowserType(), eventEmitter);
  760. var jid = data.peerjid || APP.xmpp.myJid();
  761. if(!this.remoteStreams[jid]) {
  762. this.remoteStreams[jid] = {};
  763. }
  764. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  765. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  766. return remoteStream;
  767. },
  768. getPCConstraints: function () {
  769. return this.rtcUtils.pc_constraints;
  770. },
  771. getUserMediaWithConstraints:function(um, success_callback,
  772. failure_callback, resolution,
  773. bandwidth, fps, desktopStream)
  774. {
  775. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  776. failure_callback, resolution, bandwidth, fps, desktopStream);
  777. },
  778. attachMediaStream: function (elSelector, stream) {
  779. this.rtcUtils.attachMediaStream(elSelector, stream);
  780. },
  781. getStreamID: function (stream) {
  782. return this.rtcUtils.getStreamID(stream);
  783. },
  784. getVideoSrc: function (element) {
  785. return this.rtcUtils.getVideoSrc(element);
  786. },
  787. setVideoSrc: function (element, src) {
  788. this.rtcUtils.setVideoSrc(element, src);
  789. },
  790. getVideoElementName: function () {
  791. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  792. },
  793. dispose: function() {
  794. if (this.rtcUtils) {
  795. this.rtcUtils = null;
  796. }
  797. },
  798. stop: function () {
  799. this.dispose();
  800. },
  801. start: function () {
  802. var self = this;
  803. APP.desktopsharing.addListener(
  804. function (stream, isUsingScreenStream, callback) {
  805. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  806. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  807. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  808. DataChannels.init(event.peerconnection, eventEmitter);
  809. });
  810. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  811. DataChannels.handleSelectedEndpointEvent);
  812. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  813. DataChannels.handlePinnedEndpointEvent);
  814. // In case of IE we continue from 'onReady' callback
  815. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  816. // once it is initialized.
  817. var onReady = function () {
  818. eventEmitter.emit(RTCEvents.RTC_READY, true);
  819. self.rtcUtils.obtainAudioAndVideoPermissions(
  820. null, null, getMediaStreamUsage());
  821. };
  822. this.rtcUtils = new RTCUtils(this, onReady);
  823. // Call onReady() if Temasys plugin is not used
  824. if (!RTCBrowserType.isTemasysPluginUsed()) {
  825. onReady();
  826. }
  827. },
  828. muteRemoteVideoStream: function (jid, value) {
  829. var stream;
  830. if(this.remoteStreams[jid] &&
  831. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  832. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  833. }
  834. if(!stream)
  835. return true;
  836. if (value != stream.muted) {
  837. stream.setMute(value);
  838. return true;
  839. }
  840. return false;
  841. },
  842. switchVideoStreams: function (new_stream) {
  843. this.localVideo.stream = new_stream;
  844. this.localStreams = [];
  845. //in firefox we have only one stream object
  846. if (this.localAudio.getOriginalStream() != new_stream)
  847. this.localStreams.push(this.localAudio);
  848. this.localStreams.push(this.localVideo);
  849. },
  850. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  851. var oldStream = this.localVideo.getOriginalStream();
  852. var type = (isUsingScreenStream ? "screen" : "camera");
  853. var localCallback = callback;
  854. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  855. localCallback = function() {
  856. APP.xmpp.setVideoMute(false, function(mute) {
  857. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  858. });
  859. callback();
  860. };
  861. }
  862. // FIXME: Workaround for FF/IE/Safari
  863. if (stream && stream.videoStream) {
  864. stream = stream.videoStream;
  865. }
  866. var videoStream = this.rtcUtils.createStream(stream, true);
  867. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  868. // Stop the stream to trigger onended event for old stream
  869. oldStream.stop();
  870. this.switchVideoStreams(videoStream, oldStream);
  871. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  872. },
  873. changeLocalAudio: function (stream, callback) {
  874. var oldStream = this.localAudio.getOriginalStream();
  875. var newStream = this.rtcUtils.createStream(stream);
  876. this.localAudio = this.createLocalStream(newStream, "audio", true);
  877. // Stop the stream to trigger onended event for old stream
  878. oldStream.stop();
  879. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  880. },
  881. isVideoMuted: function (jid) {
  882. if (jid === APP.xmpp.myJid()) {
  883. var localVideo = APP.RTC.localVideo;
  884. return (!localVideo || localVideo.isMuted());
  885. } else {
  886. if (!APP.RTC.remoteStreams[jid] ||
  887. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  888. return null;
  889. }
  890. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  891. }
  892. },
  893. setVideoMute: function (mute, callback, options) {
  894. if (!this.localVideo)
  895. return;
  896. if (mute == APP.RTC.localVideo.isMuted())
  897. {
  898. APP.xmpp.sendVideoInfoPresence(mute);
  899. if (callback)
  900. callback(mute);
  901. }
  902. else
  903. {
  904. APP.RTC.localVideo.setMute(mute);
  905. APP.xmpp.setVideoMute(
  906. mute,
  907. callback,
  908. options);
  909. }
  910. },
  911. setDeviceAvailability: function (devices) {
  912. if(!devices)
  913. return;
  914. if(devices.audio === true || devices.audio === false)
  915. this.devices.audio = devices.audio;
  916. if(devices.video === true || devices.video === false)
  917. this.devices.video = devices.video;
  918. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  919. }
  920. };
  921. module.exports = RTC;
  922. },{"../../service/RTC/MediaStreamTypes":66,"../../service/RTC/RTCEvents.js":67,"../../service/RTC/StreamEventTypes.js":69,"../../service/UI/UIEvents":70,"../../service/desktopsharing/DesktopSharingEventTypes":72,"../../service/xmpp/XMPPEvents":73,"./DataChannels":8,"./LocalStream.js":9,"./MediaStream.js":10,"./RTCBrowserType":12,"./RTCUtils.js":13,"events":74}],12:[function(require,module,exports){
  923. var currentBrowser;
  924. var browserVersion;
  925. var RTCBrowserType = {
  926. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  927. RTC_BROWSER_OPERA: "rtc_browser.opera",
  928. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  929. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  930. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  931. getBrowserType: function () {
  932. return currentBrowser;
  933. },
  934. isChrome: function () {
  935. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  936. },
  937. isOpera: function () {
  938. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  939. },
  940. isFirefox: function () {
  941. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  942. },
  943. isIExplorer: function () {
  944. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  945. },
  946. isSafari: function () {
  947. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  948. },
  949. isTemasysPluginUsed: function () {
  950. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  951. },
  952. getFirefoxVersion: function () {
  953. return RTCBrowserType.isFirefox() ? browserVersion : null;
  954. },
  955. getChromeVersion: function () {
  956. return RTCBrowserType.isChrome() ? browserVersion : null;
  957. },
  958. usesPlanB: function() {
  959. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  960. RTCBrowserType.isTemasysPluginUsed();
  961. },
  962. usesUnifiedPlan: function() {
  963. return RTCBrowserType.isFirefox();
  964. }
  965. // Add version getters for other browsers when needed
  966. };
  967. // detectOpera() must be called before detectChrome() !!!
  968. // otherwise Opera wil be detected as Chrome
  969. function detectChrome() {
  970. if (navigator.webkitGetUserMedia) {
  971. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  972. var userAgent = navigator.userAgent.toLowerCase();
  973. // We can assume that user agent is chrome, because it's
  974. // enforced when 'ext' streaming method is set
  975. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  976. console.log("This appears to be Chrome, ver: " + ver);
  977. return ver;
  978. }
  979. return null;
  980. }
  981. function detectOpera() {
  982. var userAgent = navigator.userAgent;
  983. if (userAgent.match(/Opera|OPR/)) {
  984. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  985. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  986. console.info("This appears to be Opera, ver: " + version);
  987. return version;
  988. }
  989. return null;
  990. }
  991. function detectFirefox() {
  992. if (navigator.mozGetUserMedia) {
  993. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  994. var version = parseInt(
  995. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  996. console.log('This appears to be Firefox, ver: ' + version);
  997. return version;
  998. }
  999. return null;
  1000. }
  1001. function detectSafari() {
  1002. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1003. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1004. console.info("This appears to be Safari");
  1005. // FIXME detect Safari version when needed
  1006. return 1;
  1007. }
  1008. return null;
  1009. }
  1010. function detectIE() {
  1011. var version;
  1012. var ua = window.navigator.userAgent;
  1013. var msie = ua.indexOf('MSIE ');
  1014. if (msie > 0) {
  1015. // IE 10 or older => return version number
  1016. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1017. }
  1018. var trident = ua.indexOf('Trident/');
  1019. if (!version && trident > 0) {
  1020. // IE 11 => return version number
  1021. var rv = ua.indexOf('rv:');
  1022. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1023. }
  1024. var edge = ua.indexOf('Edge/');
  1025. if (!version && edge > 0) {
  1026. // IE 12 => return version number
  1027. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1028. }
  1029. if (version) {
  1030. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1031. console.info("This appears to be IExplorer, ver: " + version);
  1032. }
  1033. return version;
  1034. }
  1035. function detectBrowser() {
  1036. var version;
  1037. var detectors = [
  1038. detectOpera,
  1039. detectChrome,
  1040. detectFirefox,
  1041. detectIE,
  1042. detectSafari
  1043. ];
  1044. // Try all browser detectors
  1045. for (var i = 0; i < detectors.length; i++) {
  1046. version = detectors[i]();
  1047. if (version)
  1048. return version;
  1049. }
  1050. console.error("Failed to detect browser type");
  1051. return undefined;
  1052. }
  1053. browserVersion = detectBrowser();
  1054. module.exports = RTCBrowserType;
  1055. },{}],13:[function(require,module,exports){
  1056. /* global config, require, attachMediaStream, getUserMedia */
  1057. var RTCBrowserType = require("./RTCBrowserType");
  1058. var Resolutions = require("../../service/RTC/Resolutions");
  1059. var AdapterJS = require("./adapter.screenshare");
  1060. var SDPUtil = require("../xmpp/SDPUtil");
  1061. var currentResolution = null;
  1062. function getPreviousResolution(resolution) {
  1063. if(!Resolutions[resolution])
  1064. return null;
  1065. var order = Resolutions[resolution].order;
  1066. var res = null;
  1067. var resName = null;
  1068. for(var i in Resolutions) {
  1069. var tmp = Resolutions[i];
  1070. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1071. resName = i;
  1072. res = tmp;
  1073. }
  1074. }
  1075. return resName;
  1076. }
  1077. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1078. if (Resolutions[resolution]) {
  1079. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1080. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1081. }
  1082. else if (isAndroid) {
  1083. // FIXME can't remember if the purpose of this was to always request
  1084. // low resolution on Android ? if yes it should be moved up front
  1085. constraints.video.mandatory.minWidth = 320;
  1086. constraints.video.mandatory.minHeight = 240;
  1087. constraints.video.mandatory.maxFrameRate = 15;
  1088. }
  1089. if (constraints.video.mandatory.minWidth)
  1090. constraints.video.mandatory.maxWidth =
  1091. constraints.video.mandatory.minWidth;
  1092. if (constraints.video.mandatory.minHeight)
  1093. constraints.video.mandatory.maxHeight =
  1094. constraints.video.mandatory.minHeight;
  1095. }
  1096. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1097. {
  1098. var constraints = {audio: false, video: false};
  1099. if (um.indexOf('video') >= 0) {
  1100. // same behaviour as true
  1101. constraints.video = { mandatory: {}, optional: [] };
  1102. constraints.video.optional.push({ googLeakyBucket: true });
  1103. setResolutionConstraints(constraints, resolution, isAndroid);
  1104. }
  1105. if (um.indexOf('audio') >= 0) {
  1106. if (!RTCBrowserType.isFirefox()) {
  1107. // same behaviour as true
  1108. constraints.audio = { mandatory: {}, optional: []};
  1109. // if it is good enough for hangouts...
  1110. constraints.audio.optional.push(
  1111. {googEchoCancellation: true},
  1112. {googAutoGainControl: true},
  1113. {googNoiseSupression: true},
  1114. {googHighpassFilter: true},
  1115. {googNoisesuppression2: true},
  1116. {googEchoCancellation2: true},
  1117. {googAutoGainControl2: true}
  1118. );
  1119. } else {
  1120. constraints.audio = true;
  1121. }
  1122. }
  1123. if (um.indexOf('screen') >= 0) {
  1124. if (RTCBrowserType.isChrome()) {
  1125. constraints.video = {
  1126. mandatory: {
  1127. chromeMediaSource: "screen",
  1128. googLeakyBucket: true,
  1129. maxWidth: window.screen.width,
  1130. maxHeight: window.screen.height,
  1131. maxFrameRate: 3
  1132. },
  1133. optional: []
  1134. };
  1135. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1136. constraints.video = {
  1137. optional: [
  1138. {
  1139. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1140. }
  1141. ]
  1142. };
  1143. } else {
  1144. console.error(
  1145. "'screen' WebRTC media source is supported only in Chrome" +
  1146. " and with Temasys plugin");
  1147. }
  1148. }
  1149. if (um.indexOf('desktop') >= 0) {
  1150. constraints.video = {
  1151. mandatory: {
  1152. chromeMediaSource: "desktop",
  1153. chromeMediaSourceId: desktopStream,
  1154. googLeakyBucket: true,
  1155. maxWidth: window.screen.width,
  1156. maxHeight: window.screen.height,
  1157. maxFrameRate: 3
  1158. },
  1159. optional: []
  1160. };
  1161. }
  1162. if (bandwidth) {
  1163. if (!constraints.video) {
  1164. //same behaviour as true
  1165. constraints.video = {mandatory: {}, optional: []};
  1166. }
  1167. constraints.video.optional.push({bandwidth: bandwidth});
  1168. }
  1169. if (fps) {
  1170. // for some cameras it might be necessary to request 30fps
  1171. // so they choose 30fps mjpg over 10fps yuy2
  1172. if (!constraints.video) {
  1173. // same behaviour as true;
  1174. constraints.video = {mandatory: {}, optional: []};
  1175. }
  1176. constraints.video.mandatory.minFrameRate = fps;
  1177. }
  1178. return constraints;
  1179. }
  1180. //Options parameter is to pass config options. Currently uses only "useIPv6".
  1181. function RTCUtils(RTCService, onTemasysPluginReady, options)
  1182. {
  1183. var self = this;
  1184. this.service = RTCService;
  1185. if (RTCBrowserType.isFirefox()) {
  1186. var FFversion = RTCBrowserType.getFirefoxVersion();
  1187. if (FFversion >= 40) {
  1188. this.peerconnection = mozRTCPeerConnection;
  1189. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1190. this.pc_constraints = {};
  1191. this.attachMediaStream = function (element, stream) {
  1192. // srcObject is being standardized and FF will eventually
  1193. // support that unprefixed. FF also supports the
  1194. // "element.src = URL.createObjectURL(...)" combo, but that
  1195. // will be deprecated in favour of srcObject.
  1196. //
  1197. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1198. // https://github.com/webrtc/samples/issues/302
  1199. if(!element[0])
  1200. return;
  1201. element[0].mozSrcObject = stream;
  1202. element[0].play();
  1203. };
  1204. this.getStreamID = function (stream) {
  1205. var id = stream.id;
  1206. if (!id) {
  1207. var tracks = stream.getVideoTracks();
  1208. if (!tracks || tracks.length === 0) {
  1209. tracks = stream.getAudioTracks();
  1210. }
  1211. id = tracks[0].id;
  1212. }
  1213. return SDPUtil.filter_special_chars(id);
  1214. };
  1215. this.getVideoSrc = function (element) {
  1216. if(!element)
  1217. return null;
  1218. return element.mozSrcObject;
  1219. };
  1220. this.setVideoSrc = function (element, src) {
  1221. if(element)
  1222. element.mozSrcObject = src;
  1223. };
  1224. RTCSessionDescription = mozRTCSessionDescription;
  1225. RTCIceCandidate = mozRTCIceCandidate;
  1226. } else {
  1227. console.error(
  1228. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1229. window.location.href = 'unsupported_browser.html';
  1230. return;
  1231. }
  1232. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1233. this.peerconnection = webkitRTCPeerConnection;
  1234. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1235. this.attachMediaStream = function (element, stream) {
  1236. element.attr('src', webkitURL.createObjectURL(stream));
  1237. };
  1238. this.getStreamID = function (stream) {
  1239. // streams from FF endpoints have the characters '{' and '}'
  1240. // that make jQuery choke.
  1241. return SDPUtil.filter_special_chars(stream.id);
  1242. };
  1243. this.getVideoSrc = function (element) {
  1244. if(!element)
  1245. return null;
  1246. return element.getAttribute("src");
  1247. };
  1248. this.setVideoSrc = function (element, src) {
  1249. if(element)
  1250. element.setAttribute("src", src);
  1251. };
  1252. // DTLS should now be enabled by default but..
  1253. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1254. if (options.useIPv6) {
  1255. // https://code.google.com/p/webrtc/issues/detail?id=2828
  1256. this.pc_constraints.optional.push({googIPv6: true});
  1257. }
  1258. if (navigator.userAgent.indexOf('Android') != -1) {
  1259. this.pc_constraints = {}; // disable DTLS on Android
  1260. }
  1261. if (!webkitMediaStream.prototype.getVideoTracks) {
  1262. webkitMediaStream.prototype.getVideoTracks = function () {
  1263. return this.videoTracks;
  1264. };
  1265. }
  1266. if (!webkitMediaStream.prototype.getAudioTracks) {
  1267. webkitMediaStream.prototype.getAudioTracks = function () {
  1268. return this.audioTracks;
  1269. };
  1270. }
  1271. }
  1272. // Detect IE/Safari
  1273. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1274. //AdapterJS.WebRTCPlugin.setLogLevel(
  1275. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1276. AdapterJS.webRTCReady(function (isPlugin) {
  1277. self.peerconnection = RTCPeerConnection;
  1278. self.getUserMedia = getUserMedia;
  1279. self.attachMediaStream = function (elSel, stream) {
  1280. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1281. return;
  1282. }
  1283. attachMediaStream(elSel[0], stream);
  1284. };
  1285. self.getStreamID = function (stream) {
  1286. var id = SDPUtil.filter_special_chars(stream.label);
  1287. return id;
  1288. };
  1289. self.getVideoSrc = function (element) {
  1290. if (!element) {
  1291. console.warn("Attempt to get video SRC of null element");
  1292. return null;
  1293. }
  1294. var children = element.children;
  1295. for (var i = 0; i !== children.length; ++i) {
  1296. if (children[i].name === 'streamId') {
  1297. return children[i].value;
  1298. }
  1299. }
  1300. //console.info(element.id + " SRC: " + src);
  1301. return null;
  1302. };
  1303. self.setVideoSrc = function (element, src) {
  1304. //console.info("Set video src: ", element, src);
  1305. if (!src) {
  1306. console.warn("Not attaching video stream, 'src' is null");
  1307. return;
  1308. }
  1309. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1310. var stream = AdapterJS.WebRTCPlugin.plugin
  1311. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1312. attachMediaStream(element, stream);
  1313. };
  1314. onTemasysPluginReady(isPlugin);
  1315. });
  1316. } else {
  1317. try {
  1318. console.log('Browser does not appear to be WebRTC-capable');
  1319. } catch (e) { }
  1320. window.location.href = 'unsupported_browser.html';
  1321. }
  1322. }
  1323. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1324. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1325. desktopStream) {
  1326. currentResolution = resolution;
  1327. // Check if we are running on Android device
  1328. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1329. var constraints = getConstraints(
  1330. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1331. console.info("Get media constraints", constraints);
  1332. var self = this;
  1333. try {
  1334. this.getUserMedia(constraints,
  1335. function (stream) {
  1336. console.log('onUserMediaSuccess');
  1337. self.setAvailableDevices(um, true);
  1338. success_callback(stream);
  1339. },
  1340. function (error) {
  1341. self.setAvailableDevices(um, false);
  1342. console.warn('Failed to get access to local media. Error ',
  1343. error, constraints);
  1344. if (failure_callback) {
  1345. failure_callback(error);
  1346. }
  1347. });
  1348. } catch (e) {
  1349. console.error('GUM failed: ', e);
  1350. if(failure_callback) {
  1351. failure_callback(e);
  1352. }
  1353. }
  1354. };
  1355. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1356. var devices = {};
  1357. if(um.indexOf("video") != -1) {
  1358. devices.video = available;
  1359. }
  1360. if(um.indexOf("audio") != -1) {
  1361. devices.audio = available;
  1362. }
  1363. this.service.setDeviceAvailability(devices);
  1364. };
  1365. /**
  1366. * We ask for audio and video combined stream in order to get permissions and
  1367. * not to ask twice.
  1368. */
  1369. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1370. function(devices, callback, usageOptions)
  1371. {
  1372. var self = this;
  1373. // Get AV
  1374. var successCallback = function (stream) {
  1375. if(callback)
  1376. callback(stream, usageOptions);
  1377. else
  1378. self.successCallback(stream, usageOptions);
  1379. };
  1380. if(!devices)
  1381. devices = ['audio', 'video'];
  1382. var newDevices = [];
  1383. if(usageOptions)
  1384. for(var i = 0; i < devices.length; i++) {
  1385. var device = devices[i];
  1386. if(usageOptions[device] === true)
  1387. newDevices.push(device);
  1388. }
  1389. else
  1390. newDevices = devices;
  1391. if(newDevices.length === 0) {
  1392. successCallback();
  1393. return;
  1394. }
  1395. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1396. // With FF/IE we can't split the stream into audio and video because FF
  1397. // doesn't support media stream constructors. So, we need to get the
  1398. // audio stream separately from the video stream using two distinct GUM
  1399. // calls. Not very user friendly :-( but we don't have many other
  1400. // options neither.
  1401. //
  1402. // Note that we pack those 2 streams in a single object and pass it to
  1403. // the successCallback method.
  1404. var obtainVideo = function (audioStream) {
  1405. self.getUserMediaWithConstraints(
  1406. ['video'],
  1407. function (videoStream) {
  1408. return successCallback({
  1409. audioStream: audioStream,
  1410. videoStream: videoStream
  1411. });
  1412. },
  1413. function (error) {
  1414. console.error(
  1415. 'failed to obtain video stream - stop', error);
  1416. self.errorCallback(error);
  1417. },
  1418. config.resolution || '360');
  1419. };
  1420. var obtainAudio = function () {
  1421. self.getUserMediaWithConstraints(
  1422. ['audio'],
  1423. function (audioStream) {
  1424. if (newDevices.indexOf('video') !== -1)
  1425. obtainVideo(audioStream);
  1426. },
  1427. function (error) {
  1428. console.error(
  1429. 'failed to obtain audio stream - stop', error);
  1430. self.errorCallback(error);
  1431. }
  1432. );
  1433. };
  1434. if (newDevices.indexOf('audio') !== -1) {
  1435. obtainAudio();
  1436. } else {
  1437. obtainVideo(null);
  1438. }
  1439. } else {
  1440. this.getUserMediaWithConstraints(
  1441. newDevices,
  1442. function (stream) {
  1443. successCallback(stream);
  1444. },
  1445. function (error) {
  1446. self.errorCallback(error);
  1447. },
  1448. config.resolution || '360');
  1449. }
  1450. };
  1451. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1452. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1453. // it's an object with two properties: audioStream, videoStream.
  1454. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1455. console.log('got', stream, stream.getAudioTracks().length,
  1456. stream.getVideoTracks().length);
  1457. this.handleLocalStream(stream, usageOptions);
  1458. };
  1459. RTCUtils.prototype.errorCallback = function (error) {
  1460. var self = this;
  1461. console.error('failed to obtain audio/video stream - trying audio only', error);
  1462. var resolution = getPreviousResolution(currentResolution);
  1463. if(typeof error == "object" && error.constraintName && error.name
  1464. && (error.name == "ConstraintNotSatisfiedError" ||
  1465. error.name == "OverconstrainedError") &&
  1466. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1467. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1468. && resolution != null)
  1469. {
  1470. self.getUserMediaWithConstraints(['audio', 'video'],
  1471. function (stream) {
  1472. return self.successCallback(stream);
  1473. }, function (error) {
  1474. return self.errorCallback(error);
  1475. }, resolution);
  1476. }
  1477. else {
  1478. self.getUserMediaWithConstraints(
  1479. ['audio'],
  1480. function (stream) {
  1481. return self.successCallback(stream);
  1482. },
  1483. function (error) {
  1484. console.error('failed to obtain audio/video stream - stop',
  1485. error);
  1486. return self.successCallback(null);
  1487. }
  1488. );
  1489. }
  1490. };
  1491. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1492. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1493. // an object with two properties: audioStream, videoStream.
  1494. var audioStream, videoStream;
  1495. if(window.webkitMediaStream)
  1496. {
  1497. audioStream = new webkitMediaStream();
  1498. videoStream = new webkitMediaStream();
  1499. if(stream) {
  1500. var audioTracks = stream.getAudioTracks();
  1501. for (var i = 0; i < audioTracks.length; i++) {
  1502. audioStream.addTrack(audioTracks[i]);
  1503. }
  1504. var videoTracks = stream.getVideoTracks();
  1505. for (i = 0; i < videoTracks.length; i++) {
  1506. videoStream.addTrack(videoTracks[i]);
  1507. }
  1508. }
  1509. }
  1510. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1511. { // Firefox and Temasys plugin
  1512. if (stream && stream.audioStream)
  1513. audioStream = stream.audioStream;
  1514. else
  1515. audioStream = new DummyMediaStream("dummyAudio");
  1516. if (stream && stream.videoStream)
  1517. videoStream = stream.videoStream;
  1518. else
  1519. videoStream = new DummyMediaStream("dummyVideo");
  1520. }
  1521. var audioMuted = (usageOptions && usageOptions.audio === false),
  1522. videoMuted = (usageOptions && usageOptions.video === false);
  1523. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1524. videoGUM = (!usageOptions || usageOptions.video !== false);
  1525. this.service.createLocalStream(audioStream, "audio", null, null,
  1526. audioMuted, audioGUM);
  1527. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1528. videoMuted, videoGUM);
  1529. };
  1530. function DummyMediaStream(id) {
  1531. this.id = id;
  1532. this.label = id;
  1533. this.stop = function() { };
  1534. this.getAudioTracks = function() { return []; };
  1535. this.getVideoTracks = function() { return []; };
  1536. }
  1537. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1538. var newStream = null;
  1539. if (window.webkitMediaStream) {
  1540. newStream = new webkitMediaStream();
  1541. if (newStream) {
  1542. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1543. for (var i = 0; i < tracks.length; i++) {
  1544. newStream.addTrack(tracks[i]);
  1545. }
  1546. }
  1547. }
  1548. else {
  1549. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1550. if (stream) {
  1551. newStream = stream;
  1552. } else {
  1553. newStream =
  1554. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1555. }
  1556. }
  1557. return newStream;
  1558. };
  1559. module.exports = RTCUtils;
  1560. },{"../../service/RTC/Resolutions":68,"../xmpp/SDPUtil":21,"./RTCBrowserType":12,"./adapter.screenshare":14}],14:[function(require,module,exports){
  1561. /*! adapterjs - custom version from - 2015-08-12 */
  1562. // Adapter's interface.
  1563. var AdapterJS = AdapterJS || {};
  1564. // Browserify compatibility
  1565. if(typeof exports !== 'undefined') {
  1566. module.exports = AdapterJS;
  1567. }
  1568. AdapterJS.options = AdapterJS.options || {};
  1569. // uncomment to get virtual webcams
  1570. // AdapterJS.options.getAllCams = true;
  1571. // uncomment to prevent the install prompt when the plugin in not yet installed
  1572. // AdapterJS.options.hidePluginInstallPrompt = true;
  1573. // AdapterJS version
  1574. AdapterJS.VERSION = '0.11.1';
  1575. // This function will be called when the WebRTC API is ready to be used
  1576. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1577. // the plugin
  1578. // You may Override this function to synchronise the start of your application
  1579. // with the WebRTC API being ready.
  1580. // If you decide not to override use this synchronisation, it may result in
  1581. // an extensive CPU usage on the plugin start (once per tab loaded)
  1582. // Params:
  1583. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1584. //
  1585. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1586. // The WebRTC API is ready.
  1587. // Override me and do whatever you want here
  1588. };
  1589. // Sets a callback function to be called when the WebRTC interface is ready.
  1590. // The first argument is the function to callback.\
  1591. // Throws an error if the first argument is not a function
  1592. AdapterJS.webRTCReady = function (callback) {
  1593. if (typeof callback !== 'function') {
  1594. throw new Error('Callback provided is not a function');
  1595. }
  1596. if (true === AdapterJS.onwebrtcreadyDone) {
  1597. // All WebRTC interfaces are ready, just call the callback
  1598. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1599. } else {
  1600. // will be triggered automatically when your browser/plugin is ready.
  1601. AdapterJS.onwebrtcready = callback;
  1602. }
  1603. };
  1604. // Plugin namespace
  1605. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1606. // The object to store plugin information
  1607. AdapterJS.WebRTCPlugin.pluginInfo = {
  1608. prefix : 'Tem',
  1609. plugName : 'TemWebRTCPlugin',
  1610. pluginId : 'plugin0',
  1611. type : 'application/x-temwebrtcplugin',
  1612. onload : '__TemWebRTCReady0',
  1613. portalLink : 'http://skylink.io/plugin/',
  1614. downloadLink : null, //set below
  1615. companyName: 'Temasys'
  1616. };
  1617. if(!!navigator.platform.match(/^Mac/i)) {
  1618. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1619. }
  1620. else if(!!navigator.platform.match(/^Win/i)) {
  1621. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1622. }
  1623. // Unique identifier of each opened page
  1624. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1625. // Use this whenever you want to call the plugin.
  1626. AdapterJS.WebRTCPlugin.plugin = null;
  1627. // Set log level for the plugin once it is ready.
  1628. // The different values are
  1629. // This is an asynchronous function that will run when the plugin is ready
  1630. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1631. // Defines webrtc's JS interface according to the plugin's implementation.
  1632. // Define plugin Browsers as WebRTC Interface.
  1633. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1634. // This function detects whether or not a plugin is installed.
  1635. // Checks if Not IE (firefox, for example), else if it's IE,
  1636. // we're running IE and do something. If not it is not supported.
  1637. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1638. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1639. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1640. // Inject the HTML DOM object element into the page.
  1641. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1642. // States of readiness that the plugin goes through when
  1643. // being injected and stated
  1644. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1645. NONE : 0, // no plugin use
  1646. INITIALIZING : 1, // Detected need for plugin
  1647. INJECTING : 2, // Injecting plugin
  1648. INJECTED: 3, // Plugin element injected but not usable yet
  1649. READY: 4 // Plugin ready to be used
  1650. };
  1651. // Current state of the plugin. You cannot use the plugin before this is
  1652. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1653. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1654. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1655. // Used to make sure AdapterJS.onwebrtcready is only called once
  1656. AdapterJS.onwebrtcreadyDone = false;
  1657. // Log levels for the plugin.
  1658. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1659. /*
  1660. Log outputs are prefixed in some cases.
  1661. INFO: Information reported by the plugin.
  1662. ERROR: Errors originating from within the plugin.
  1663. WEBRTC: Error originating from within the libWebRTC library
  1664. */
  1665. // From the least verbose to the most verbose
  1666. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1667. NONE : 'NONE',
  1668. ERROR : 'ERROR',
  1669. WARNING : 'WARNING',
  1670. INFO: 'INFO',
  1671. VERBOSE: 'VERBOSE',
  1672. SENSITIVE: 'SENSITIVE'
  1673. };
  1674. // Does a waiting check before proceeding to load the plugin.
  1675. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1676. // This methid will use an interval to wait for the plugin to be ready.
  1677. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1678. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1679. // This function will be called when plugin is ready. It sends necessary
  1680. // details to the plugin.
  1681. // The function will wait for the document to be ready and the set the
  1682. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1683. // indicating that it can start being requested.
  1684. // This function is not in the IE/Safari condition brackets so that
  1685. // TemPluginLoaded function might be called on Chrome/Firefox.
  1686. // This function is the only private function that is not encapsulated to
  1687. // allow the plugin method to be called.
  1688. __TemWebRTCReady0 = function () {
  1689. if (document.readyState === 'complete') {
  1690. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1691. AdapterJS.maybeThroughWebRTCReady();
  1692. } else {
  1693. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1694. if (document.readyState === 'complete') {
  1695. // TODO: update comments, we wait for the document to be ready
  1696. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1697. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1698. AdapterJS.maybeThroughWebRTCReady();
  1699. }
  1700. }, 100);
  1701. }
  1702. };
  1703. AdapterJS.maybeThroughWebRTCReady = function() {
  1704. if (!AdapterJS.onwebrtcreadyDone) {
  1705. AdapterJS.onwebrtcreadyDone = true;
  1706. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1707. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1708. }
  1709. }
  1710. };
  1711. // Text namespace
  1712. AdapterJS.TEXT = {
  1713. PLUGIN: {
  1714. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1715. 'to work on this browser.',
  1716. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1717. BUTTON: 'Install Now'
  1718. },
  1719. REFRESH: {
  1720. REQUIRE_REFRESH: 'Please refresh page',
  1721. BUTTON: 'Refresh Page'
  1722. }
  1723. };
  1724. // The result of ice connection states.
  1725. // - starting: Ice connection is starting.
  1726. // - checking: Ice connection is checking.
  1727. // - connected Ice connection is connected.
  1728. // - completed Ice connection is connected.
  1729. // - done Ice connection has been completed.
  1730. // - disconnected Ice connection has been disconnected.
  1731. // - failed Ice connection has failed.
  1732. // - closed Ice connection is closed.
  1733. AdapterJS._iceConnectionStates = {
  1734. starting : 'starting',
  1735. checking : 'checking',
  1736. connected : 'connected',
  1737. completed : 'connected',
  1738. done : 'completed',
  1739. disconnected : 'disconnected',
  1740. failed : 'failed',
  1741. closed : 'closed'
  1742. };
  1743. //The IceConnection states that has been fired for each peer.
  1744. AdapterJS._iceConnectionFiredStates = [];
  1745. // Check if WebRTC Interface is defined.
  1746. AdapterJS.isDefined = null;
  1747. // This function helps to retrieve the webrtc detected browser information.
  1748. // This sets:
  1749. // - webrtcDetectedBrowser: The browser agent name.
  1750. // - webrtcDetectedVersion: The browser version.
  1751. // - webrtcDetectedType: The types of webRTC support.
  1752. // - 'moz': Mozilla implementation of webRTC.
  1753. // - 'webkit': WebKit implementation of webRTC.
  1754. // - 'plugin': Using the plugin implementation.
  1755. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1756. var hasMatch, checkMatch = navigator.userAgent.match(
  1757. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1758. if (/trident/i.test(checkMatch[1])) {
  1759. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1760. webrtcDetectedBrowser = 'IE';
  1761. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1762. } else if (checkMatch[1] === 'Chrome') {
  1763. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1764. if (hasMatch !== null) {
  1765. webrtcDetectedBrowser = 'opera';
  1766. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1767. }
  1768. }
  1769. if (navigator.userAgent.indexOf('Safari')) {
  1770. if (typeof InstallTrigger !== 'undefined') {
  1771. webrtcDetectedBrowser = 'firefox';
  1772. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1773. webrtcDetectedBrowser = 'IE';
  1774. } else if (
  1775. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1776. webrtcDetectedBrowser = 'safari';
  1777. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1778. webrtcDetectedBrowser = 'opera';
  1779. } else if (!!window.chrome) {
  1780. webrtcDetectedBrowser = 'chrome';
  1781. }
  1782. }
  1783. if (!webrtcDetectedBrowser) {
  1784. webrtcDetectedVersion = checkMatch[1];
  1785. }
  1786. if (!webrtcDetectedVersion) {
  1787. try {
  1788. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1789. [navigator.appName, navigator.appVersion, '-?'];
  1790. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1791. checkMatch.splice(1, 1, hasMatch[1]);
  1792. }
  1793. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1794. } catch (error) { }
  1795. }
  1796. };
  1797. // To fix configuration as some browsers does not support
  1798. // the 'urls' attribute.
  1799. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1800. if (pcConfig === null) {
  1801. return;
  1802. }
  1803. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1804. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1805. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1806. delete pcConfig.iceServers[i].urls;
  1807. }
  1808. }
  1809. };
  1810. AdapterJS.addEvent = function(elem, evnt, func) {
  1811. if (elem.addEventListener) { // W3C DOM
  1812. elem.addEventListener(evnt, func, false);
  1813. } else if (elem.attachEvent) {// OLD IE DOM
  1814. elem.attachEvent('on'+evnt, func);
  1815. } else { // No much to do
  1816. elem[evnt] = func;
  1817. }
  1818. };
  1819. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1820. // only inject once the page is ready
  1821. if (document.readyState !== 'complete') {
  1822. return;
  1823. }
  1824. var w = window;
  1825. var i = document.createElement('iframe');
  1826. i.style.position = 'fixed';
  1827. i.style.top = '-41px';
  1828. i.style.left = 0;
  1829. i.style.right = 0;
  1830. i.style.width = '100%';
  1831. i.style.height = '40px';
  1832. i.style.backgroundColor = '#ffffe1';
  1833. i.style.border = 'none';
  1834. i.style.borderBottom = '1px solid #888888';
  1835. i.style.zIndex = '9999999';
  1836. if(typeof i.style.webkitTransition === 'string') {
  1837. i.style.webkitTransition = 'all .5s ease-out';
  1838. } else if(typeof i.style.transition === 'string') {
  1839. i.style.transition = 'all .5s ease-out';
  1840. }
  1841. document.body.appendChild(i);
  1842. c = (i.contentWindow) ? i.contentWindow :
  1843. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1844. c.document.open();
  1845. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1846. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1847. 'middle; cursor: default;">' + text + '</span>');
  1848. if(buttonText && buttonLink) {
  1849. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1850. c.document.close();
  1851. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1852. if (!!displayRefreshBar) {
  1853. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1854. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1855. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1856. }
  1857. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1858. e.preventDefault();
  1859. try {
  1860. event.cancelBubble = true;
  1861. } catch(error) { }
  1862. var pluginInstallInterval = setInterval(function(){
  1863. if(! isIE) {
  1864. navigator.plugins.refresh(false);
  1865. }
  1866. AdapterJS.WebRTCPlugin.isPluginInstalled(
  1867. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  1868. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  1869. function() {
  1870. clearInterval(pluginInstallInterval);
  1871. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  1872. },
  1873. function() { //Does nothing because not used here
  1874. });
  1875. } , 500);
  1876. });
  1877. }else {
  1878. c.document.close();
  1879. }
  1880. AdapterJS.addEvent(c.document, 'click', function() {
  1881. w.document.body.removeChild(i);
  1882. });
  1883. setTimeout(function() {
  1884. if(typeof i.style.webkitTransform === 'string') {
  1885. i.style.webkitTransform = 'translateY(40px)';
  1886. } else if(typeof i.style.transform === 'string') {
  1887. i.style.transform = 'translateY(40px)';
  1888. } else {
  1889. i.style.top = '0px';
  1890. }
  1891. }, 300);
  1892. };
  1893. // -----------------------------------------------------------
  1894. // Detected webrtc implementation. Types are:
  1895. // - 'moz': Mozilla implementation of webRTC.
  1896. // - 'webkit': WebKit implementation of webRTC.
  1897. // - 'plugin': Using the plugin implementation.
  1898. webrtcDetectedType = null;
  1899. // Detected webrtc datachannel support. Types are:
  1900. // - 'SCTP': SCTP datachannel support.
  1901. // - 'RTP': RTP datachannel support.
  1902. webrtcDetectedDCSupport = null;
  1903. // Set the settings for creating DataChannels, MediaStream for
  1904. // Cross-browser compability.
  1905. // - This is only for SCTP based support browsers.
  1906. // the 'urls' attribute.
  1907. checkMediaDataChannelSettings =
  1908. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1909. if (typeof callback !== 'function') {
  1910. return;
  1911. }
  1912. var beOfferer = true;
  1913. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1914. // Nightly version does not require MozDontOfferDataChannel for interop
  1915. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1916. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1917. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1918. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1919. // Resends an updated version of constraints for MozDataChannel to work
  1920. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1921. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1922. try {
  1923. delete constraints.mandatory.MozDontOfferDataChannel;
  1924. } catch (error) {
  1925. console.error('Failed deleting MozDontOfferDataChannel');
  1926. console.error(error);
  1927. }
  1928. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1929. constraints.mandatory.MozDontOfferDataChannel = true;
  1930. }
  1931. if (!isLocalFirefox) {
  1932. // temporary measure to remove Moz* constraints in non Firefox browsers
  1933. for (var prop in constraints.mandatory) {
  1934. if (constraints.mandatory.hasOwnProperty(prop)) {
  1935. if (prop.indexOf('Moz') !== -1) {
  1936. delete constraints.mandatory[prop];
  1937. }
  1938. }
  1939. }
  1940. }
  1941. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1942. // interopability of the media stream
  1943. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1944. beOfferer = false;
  1945. }
  1946. callback(beOfferer, constraints);
  1947. };
  1948. // Handles the differences for all browsers ice connection state output.
  1949. // - Tested outcomes are:
  1950. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1951. // - Chrome (answerer) : 'checking' > 'connected'
  1952. // - Firefox (offerer) : 'checking' > 'connected'
  1953. // - Firefox (answerer): 'checking' > 'connected'
  1954. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1955. if (typeof callback !== 'function') {
  1956. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1957. return;
  1958. }
  1959. peerId = (peerId) ? peerId : 'peer';
  1960. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1961. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1962. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1963. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1964. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1965. }
  1966. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1967. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1968. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1969. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1970. setTimeout(function () {
  1971. AdapterJS._iceConnectionFiredStates[peerId]
  1972. .push(AdapterJS._iceConnectionStates.done);
  1973. callback(AdapterJS._iceConnectionStates.done);
  1974. }, 1000);
  1975. }
  1976. callback(iceConnectionState);
  1977. }
  1978. return;
  1979. };
  1980. // Firefox:
  1981. // - Creates iceServer from the url for Firefox.
  1982. // - Create iceServer with stun url.
  1983. // - Create iceServer with turn url.
  1984. // - Ignore the transport parameter from TURN url for FF version <=27.
  1985. // - Return null for createIceServer if transport=tcp.
  1986. // - FF 27 and above supports transport parameters in TURN url,
  1987. // - So passing in the full url to create iceServer.
  1988. // Chrome:
  1989. // - Creates iceServer from the url for Chrome M33 and earlier.
  1990. // - Create iceServer with stun url.
  1991. // - Chrome M28 & above uses below TURN format.
  1992. // Plugin:
  1993. // - Creates Ice Server for Plugin Browsers
  1994. // - If Stun - Create iceServer with stun url.
  1995. // - Else - Create iceServer with turn url
  1996. // - This is a WebRTC Function
  1997. createIceServer = null;
  1998. // Firefox:
  1999. // - Creates IceServers for Firefox
  2000. // - Use .url for FireFox.
  2001. // - Multiple Urls support
  2002. // Chrome:
  2003. // - Creates iceServers from the urls for Chrome M34 and above.
  2004. // - .urls is supported since Chrome M34.
  2005. // - Multiple Urls support
  2006. // Plugin:
  2007. // - Creates Ice Servers for Plugin Browsers
  2008. // - Multiple Urls support
  2009. // - This is a WebRTC Function
  2010. createIceServers = null;
  2011. //------------------------------------------------------------
  2012. //The RTCPeerConnection object.
  2013. RTCPeerConnection = null;
  2014. // Creates RTCSessionDescription object for Plugin Browsers
  2015. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2016. RTCSessionDescription : null;
  2017. // Creates RTCIceCandidate object for Plugin Browsers
  2018. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2019. RTCIceCandidate : null;
  2020. // Get UserMedia (only difference is the prefix).
  2021. // Code from Adam Barth.
  2022. getUserMedia = null;
  2023. // Attach a media stream to an element.
  2024. attachMediaStream = null;
  2025. // Re-attach a media stream to an element.
  2026. reattachMediaStream = null;
  2027. // Detected browser agent name. Types are:
  2028. // - 'firefox': Firefox browser.
  2029. // - 'chrome': Chrome browser.
  2030. // - 'opera': Opera browser.
  2031. // - 'safari': Safari browser.
  2032. // - 'IE' - Internet Explorer browser.
  2033. webrtcDetectedBrowser = null;
  2034. // Detected browser version.
  2035. webrtcDetectedVersion = null;
  2036. // Check for browser types and react accordingly
  2037. if (navigator.mozGetUserMedia) {
  2038. webrtcDetectedBrowser = 'firefox';
  2039. webrtcDetectedVersion = parseInt(navigator
  2040. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2041. webrtcDetectedType = 'moz';
  2042. webrtcDetectedDCSupport = 'SCTP';
  2043. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2044. AdapterJS.maybeFixConfiguration(pcConfig);
  2045. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2046. };
  2047. // The RTCSessionDescription object.
  2048. RTCSessionDescription = mozRTCSessionDescription;
  2049. window.RTCSessionDescription = RTCSessionDescription;
  2050. // The RTCIceCandidate object.
  2051. RTCIceCandidate = mozRTCIceCandidate;
  2052. window.RTCIceCandidate = RTCIceCandidate;
  2053. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2054. navigator.getUserMedia = window.getUserMedia;
  2055. // Shim for MediaStreamTrack.getSources.
  2056. MediaStreamTrack.getSources = function(successCb) {
  2057. setTimeout(function() {
  2058. var infos = [
  2059. { kind: 'audio', id: 'default', label:'', facing:'' },
  2060. { kind: 'video', id: 'default', label:'', facing:'' }
  2061. ];
  2062. successCb(infos);
  2063. }, 0);
  2064. };
  2065. createIceServer = function (url, username, password) {
  2066. var iceServer = null;
  2067. var url_parts = url.split(':');
  2068. if (url_parts[0].indexOf('stun') === 0) {
  2069. iceServer = { url : url };
  2070. } else if (url_parts[0].indexOf('turn') === 0) {
  2071. if (webrtcDetectedVersion < 27) {
  2072. var turn_url_parts = url.split('?');
  2073. if (turn_url_parts.length === 1 ||
  2074. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2075. iceServer = {
  2076. url : turn_url_parts[0],
  2077. credential : password,
  2078. username : username
  2079. };
  2080. }
  2081. } else {
  2082. iceServer = {
  2083. url : url,
  2084. credential : password,
  2085. username : username
  2086. };
  2087. }
  2088. }
  2089. return iceServer;
  2090. };
  2091. createIceServers = function (urls, username, password) {
  2092. var iceServers = [];
  2093. for (i = 0; i < urls.length; i++) {
  2094. var iceServer = createIceServer(urls[i], username, password);
  2095. if (iceServer !== null) {
  2096. iceServers.push(iceServer);
  2097. }
  2098. }
  2099. return iceServers;
  2100. };
  2101. attachMediaStream = function (element, stream) {
  2102. element.mozSrcObject = stream;
  2103. if (stream !== null)
  2104. element.play();
  2105. return element;
  2106. };
  2107. reattachMediaStream = function (to, from) {
  2108. to.mozSrcObject = from.mozSrcObject;
  2109. to.play();
  2110. return to;
  2111. };
  2112. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2113. if (!callback) {
  2114. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2115. ': 1 argument required, but only 0 present.');
  2116. }
  2117. return callback([]);
  2118. };
  2119. // Fake get{Video,Audio}Tracks
  2120. if (!MediaStream.prototype.getVideoTracks) {
  2121. MediaStream.prototype.getVideoTracks = function () {
  2122. return [];
  2123. };
  2124. }
  2125. if (!MediaStream.prototype.getAudioTracks) {
  2126. MediaStream.prototype.getAudioTracks = function () {
  2127. return [];
  2128. };
  2129. }
  2130. AdapterJS.maybeThroughWebRTCReady();
  2131. } else if (navigator.webkitGetUserMedia) {
  2132. webrtcDetectedBrowser = 'chrome';
  2133. webrtcDetectedType = 'webkit';
  2134. webrtcDetectedVersion = parseInt(navigator
  2135. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2136. // check if browser is opera 20+
  2137. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2138. if (checkIfOpera !== null) {
  2139. webrtcDetectedBrowser = 'opera';
  2140. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2141. }
  2142. // check browser datachannel support
  2143. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2144. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2145. webrtcDetectedDCSupport = 'SCTP';
  2146. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2147. webrtcDetectedVersion > 24) {
  2148. webrtcDetectedDCSupport = 'RTP';
  2149. } else {
  2150. webrtcDetectedDCSupport = '';
  2151. }
  2152. createIceServer = function (url, username, password) {
  2153. var iceServer = null;
  2154. var url_parts = url.split(':');
  2155. if (url_parts[0].indexOf('stun') === 0) {
  2156. iceServer = { 'url' : url };
  2157. } else if (url_parts[0].indexOf('turn') === 0) {
  2158. iceServer = {
  2159. 'url' : url,
  2160. 'credential' : password,
  2161. 'username' : username
  2162. };
  2163. }
  2164. return iceServer;
  2165. };
  2166. createIceServers = function (urls, username, password) {
  2167. var iceServers = [];
  2168. if (webrtcDetectedVersion >= 34) {
  2169. iceServers = {
  2170. 'urls' : urls,
  2171. 'credential' : password,
  2172. 'username' : username
  2173. };
  2174. } else {
  2175. for (i = 0; i < urls.length; i++) {
  2176. var iceServer = createIceServer(urls[i], username, password);
  2177. if (iceServer !== null) {
  2178. iceServers.push(iceServer);
  2179. }
  2180. }
  2181. }
  2182. return iceServers;
  2183. };
  2184. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2185. if (webrtcDetectedVersion < 34) {
  2186. AdapterJS.maybeFixConfiguration(pcConfig);
  2187. }
  2188. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2189. };
  2190. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2191. navigator.getUserMedia = window.getUserMedia;
  2192. attachMediaStream = function (element, stream) {
  2193. if (typeof element.srcObject !== 'undefined') {
  2194. element.srcObject = stream;
  2195. } else if (typeof element.mozSrcObject !== 'undefined') {
  2196. element.mozSrcObject = stream;
  2197. } else if (typeof element.src !== 'undefined') {
  2198. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2199. } else {
  2200. console.log('Error attaching stream to element.');
  2201. }
  2202. return element;
  2203. };
  2204. reattachMediaStream = function (to, from) {
  2205. to.src = from.src;
  2206. return to;
  2207. };
  2208. AdapterJS.maybeThroughWebRTCReady();
  2209. } else { // TRY TO USE PLUGIN
  2210. // IE 9 is not offering an implementation of console.log until you open a console
  2211. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2212. /* jshint -W020 */
  2213. console = {} || console;
  2214. // Implemented based on console specs from MDN
  2215. // You may override these functions
  2216. console.log = function (arg) {};
  2217. console.info = function (arg) {};
  2218. console.error = function (arg) {};
  2219. console.dir = function (arg) {};
  2220. console.exception = function (arg) {};
  2221. console.trace = function (arg) {};
  2222. console.warn = function (arg) {};
  2223. console.count = function (arg) {};
  2224. console.debug = function (arg) {};
  2225. console.count = function (arg) {};
  2226. console.time = function (arg) {};
  2227. console.timeEnd = function (arg) {};
  2228. console.group = function (arg) {};
  2229. console.groupCollapsed = function (arg) {};
  2230. console.groupEnd = function (arg) {};
  2231. /* jshint +W020 */
  2232. }
  2233. webrtcDetectedType = 'plugin';
  2234. webrtcDetectedDCSupport = 'plugin';
  2235. AdapterJS.parseWebrtcDetectedBrowser();
  2236. isIE = webrtcDetectedBrowser === 'IE';
  2237. /* jshint -W035 */
  2238. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2239. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2240. /* empty because it needs to prevent the function from running. */
  2241. }
  2242. };
  2243. /* jshint +W035 */
  2244. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2245. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2246. // Call immediately if possible
  2247. // Once the plugin is set, the code will always take this path
  2248. callback();
  2249. } else {
  2250. // otherwise start a 100ms interval
  2251. var checkPluginReadyState = setInterval(function () {
  2252. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2253. clearInterval(checkPluginReadyState);
  2254. callback();
  2255. }
  2256. }, 100);
  2257. }
  2258. };
  2259. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2260. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2261. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2262. });
  2263. };
  2264. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2265. // only inject once the page is ready
  2266. if (document.readyState !== 'complete') {
  2267. return;
  2268. }
  2269. // Prevent multiple injections
  2270. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2271. return;
  2272. }
  2273. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2274. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2275. var frag = document.createDocumentFragment();
  2276. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2277. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2278. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2279. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2280. '<param name="pluginId" value="' +
  2281. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2282. '<param name="windowless" value="false" /> ' +
  2283. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2284. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2285. '" />' +
  2286. // uncomment to be able to use virtual cams
  2287. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2288. '</object>';
  2289. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2290. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2291. }
  2292. document.body.appendChild(frag);
  2293. // Need to re-fetch the plugin
  2294. AdapterJS.WebRTCPlugin.plugin =
  2295. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2296. } else {
  2297. // Load Plugin
  2298. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2299. AdapterJS.WebRTCPlugin.plugin.id =
  2300. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2301. // IE will only start the plugin if it's ACTUALLY visible
  2302. if (isIE) {
  2303. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2304. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2305. } else { // The size of the plugin on Safari should be 0x0px
  2306. // so that the autorisation prompt is at the top
  2307. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2308. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2309. }
  2310. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2311. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2312. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2313. '<param name="pluginId" value="' +
  2314. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2315. '<param name="windowless" value="false" /> ' +
  2316. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2317. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2318. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2319. }
  2320. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2321. };
  2322. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2323. function (comName, plugName, installedCb, notInstalledCb) {
  2324. if (!isIE) {
  2325. var pluginArray = navigator.plugins;
  2326. for (var i = 0; i < pluginArray.length; i++) {
  2327. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2328. installedCb();
  2329. return;
  2330. }
  2331. }
  2332. notInstalledCb();
  2333. } else {
  2334. try {
  2335. var axo = new ActiveXObject(comName + '.' + plugName);
  2336. } catch (e) {
  2337. notInstalledCb();
  2338. return;
  2339. }
  2340. installedCb();
  2341. }
  2342. };
  2343. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2344. if (AdapterJS.WebRTCPlugin.pluginState ===
  2345. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2346. console.error("WebRTC interface has been defined already");
  2347. return;
  2348. }
  2349. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2350. AdapterJS.isDefined = function (variable) {
  2351. return variable !== null && variable !== undefined;
  2352. };
  2353. createIceServer = function (url, username, password) {
  2354. var iceServer = null;
  2355. var url_parts = url.split(':');
  2356. if (url_parts[0].indexOf('stun') === 0) {
  2357. iceServer = {
  2358. 'url' : url,
  2359. 'hasCredentials' : false
  2360. };
  2361. } else if (url_parts[0].indexOf('turn') === 0) {
  2362. iceServer = {
  2363. 'url' : url,
  2364. 'hasCredentials' : true,
  2365. 'credential' : password,
  2366. 'username' : username
  2367. };
  2368. }
  2369. return iceServer;
  2370. };
  2371. createIceServers = function (urls, username, password) {
  2372. var iceServers = [];
  2373. for (var i = 0; i < urls.length; ++i) {
  2374. iceServers.push(createIceServer(urls[i], username, password));
  2375. }
  2376. return iceServers;
  2377. };
  2378. RTCSessionDescription = function (info) {
  2379. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2380. return AdapterJS.WebRTCPlugin.plugin.
  2381. ConstructSessionDescription(info.type, info.sdp);
  2382. };
  2383. RTCPeerConnection = function (servers, constraints) {
  2384. var iceServers = null;
  2385. if (servers) {
  2386. iceServers = servers.iceServers;
  2387. for (var i = 0; i < iceServers.length; i++) {
  2388. if (iceServers[i].urls && !iceServers[i].url) {
  2389. iceServers[i].url = iceServers[i].urls;
  2390. }
  2391. iceServers[i].hasCredentials = AdapterJS.
  2392. isDefined(iceServers[i].username) &&
  2393. AdapterJS.isDefined(iceServers[i].credential);
  2394. }
  2395. }
  2396. var mandatory = (constraints && constraints.mandatory) ?
  2397. constraints.mandatory : null;
  2398. var optional = (constraints && constraints.optional) ?
  2399. constraints.optional : null;
  2400. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2401. return AdapterJS.WebRTCPlugin.plugin.
  2402. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2403. iceServers, mandatory, optional);
  2404. };
  2405. MediaStreamTrack = {};
  2406. MediaStreamTrack.getSources = function (callback) {
  2407. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2408. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2409. });
  2410. };
  2411. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2412. constraints.audio = constraints.audio || false;
  2413. constraints.video = constraints.video || false;
  2414. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2415. AdapterJS.WebRTCPlugin.plugin.
  2416. getUserMedia(constraints, successCallback, failureCallback);
  2417. });
  2418. };
  2419. window.navigator.getUserMedia = window.getUserMedia;
  2420. attachMediaStream = function (element, stream) {
  2421. if (!element || !element.parentNode) {
  2422. return;
  2423. }
  2424. var streamId
  2425. if (stream === null) {
  2426. streamId = '';
  2427. }
  2428. else {
  2429. stream.enableSoundTracks(true);
  2430. streamId = stream.id;
  2431. }
  2432. if (element.nodeName.toLowerCase() !== 'audio') {
  2433. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2434. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2435. var frag = document.createDocumentFragment();
  2436. var temp = document.createElement('div');
  2437. var classHTML = '';
  2438. if (element.className) {
  2439. classHTML = 'class="' + element.className + '" ';
  2440. } else if (element.attributes && element.attributes['class']) {
  2441. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2442. }
  2443. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2444. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2445. '<param name="pluginId" value="' + elementId + '" /> ' +
  2446. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2447. '<param name="windowless" value="true" /> ' +
  2448. '<param name="streamId" value="' + streamId + '" /> ' +
  2449. '</object>';
  2450. while (temp.firstChild) {
  2451. frag.appendChild(temp.firstChild);
  2452. }
  2453. var height = '';
  2454. var width = '';
  2455. if (element.getBoundingClientRect) {
  2456. var rectObject = element.getBoundingClientRect();
  2457. width = rectObject.width + 'px';
  2458. height = rectObject.height + 'px';
  2459. }
  2460. else if (element.width) {
  2461. width = element.width;
  2462. height = element.height;
  2463. } else {
  2464. // TODO: What scenario could bring us here?
  2465. }
  2466. element.parentNode.insertBefore(frag, element);
  2467. frag = document.getElementById(elementId);
  2468. frag.width = width;
  2469. frag.height = height;
  2470. element.parentNode.removeChild(element);
  2471. } else {
  2472. var children = element.children;
  2473. for (var i = 0; i !== children.length; ++i) {
  2474. if (children[i].name === 'streamId') {
  2475. children[i].value = streamId;
  2476. break;
  2477. }
  2478. }
  2479. element.setStreamId(streamId);
  2480. }
  2481. var newElement = document.getElementById(elementId);
  2482. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2483. if (isIE) { // on IE the event needs to be plugged manually
  2484. newElement.attachEvent('onplaying', newElement.onplaying);
  2485. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2486. newElement._TemOnClick = function (id) {
  2487. var arg = {
  2488. srcElement : document.getElementById(id)
  2489. };
  2490. newElement.onclick(arg);
  2491. };
  2492. }
  2493. return newElement;
  2494. } else {
  2495. return element;
  2496. }
  2497. };
  2498. reattachMediaStream = function (to, from) {
  2499. var stream = null;
  2500. var children = from.children;
  2501. for (var i = 0; i !== children.length; ++i) {
  2502. if (children[i].name === 'streamId') {
  2503. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2504. stream = AdapterJS.WebRTCPlugin.plugin
  2505. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2506. break;
  2507. }
  2508. }
  2509. if (stream !== null) {
  2510. return attachMediaStream(to, stream);
  2511. } else {
  2512. console.log('Could not find the stream associated with this element');
  2513. }
  2514. };
  2515. RTCIceCandidate = function (candidate) {
  2516. if (!candidate.sdpMid) {
  2517. candidate.sdpMid = '';
  2518. }
  2519. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2520. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2521. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2522. );
  2523. };
  2524. // inject plugin
  2525. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2526. AdapterJS.WebRTCPlugin.injectPlugin();
  2527. };
  2528. // This function will be called if the plugin is needed (browser different
  2529. // from Chrome or Firefox), but the plugin is not installed.
  2530. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2531. function() {
  2532. AdapterJS.addEvent(document,
  2533. 'readystatechange',
  2534. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2535. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2536. };
  2537. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2538. if (AdapterJS.options.hidePluginInstallPrompt) {
  2539. return;
  2540. }
  2541. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2542. if(downloadLink) { // if download link
  2543. var popupString;
  2544. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2545. popupString = 'This website requires you to install the ' +
  2546. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2547. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2548. ' WebRTC Plugin</a>' +
  2549. ' to work on this browser.';
  2550. } else { // no portal link, just print a generic explanation
  2551. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2552. }
  2553. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2554. } else { // no download link, just print a generic explanation
  2555. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2556. }
  2557. };
  2558. // Try to detect the plugin and act accordingly
  2559. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2560. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2561. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2562. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2563. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2564. }
  2565. (function () {
  2566. 'use strict';
  2567. var baseGetUserMedia = null;
  2568. AdapterJS.TEXT.EXTENSION = {
  2569. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2570. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2571. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2572. BUTTON_FF: 'Install Now',
  2573. BUTTON_CHROME: 'Go to Chrome Web Store'
  2574. };
  2575. var clone = function(obj) {
  2576. if (null == obj || "object" != typeof obj) return obj;
  2577. var copy = obj.constructor();
  2578. for (var attr in obj) {
  2579. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2580. }
  2581. return copy;
  2582. };
  2583. if (window.navigator.mozGetUserMedia) {
  2584. baseGetUserMedia = window.navigator.getUserMedia;
  2585. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2586. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2587. // intercepting screensharing requests
  2588. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2589. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2590. }
  2591. var updatedConstraints = clone(constraints);
  2592. //constraints.video.mediaSource = constraints.video.mediaSource;
  2593. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2594. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2595. // strange but this works anyway
  2596. var checkIfReady = setInterval(function () {
  2597. if (document.readyState === 'complete') {
  2598. clearInterval(checkIfReady);
  2599. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2600. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2601. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2602. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2603. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2604. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2605. } else {
  2606. failureCb(error);
  2607. }
  2608. });
  2609. }
  2610. }, 1);
  2611. } else { // regular GetUserMediaRequest
  2612. baseGetUserMedia(constraints, successCb, failureCb);
  2613. }
  2614. };
  2615. getUserMedia = navigator.getUserMedia;
  2616. } else if (window.navigator.webkitGetUserMedia) {
  2617. baseGetUserMedia = window.navigator.getUserMedia;
  2618. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2619. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2620. if (window.webrtcDetectedBrowser !== 'chrome') {
  2621. throw new Error('Current browser does not support screensharing');
  2622. }
  2623. // would be fine since no methods
  2624. var updatedConstraints = clone(constraints);
  2625. var chromeCallback = function(error, sourceId) {
  2626. if(!error) {
  2627. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2628. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2629. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2630. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2631. if (sourceId) {
  2632. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2633. }
  2634. delete updatedConstraints.video.mediaSource;
  2635. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2636. } else {
  2637. if (error === 'permission-denied') {
  2638. throw new Error('Permission denied for screen retrieval');
  2639. } else {
  2640. throw new Error('Failed retrieving selected screen');
  2641. }
  2642. }
  2643. };
  2644. var onIFrameCallback = function (event) {
  2645. if (!event.data) {
  2646. return;
  2647. }
  2648. if (event.data.chromeMediaSourceId) {
  2649. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2650. chromeCallback('permission-denied');
  2651. } else {
  2652. chromeCallback(null, event.data.chromeMediaSourceId);
  2653. }
  2654. }
  2655. if (event.data.chromeExtensionStatus) {
  2656. if (event.data.chromeExtensionStatus === 'not-installed') {
  2657. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2658. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2659. event.data.data, true, true);
  2660. } else {
  2661. chromeCallback(event.data.chromeExtensionStatus, null);
  2662. }
  2663. }
  2664. // this event listener is no more needed
  2665. window.removeEventListener('message', onIFrameCallback);
  2666. };
  2667. window.addEventListener('message', onIFrameCallback);
  2668. postFrameMessage({
  2669. captureSourceId: true
  2670. });
  2671. } else {
  2672. baseGetUserMedia(constraints, successCb, failureCb);
  2673. }
  2674. };
  2675. getUserMedia = navigator.getUserMedia;
  2676. } else {
  2677. baseGetUserMedia = window.navigator.getUserMedia;
  2678. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2679. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2680. // would be fine since no methods
  2681. var updatedConstraints = clone(constraints);
  2682. // wait for plugin to be ready
  2683. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2684. // check if screensharing feature is available
  2685. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2686. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2687. // set the constraints
  2688. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2689. updatedConstraints.video.optional.push({
  2690. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2691. });
  2692. delete updatedConstraints.video.mediaSource;
  2693. } else {
  2694. throw new Error('Your WebRTC plugin does not support screensharing');
  2695. }
  2696. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2697. });
  2698. } else {
  2699. baseGetUserMedia(constraints, successCb, failureCb);
  2700. }
  2701. };
  2702. getUserMedia = window.navigator.getUserMedia;
  2703. }
  2704. if (window.webrtcDetectedBrowser === 'chrome') {
  2705. var iframe = document.createElement('iframe');
  2706. iframe.onload = function() {
  2707. iframe.isLoaded = true;
  2708. };
  2709. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2710. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2711. iframe.style.display = 'none';
  2712. (document.body || document.documentElement).appendChild(iframe);
  2713. var postFrameMessage = function (object) {
  2714. object = object || {};
  2715. if (!iframe.isLoaded) {
  2716. setTimeout(function () {
  2717. iframe.contentWindow.postMessage(object, '*');
  2718. }, 100);
  2719. return;
  2720. }
  2721. iframe.contentWindow.postMessage(object, '*');
  2722. };
  2723. }
  2724. })();
  2725. },{}],15:[function(require,module,exports){
  2726. function supportsLocalStorage() {
  2727. try {
  2728. return 'localStorage' in window && window.localStorage !== null;
  2729. } catch (e) {
  2730. console.log("localstorage is not supported");
  2731. return false;
  2732. }
  2733. }
  2734. function generateUniqueId() {
  2735. function _p8() {
  2736. return (Math.random().toString(16) + "000000000").substr(2, 8);
  2737. }
  2738. return _p8() + _p8() + _p8() + _p8();
  2739. }
  2740. function Settings(conferenceID) {
  2741. this.email = '';
  2742. this.displayName = '';
  2743. this.userId;
  2744. this.language = null;
  2745. this.confSettings = null;
  2746. this.conferenceID = conferenceID;
  2747. if (supportsLocalStorage()) {
  2748. if(!window.localStorage.getItem(conferenceID))
  2749. this.confSettings = {};
  2750. else
  2751. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  2752. if(!this.confSettings.jitsiMeetId) {
  2753. this.confSettings.jitsiMeetId = generateUniqueId();
  2754. console.log("generated id",
  2755. this.confSettings.jitsiMeetId);
  2756. this.save();
  2757. }
  2758. this.userId = this.confSettings.jitsiMeetId || '';
  2759. this.email = this.confSettings.email || '';
  2760. this.displayName = this.confSettings.displayname || '';
  2761. this.language = this.confSettings.language;
  2762. } else {
  2763. console.log("local storage is not supported");
  2764. this.userId = generateUniqueId();
  2765. }
  2766. }
  2767. Settings.prototype.save = function () {
  2768. if(!supportsLocalStorage())
  2769. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  2770. }
  2771. Settings.prototype.setDisplayName = function (newDisplayName) {
  2772. this.displayName = newDisplayName;
  2773. if(this.confSettings != null)
  2774. this.confSettings.displayname = displayName;
  2775. this.save();
  2776. return this.displayName;
  2777. },
  2778. Settings.prototype.setEmail = function (newEmail) {
  2779. this.email = newEmail;
  2780. if(this.confSettings != null)
  2781. this.confSettings.email = newEmail;
  2782. this.save();
  2783. return this.email;
  2784. },
  2785. Settings.prototype.getSettings = function () {
  2786. return {
  2787. email: this.email,
  2788. displayName: this.displayName,
  2789. uid: this.userId,
  2790. language: this.language
  2791. };
  2792. },
  2793. Settings.prototype.setLanguage = function (lang) {
  2794. this.language = lang;
  2795. if(this.confSettings != null)
  2796. this.confSettings.language = lang;
  2797. this.save();
  2798. }
  2799. module.exports = Settings;
  2800. },{}],16:[function(require,module,exports){
  2801. /*
  2802. * JingleSession provides an API to manage a single Jingle session. We will
  2803. * have different implementations depending on the underlying interface used
  2804. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  2805. */
  2806. function JingleSession(me, sid, connection, service, eventEmitter) {
  2807. /**
  2808. * Our JID.
  2809. */
  2810. this.me = me;
  2811. /**
  2812. * The Jingle session identifier.
  2813. */
  2814. this.sid = sid;
  2815. /**
  2816. * The XMPP connection.
  2817. */
  2818. this.connection = connection;
  2819. /**
  2820. * The XMPP service.
  2821. */
  2822. this.service = service;
  2823. /**
  2824. * The event emitter.
  2825. */
  2826. this.eventEmitter = eventEmitter;
  2827. /**
  2828. * Whether to use dripping or not. Dripping is sending trickle candidates
  2829. * not one-by-one.
  2830. * Note: currently we do not support 'false'.
  2831. */
  2832. this.usedrip = true;
  2833. /**
  2834. * When dripping is used, stores ICE candidates which are to be sent.
  2835. */
  2836. this.drip_container = [];
  2837. // Media constraints. Is this WebRTC only?
  2838. this.media_constraints = null;
  2839. // ICE servers config (RTCConfiguration?).
  2840. this.ice_config = {};
  2841. }
  2842. /**
  2843. * Prepares this object to initiate a session.
  2844. * @param peerjid the JID of the remote peer.
  2845. * @param isInitiator whether we will be the Jingle initiator.
  2846. * @param media_constraints
  2847. * @param ice_config
  2848. */
  2849. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  2850. media_constraints, ice_config) {
  2851. this.media_constraints = media_constraints;
  2852. this.ice_config = ice_config;
  2853. if (this.state !== null) {
  2854. console.error('attempt to initiate on session ' + this.sid +
  2855. 'in state ' + this.state);
  2856. return;
  2857. }
  2858. this.state = 'pending';
  2859. this.initiator = isInitiator ? this.me : peerjid;
  2860. this.responder = !isInitiator ? this.me : peerjid;
  2861. this.peerjid = peerjid;
  2862. this.doInitialize();
  2863. };
  2864. /**
  2865. * Finishes initialization.
  2866. */
  2867. JingleSession.prototype.doInitialize = function() {};
  2868. /**
  2869. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  2870. * Note: currently only used on transport-info
  2871. */
  2872. JingleSession.prototype.addIceCandidates = function(contents) {};
  2873. /**
  2874. * Handles an 'add-source' event.
  2875. *
  2876. * @param contents an array of Jingle 'content' elements.
  2877. */
  2878. JingleSession.prototype.addSources = function(contents) {};
  2879. /**
  2880. * Handles a 'remove-source' event.
  2881. *
  2882. * @param contents an array of Jingle 'content' elements.
  2883. */
  2884. JingleSession.prototype.removeSources = function(contents) {};
  2885. /**
  2886. * Terminates this Jingle session (stops sending media and closes the streams?)
  2887. */
  2888. JingleSession.prototype.terminate = function() {};
  2889. /**
  2890. * Sends a Jingle session-terminate message to the peer and terminates the
  2891. * session.
  2892. * @param reason
  2893. * @param text
  2894. */
  2895. JingleSession.prototype.sendTerminate = function(reason, text) {};
  2896. /**
  2897. * Handles an offer from the remote peer (prepares to accept a session).
  2898. * @param jingle the 'jingle' XML element.
  2899. */
  2900. JingleSession.prototype.setOffer = function(jingle) {};
  2901. /**
  2902. * Handles an answer from the remote peer (prepares to accept a session).
  2903. * @param jingle the 'jingle' XML element.
  2904. */
  2905. JingleSession.prototype.setAnswer = function(jingle) {};
  2906. module.exports = JingleSession;
  2907. },{}],17:[function(require,module,exports){
  2908. /* jshint -W117 */
  2909. var JingleSession = require("./JingleSession");
  2910. var TraceablePeerConnection = require("./TraceablePeerConnection");
  2911. var SDPDiffer = require("./SDPDiffer");
  2912. var SDPUtil = require("./SDPUtil");
  2913. var SDP = require("./SDP");
  2914. var async = require("async");
  2915. var transform = require("sdp-transform");
  2916. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2917. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2918. var SSRCReplacement = require("./LocalSSRCReplacement");
  2919. var RTC = require("../RTC/RTC");
  2920. // Jingle stuff
  2921. function JingleSessionPC(me, sid, connection, service, eventEmitter) {
  2922. JingleSession.call(this, me, sid, connection, service, eventEmitter);
  2923. this.initiator = null;
  2924. this.responder = null;
  2925. this.peerjid = null;
  2926. this.state = null;
  2927. this.localSDP = null;
  2928. this.remoteSDP = null;
  2929. this.relayedStreams = [];
  2930. this.usetrickle = true;
  2931. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  2932. this.hadstuncandidate = false;
  2933. this.hadturncandidate = false;
  2934. this.lasticecandidate = false;
  2935. this.statsinterval = null;
  2936. this.reason = null;
  2937. this.addssrc = [];
  2938. this.removessrc = [];
  2939. this.pendingop = null;
  2940. this.switchstreams = false;
  2941. this.wait = true;
  2942. this.localStreamsSSRC = null;
  2943. this.ssrcOwners = {};
  2944. this.ssrcVideoTypes = {};
  2945. this.eventEmitter = eventEmitter;
  2946. /**
  2947. * The indicator which determines whether the (local) video has been muted
  2948. * in response to a user command in contrast to an automatic decision made
  2949. * by the application logic.
  2950. */
  2951. this.videoMuteByUser = false;
  2952. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  2953. // We start with the queue paused. We resume it when the signaling state is
  2954. // stable and the ice connection state is connected.
  2955. this.modifySourcesQueue.pause();
  2956. }
  2957. JingleSessionPC.prototype = JingleSession.prototype;
  2958. JingleSessionPC.prototype.constructor = JingleSessionPC;
  2959. JingleSessionPC.prototype.setOffer = function(offer) {
  2960. this.setRemoteDescription(offer, 'offer');
  2961. };
  2962. JingleSessionPC.prototype.setAnswer = function(answer) {
  2963. this.setRemoteDescription(answer, 'answer');
  2964. };
  2965. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  2966. var signalingState = this.peerconnection.signalingState;
  2967. var iceConnectionState = this.peerconnection.iceConnectionState;
  2968. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  2969. this.modifySourcesQueue.resume();
  2970. } else {
  2971. this.modifySourcesQueue.pause();
  2972. }
  2973. };
  2974. JingleSessionPC.prototype.doInitialize = function () {
  2975. var self = this;
  2976. this.hadstuncandidate = false;
  2977. this.hadturncandidate = false;
  2978. this.lasticecandidate = false;
  2979. this.isreconnect = false;
  2980. this.peerconnection = new TraceablePeerConnection(
  2981. this.connection.jingle.ice_config,
  2982. RTC.getPCConstraints(),
  2983. this);
  2984. this.peerconnection.onicecandidate = function (event) {
  2985. self.sendIceCandidate(event.candidate);
  2986. };
  2987. this.peerconnection.onaddstream = function (event) {
  2988. if (event.stream.id !== 'default') {
  2989. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  2990. self.remoteStreamAdded(event);
  2991. } else {
  2992. // This is a recvonly stream. Clients that implement Unified Plan,
  2993. // such as Firefox use recvonly "streams/channels/tracks" for
  2994. // receiving remote stream/tracks, as opposed to Plan B where there
  2995. // are only 3 channels: audio, video and data.
  2996. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  2997. }
  2998. };
  2999. this.peerconnection.onremovestream = function (event) {
  3000. // Remove the stream from remoteStreams
  3001. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  3002. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  3003. };
  3004. this.peerconnection.onsignalingstatechange = function (event) {
  3005. if (!(self && self.peerconnection)) return;
  3006. self.updateModifySourcesQueue();
  3007. };
  3008. /**
  3009. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  3010. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  3011. * RTCPeerConnection.iceConnectionState changes.
  3012. *
  3013. * @param event the event containing information about the change
  3014. */
  3015. this.peerconnection.oniceconnectionstatechange = function (event) {
  3016. if (!(self && self.peerconnection)) return;
  3017. self.updateModifySourcesQueue();
  3018. switch (self.peerconnection.iceConnectionState) {
  3019. case 'connected':
  3020. // Informs interested parties that the connection has been restored.
  3021. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  3022. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  3023. self.isreconnect = false;
  3024. break;
  3025. case 'disconnected':
  3026. self.isreconnect = true;
  3027. // Informs interested parties that the connection has been interrupted.
  3028. if (self.peerconnection.signalingState === 'stable')
  3029. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  3030. break;
  3031. case 'failed':
  3032. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  3033. break;
  3034. }
  3035. onIceConnectionStateChange(self.sid, self);
  3036. };
  3037. this.peerconnection.onnegotiationneeded = function (event) {
  3038. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  3039. };
  3040. this.relayedStreams.forEach(function(stream) {
  3041. self.peerconnection.addStream(stream);
  3042. });
  3043. };
  3044. JingleSessionPC.prototype.addLocalStreams = function (localStreams) {
  3045. var self = this;
  3046. // add any local and relayed stream
  3047. localStreams.forEach(function(stream) {
  3048. self.peerconnection.addStream(stream.getOriginalStream());
  3049. });
  3050. }
  3051. function onIceConnectionStateChange(sid, session) {
  3052. switch (session.peerconnection.iceConnectionState) {
  3053. case 'checking':
  3054. session.timeChecking = (new Date()).getTime();
  3055. session.firstconnect = true;
  3056. break;
  3057. case 'completed': // on caller side
  3058. case 'connected':
  3059. if (session.firstconnect) {
  3060. session.firstconnect = false;
  3061. var metadata = {};
  3062. metadata.setupTime
  3063. = (new Date()).getTime() - session.timeChecking;
  3064. session.peerconnection.getStats(function (res) {
  3065. if(res && res.result) {
  3066. res.result().forEach(function (report) {
  3067. if (report.type == 'googCandidatePair' &&
  3068. report.stat('googActiveConnection') == 'true') {
  3069. metadata.localCandidateType
  3070. = report.stat('googLocalCandidateType');
  3071. metadata.remoteCandidateType
  3072. = report.stat('googRemoteCandidateType');
  3073. // log pair as well so we can get nice pie
  3074. // charts
  3075. metadata.candidatePair
  3076. = report.stat('googLocalCandidateType') +
  3077. ';' +
  3078. report.stat('googRemoteCandidateType');
  3079. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  3080. {
  3081. metadata.ipv6 = true;
  3082. }
  3083. }
  3084. });
  3085. }
  3086. });
  3087. }
  3088. break;
  3089. }
  3090. }
  3091. JingleSessionPC.prototype.accept = function () {
  3092. this.state = 'active';
  3093. var pranswer = this.peerconnection.localDescription;
  3094. if (!pranswer || pranswer.type != 'pranswer') {
  3095. return;
  3096. }
  3097. console.log('going from pranswer to answer');
  3098. if (this.usetrickle) {
  3099. // remove candidates already sent from session-accept
  3100. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  3101. for (var i = 0; i < lines.length; i++) {
  3102. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  3103. }
  3104. }
  3105. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  3106. // FIXME: change any inactive to sendrecv or whatever they were originally
  3107. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  3108. }
  3109. var prsdp = new SDP(pranswer.sdp);
  3110. var accept = $iq({to: this.peerjid,
  3111. type: 'set'})
  3112. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  3113. action: 'session-accept',
  3114. initiator: this.initiator,
  3115. responder: this.responder,
  3116. sid: this.sid });
  3117. // FIXME why do we generate session-accept in 3 different places ?
  3118. prsdp.toJingle(
  3119. accept,
  3120. this.initiator == this.me ? 'initiator' : 'responder',
  3121. this.localStreamsSSRC);
  3122. var sdp = this.peerconnection.localDescription.sdp;
  3123. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  3124. // FIXME: change any inactive to sendrecv or whatever they were originally
  3125. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  3126. }
  3127. var self = this;
  3128. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  3129. function () {
  3130. //console.log('setLocalDescription success');
  3131. self.setLocalDescription();
  3132. SSRCReplacement.processSessionInit(accept);
  3133. self.connection.sendIQ(accept,
  3134. function () {
  3135. var ack = {};
  3136. ack.source = 'answer';
  3137. $(document).trigger('ack.jingle', [self.sid, ack]);
  3138. },
  3139. function (stanza) {
  3140. var error = ($(stanza).find('error').length) ? {
  3141. code: $(stanza).find('error').attr('code'),
  3142. reason: $(stanza).find('error :first')[0].tagName
  3143. }:{};
  3144. error.source = 'answer';
  3145. JingleSessionPC.onJingleError(self.sid, error);
  3146. },
  3147. 10000);
  3148. },
  3149. function (e) {
  3150. console.error('setLocalDescription failed', e);
  3151. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  3152. }
  3153. );
  3154. };
  3155. JingleSessionPC.prototype.terminate = function (reason) {
  3156. this.state = 'ended';
  3157. this.reason = reason;
  3158. this.peerconnection.close();
  3159. if (this.statsinterval !== null) {
  3160. window.clearInterval(this.statsinterval);
  3161. this.statsinterval = null;
  3162. }
  3163. };
  3164. JingleSessionPC.prototype.active = function () {
  3165. return this.state == 'active';
  3166. };
  3167. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  3168. var self = this;
  3169. if (candidate && !this.lasticecandidate) {
  3170. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  3171. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  3172. if (!(ice && jcand)) {
  3173. console.error('failed to get ice && jcand');
  3174. return;
  3175. }
  3176. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  3177. if (jcand.type === 'srflx') {
  3178. this.hadstuncandidate = true;
  3179. } else if (jcand.type === 'relay') {
  3180. this.hadturncandidate = true;
  3181. }
  3182. if (this.usetrickle) {
  3183. if (this.usedrip) {
  3184. if (this.drip_container.length === 0) {
  3185. // start 20ms callout
  3186. window.setTimeout(function () {
  3187. if (self.drip_container.length === 0) return;
  3188. self.sendIceCandidates(self.drip_container);
  3189. self.drip_container = [];
  3190. }, 20);
  3191. }
  3192. this.drip_container.push(candidate);
  3193. return;
  3194. } else {
  3195. self.sendIceCandidate([candidate]);
  3196. }
  3197. }
  3198. } else {
  3199. //console.log('sendIceCandidate: last candidate.');
  3200. if (!this.usetrickle) {
  3201. //console.log('should send full offer now...');
  3202. //FIXME why do we generate session-accept in 3 different places ?
  3203. var init = $iq({to: this.peerjid,
  3204. type: 'set'})
  3205. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  3206. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  3207. initiator: this.initiator,
  3208. sid: this.sid});
  3209. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  3210. var sendJingle = function (ssrc) {
  3211. if(!ssrc)
  3212. ssrc = {};
  3213. self.localSDP.toJingle(
  3214. init,
  3215. self.initiator == self.me ? 'initiator' : 'responder',
  3216. ssrc);
  3217. SSRCReplacement.processSessionInit(init);
  3218. self.connection.sendIQ(init,
  3219. function () {
  3220. //console.log('session initiate ack');
  3221. var ack = {};
  3222. ack.source = 'offer';
  3223. $(document).trigger('ack.jingle', [self.sid, ack]);
  3224. },
  3225. function (stanza) {
  3226. self.state = 'error';
  3227. self.peerconnection.close();
  3228. var error = ($(stanza).find('error').length) ? {
  3229. code: $(stanza).find('error').attr('code'),
  3230. reason: $(stanza).find('error :first')[0].tagName,
  3231. }:{};
  3232. error.source = 'offer';
  3233. JingleSessionPC.onJingleError(self.sid, error);
  3234. },
  3235. 10000);
  3236. };
  3237. sendJingle();
  3238. }
  3239. this.lasticecandidate = true;
  3240. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  3241. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  3242. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  3243. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  3244. }
  3245. }
  3246. };
  3247. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  3248. console.log('sendIceCandidates', candidates);
  3249. var cand = $iq({to: this.peerjid, type: 'set'})
  3250. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  3251. action: 'transport-info',
  3252. initiator: this.initiator,
  3253. sid: this.sid});
  3254. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  3255. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  3256. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  3257. if (cands.length > 0) {
  3258. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  3259. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  3260. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  3261. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  3262. }).c('transport', ice);
  3263. for (var i = 0; i < cands.length; i++) {
  3264. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  3265. }
  3266. // add fingerprint
  3267. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  3268. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  3269. tmp.required = true;
  3270. cand.c(
  3271. 'fingerprint',
  3272. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  3273. .t(tmp.fingerprint);
  3274. delete tmp.fingerprint;
  3275. cand.attrs(tmp);
  3276. cand.up();
  3277. }
  3278. cand.up(); // transport
  3279. cand.up(); // content
  3280. }
  3281. }
  3282. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  3283. //console.log('was this the last candidate', this.lasticecandidate);
  3284. this.connection.sendIQ(cand,
  3285. function () {
  3286. var ack = {};
  3287. ack.source = 'transportinfo';
  3288. $(document).trigger('ack.jingle', [this.sid, ack]);
  3289. },
  3290. function (stanza) {
  3291. var error = ($(stanza).find('error').length) ? {
  3292. code: $(stanza).find('error').attr('code'),
  3293. reason: $(stanza).find('error :first')[0].tagName,
  3294. }:{};
  3295. error.source = 'transportinfo';
  3296. JingleSessionPC.onJingleError(this.sid, error);
  3297. },
  3298. 10000);
  3299. };
  3300. JingleSessionPC.prototype.sendOffer = function () {
  3301. //console.log('sendOffer...');
  3302. var self = this;
  3303. this.peerconnection.createOffer(function (sdp) {
  3304. self.createdOffer(sdp);
  3305. },
  3306. function (e) {
  3307. console.error('createOffer failed', e);
  3308. },
  3309. this.media_constraints
  3310. );
  3311. };
  3312. // FIXME createdOffer is never used in jitsi-meet
  3313. JingleSessionPC.prototype.createdOffer = function (sdp) {
  3314. //console.log('createdOffer', sdp);
  3315. var self = this;
  3316. this.localSDP = new SDP(sdp.sdp);
  3317. //this.localSDP.mangle();
  3318. var sendJingle = function () {
  3319. var init = $iq({to: this.peerjid,
  3320. type: 'set'})
  3321. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  3322. action: 'session-initiate',
  3323. initiator: this.initiator,
  3324. sid: this.sid});
  3325. self.localSDP.toJingle(
  3326. init,
  3327. this.initiator == this.me ? 'initiator' : 'responder',
  3328. this.localStreamsSSRC);
  3329. SSRCReplacement.processSessionInit(init);
  3330. self.connection.sendIQ(init,
  3331. function () {
  3332. var ack = {};
  3333. ack.source = 'offer';
  3334. $(document).trigger('ack.jingle', [self.sid, ack]);
  3335. },
  3336. function (stanza) {
  3337. self.state = 'error';
  3338. self.peerconnection.close();
  3339. var error = ($(stanza).find('error').length) ? {
  3340. code: $(stanza).find('error').attr('code'),
  3341. reason: $(stanza).find('error :first')[0].tagName,
  3342. }:{};
  3343. error.source = 'offer';
  3344. JingleSessionPC.onJingleError(self.sid, error);
  3345. },
  3346. 10000);
  3347. }
  3348. sdp.sdp = this.localSDP.raw;
  3349. this.peerconnection.setLocalDescription(sdp,
  3350. function () {
  3351. if(self.usetrickle)
  3352. {
  3353. sendJingle();
  3354. }
  3355. self.setLocalDescription();
  3356. //console.log('setLocalDescription success');
  3357. },
  3358. function (e) {
  3359. console.error('setLocalDescription failed', e);
  3360. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  3361. }
  3362. );
  3363. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  3364. for (var i = 0; i < cands.length; i++) {
  3365. var cand = SDPUtil.parse_icecandidate(cands[i]);
  3366. if (cand.type == 'srflx') {
  3367. this.hadstuncandidate = true;
  3368. } else if (cand.type == 'relay') {
  3369. this.hadturncandidate = true;
  3370. }
  3371. }
  3372. };
  3373. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  3374. var self = this;
  3375. $(contents).each(function (idx, content) {
  3376. var name = $(content).attr('name');
  3377. var mediaType = this.getAttribute('name');
  3378. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  3379. ssrcs.each(function () {
  3380. var ssrc = this.getAttribute('ssrc');
  3381. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  3382. function () {
  3383. var owner = this.getAttribute('owner');
  3384. self.ssrcOwners[ssrc] = owner;
  3385. }
  3386. );
  3387. });
  3388. });
  3389. };
  3390. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  3391. return this.ssrcOwners[ssrc];
  3392. };
  3393. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  3394. //console.log('setting remote description... ', desctype);
  3395. this.remoteSDP = new SDP('');
  3396. this.remoteSDP.fromJingle(elem);
  3397. this.readSsrcInfo($(elem).find(">content"));
  3398. if (this.peerconnection.remoteDescription !== null) {
  3399. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  3400. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  3401. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  3402. for (var i = 0; i < pranswer.media.length; i++) {
  3403. // make sure we have ice ufrag and pwd
  3404. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  3405. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  3406. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  3407. } else {
  3408. console.warn('no ice ufrag?');
  3409. }
  3410. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  3411. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  3412. } else {
  3413. console.warn('no ice pwd?');
  3414. }
  3415. }
  3416. // copy over candidates
  3417. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  3418. for (var j = 0; j < lines.length; j++) {
  3419. this.remoteSDP.media[i] += lines[j] + '\r\n';
  3420. }
  3421. }
  3422. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  3423. }
  3424. }
  3425. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  3426. this.peerconnection.setRemoteDescription(remotedesc,
  3427. function () {
  3428. //console.log('setRemoteDescription success');
  3429. },
  3430. function (e) {
  3431. console.error('setRemoteDescription error', e);
  3432. JingleSessionPC.onJingleFatalError(self, e);
  3433. }
  3434. );
  3435. };
  3436. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  3437. var self = this;
  3438. if (this.peerconnection.signalingState == 'closed') {
  3439. return;
  3440. }
  3441. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  3442. console.log('trickle ice candidate arriving before session accept...');
  3443. // create a PRANSWER for setRemoteDescription
  3444. if (!this.remoteSDP) {
  3445. var cobbled = 'v=0\r\n' +
  3446. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  3447. 's=-\r\n' +
  3448. 't=0 0\r\n';
  3449. // first, take some things from the local description
  3450. for (var i = 0; i < this.localSDP.media.length; i++) {
  3451. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  3452. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  3453. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  3454. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  3455. }
  3456. cobbled += 'a=inactive\r\n';
  3457. }
  3458. this.remoteSDP = new SDP(cobbled);
  3459. }
  3460. // then add things like ice and dtls from remote candidate
  3461. elem.each(function () {
  3462. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  3463. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  3464. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  3465. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  3466. var tmp = $(this).find('transport');
  3467. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  3468. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  3469. tmp = $(this).find('transport>fingerprint');
  3470. if (tmp.length) {
  3471. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  3472. } else {
  3473. console.log('no dtls fingerprint (webrtc issue #1718?)');
  3474. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  3475. }
  3476. break;
  3477. }
  3478. }
  3479. }
  3480. });
  3481. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  3482. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  3483. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  3484. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  3485. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  3486. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  3487. }).length == this.remoteSDP.media.length;
  3488. if (iscomplete) {
  3489. console.log('setting pranswer');
  3490. try {
  3491. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  3492. function() {
  3493. },
  3494. function(e) {
  3495. console.log('setRemoteDescription pranswer failed', e.toString());
  3496. });
  3497. } catch (e) {
  3498. console.error('setting pranswer failed', e);
  3499. }
  3500. } else {
  3501. //console.log('not yet setting pranswer');
  3502. }
  3503. }
  3504. // operate on each content element
  3505. elem.each(function () {
  3506. // would love to deactivate this, but firefox still requires it
  3507. var idx = -1;
  3508. var i;
  3509. for (i = 0; i < self.remoteSDP.media.length; i++) {
  3510. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  3511. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  3512. idx = i;
  3513. break;
  3514. }
  3515. }
  3516. if (idx == -1) { // fall back to localdescription
  3517. for (i = 0; i < self.localSDP.media.length; i++) {
  3518. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  3519. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  3520. idx = i;
  3521. break;
  3522. }
  3523. }
  3524. }
  3525. var name = $(this).attr('name');
  3526. // TODO: check ice-pwd and ice-ufrag?
  3527. $(this).find('transport>candidate').each(function () {
  3528. var line, candidate;
  3529. line = SDPUtil.candidateFromJingle(this);
  3530. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  3531. sdpMid: name,
  3532. candidate: line});
  3533. try {
  3534. self.peerconnection.addIceCandidate(candidate);
  3535. } catch (e) {
  3536. console.error('addIceCandidate failed', e.toString(), line);
  3537. }
  3538. });
  3539. });
  3540. };
  3541. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  3542. //console.log('createAnswer', provisional);
  3543. var self = this;
  3544. this.peerconnection.createAnswer(
  3545. function (sdp) {
  3546. self.createdAnswer(sdp, provisional);
  3547. },
  3548. function (e) {
  3549. console.error('createAnswer failed', e);
  3550. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  3551. },
  3552. this.media_constraints
  3553. );
  3554. };
  3555. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  3556. //console.log('createAnswer callback');
  3557. var self = this;
  3558. this.localSDP = new SDP(sdp.sdp);
  3559. //this.localSDP.mangle();
  3560. this.usepranswer = provisional === true;
  3561. if (this.usetrickle) {
  3562. if (this.usepranswer) {
  3563. sdp.type = 'pranswer';
  3564. for (var i = 0; i < this.localSDP.media.length; i++) {
  3565. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  3566. }
  3567. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  3568. }
  3569. }
  3570. var self = this;
  3571. var sendJingle = function (ssrcs) {
  3572. // FIXME why do we generate session-accept in 3 different places ?
  3573. var accept = $iq({to: self.peerjid,
  3574. type: 'set'})
  3575. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  3576. action: 'session-accept',
  3577. initiator: self.initiator,
  3578. responder: self.responder,
  3579. sid: self.sid });
  3580. self.localSDP.toJingle(
  3581. accept,
  3582. self.initiator == self.me ? 'initiator' : 'responder',
  3583. ssrcs);
  3584. SSRCReplacement.processSessionInit(accept);
  3585. self.connection.sendIQ(accept,
  3586. function () {
  3587. var ack = {};
  3588. ack.source = 'answer';
  3589. $(document).trigger('ack.jingle', [self.sid, ack]);
  3590. },
  3591. function (stanza) {
  3592. var error = ($(stanza).find('error').length) ? {
  3593. code: $(stanza).find('error').attr('code'),
  3594. reason: $(stanza).find('error :first')[0].tagName,
  3595. }:{};
  3596. error.source = 'answer';
  3597. JingleSessionPC.onJingleError(self.sid, error);
  3598. },
  3599. 10000);
  3600. }
  3601. sdp.sdp = this.localSDP.raw;
  3602. this.peerconnection.setLocalDescription(sdp,
  3603. function () {
  3604. //console.log('setLocalDescription success');
  3605. if (self.usetrickle && !self.usepranswer) {
  3606. sendJingle();
  3607. }
  3608. self.setLocalDescription();
  3609. },
  3610. function (e) {
  3611. console.error('setLocalDescription failed', e);
  3612. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  3613. }
  3614. );
  3615. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  3616. for (var j = 0; j < cands.length; j++) {
  3617. var cand = SDPUtil.parse_icecandidate(cands[j]);
  3618. if (cand.type == 'srflx') {
  3619. this.hadstuncandidate = true;
  3620. } else if (cand.type == 'relay') {
  3621. this.hadturncandidate = true;
  3622. }
  3623. }
  3624. };
  3625. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  3626. var self = this,
  3627. term = $iq({to: this.peerjid,
  3628. type: 'set'})
  3629. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  3630. action: 'session-terminate',
  3631. initiator: this.initiator,
  3632. sid: this.sid})
  3633. .c('reason')
  3634. .c(reason || 'success');
  3635. if (text) {
  3636. term.up().c('text').t(text);
  3637. }
  3638. this.connection.sendIQ(term,
  3639. function () {
  3640. self.peerconnection.close();
  3641. self.peerconnection = null;
  3642. self.terminate();
  3643. var ack = {};
  3644. ack.source = 'terminate';
  3645. $(document).trigger('ack.jingle', [self.sid, ack]);
  3646. },
  3647. function (stanza) {
  3648. var error = ($(stanza).find('error').length) ? {
  3649. code: $(stanza).find('error').attr('code'),
  3650. reason: $(stanza).find('error :first')[0].tagName,
  3651. }:{};
  3652. $(document).trigger('ack.jingle', [self.sid, error]);
  3653. },
  3654. 10000);
  3655. if (this.statsinterval !== null) {
  3656. window.clearInterval(this.statsinterval);
  3657. this.statsinterval = null;
  3658. }
  3659. };
  3660. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  3661. var self = this;
  3662. // FIXME: dirty waiting
  3663. if (!this.peerconnection.localDescription)
  3664. {
  3665. console.warn("addSource - localDescription not ready yet")
  3666. setTimeout(function()
  3667. {
  3668. self.addSource(elem, fromJid);
  3669. },
  3670. 200
  3671. );
  3672. return;
  3673. }
  3674. console.log('addssrc', new Date().getTime());
  3675. console.log('ice', this.peerconnection.iceConnectionState);
  3676. this.readSsrcInfo(elem);
  3677. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  3678. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  3679. $(elem).each(function (idx, content) {
  3680. var name = $(content).attr('name');
  3681. var lines = '';
  3682. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  3683. var semantics = this.getAttribute('semantics');
  3684. var ssrcs = $(this).find('>source').map(function () {
  3685. return this.getAttribute('ssrc');
  3686. }).get();
  3687. if (ssrcs.length != 0) {
  3688. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  3689. }
  3690. });
  3691. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  3692. tmp.each(function () {
  3693. var ssrc = $(this).attr('ssrc');
  3694. if(mySdp.containsSSRC(ssrc)){
  3695. /**
  3696. * This happens when multiple participants change their streams at the same time and
  3697. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  3698. * addssrc are scheduled for update IQ. See
  3699. */
  3700. console.warn("Got add stream request for my own ssrc: "+ssrc);
  3701. return;
  3702. }
  3703. if (sdp.containsSSRC(ssrc)) {
  3704. console.warn("Source-add request for existing SSRC: " + ssrc);
  3705. return;
  3706. }
  3707. $(this).find('>parameter').each(function () {
  3708. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  3709. if ($(this).attr('value') && $(this).attr('value').length)
  3710. lines += ':' + $(this).attr('value');
  3711. lines += '\r\n';
  3712. });
  3713. });
  3714. sdp.media.forEach(function(media, idx) {
  3715. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  3716. return;
  3717. sdp.media[idx] += lines;
  3718. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  3719. self.addssrc[idx] += lines;
  3720. });
  3721. sdp.raw = sdp.session + sdp.media.join('');
  3722. });
  3723. this.modifySourcesQueue.push(function() {
  3724. // When a source is added and if this is FF, a new channel is allocated
  3725. // for receiving the added source. We need to diffuse the SSRC of this
  3726. // new recvonly channel to the rest of the peers.
  3727. console.log('modify sources done');
  3728. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  3729. console.log("SDPs", mySdp, newSdp);
  3730. self.notifyMySSRCUpdate(mySdp, newSdp);
  3731. });
  3732. };
  3733. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  3734. var self = this;
  3735. // FIXME: dirty waiting
  3736. if (!this.peerconnection.localDescription)
  3737. {
  3738. console.warn("removeSource - localDescription not ready yet")
  3739. setTimeout(function()
  3740. {
  3741. self.removeSource(elem, fromJid);
  3742. },
  3743. 200
  3744. );
  3745. return;
  3746. }
  3747. console.log('removessrc', new Date().getTime());
  3748. console.log('ice', this.peerconnection.iceConnectionState);
  3749. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  3750. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  3751. $(elem).each(function (idx, content) {
  3752. var name = $(content).attr('name');
  3753. var lines = '';
  3754. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  3755. var semantics = this.getAttribute('semantics');
  3756. var ssrcs = $(this).find('>source').map(function () {
  3757. return this.getAttribute('ssrc');
  3758. }).get();
  3759. if (ssrcs.length != 0) {
  3760. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  3761. }
  3762. });
  3763. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  3764. tmp.each(function () {
  3765. var ssrc = $(this).attr('ssrc');
  3766. // This should never happen, but can be useful for bug detection
  3767. if(mySdp.containsSSRC(ssrc)){
  3768. console.error("Got remove stream request for my own ssrc: "+ssrc);
  3769. return;
  3770. }
  3771. $(this).find('>parameter').each(function () {
  3772. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  3773. if ($(this).attr('value') && $(this).attr('value').length)
  3774. lines += ':' + $(this).attr('value');
  3775. lines += '\r\n';
  3776. });
  3777. });
  3778. sdp.media.forEach(function(media, idx) {
  3779. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  3780. return;
  3781. sdp.media[idx] += lines;
  3782. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  3783. self.removessrc[idx] += lines;
  3784. });
  3785. sdp.raw = sdp.session + sdp.media.join('');
  3786. });
  3787. this.modifySourcesQueue.push(function() {
  3788. // When a source is removed and if this is FF, the recvonly channel that
  3789. // receives the remote stream is deactivated . We need to diffuse the
  3790. // recvonly SSRC removal to the rest of the peers.
  3791. console.log('modify sources done');
  3792. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  3793. console.log("SDPs", mySdp, newSdp);
  3794. self.notifyMySSRCUpdate(mySdp, newSdp);
  3795. });
  3796. };
  3797. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  3798. var self = this;
  3799. if (this.peerconnection.signalingState == 'closed') return;
  3800. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  3801. // There is nothing to do since scheduled job might have been executed by another succeeding call
  3802. this.setLocalDescription();
  3803. if(successCallback){
  3804. successCallback();
  3805. }
  3806. queueCallback();
  3807. return;
  3808. }
  3809. // Reset switch streams flag
  3810. this.switchstreams = false;
  3811. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  3812. // add sources
  3813. this.addssrc.forEach(function(lines, idx) {
  3814. sdp.media[idx] += lines;
  3815. });
  3816. this.addssrc = [];
  3817. // remove sources
  3818. this.removessrc.forEach(function(lines, idx) {
  3819. lines = lines.split('\r\n');
  3820. lines.pop(); // remove empty last element;
  3821. lines.forEach(function(line) {
  3822. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  3823. });
  3824. });
  3825. this.removessrc = [];
  3826. sdp.raw = sdp.session + sdp.media.join('');
  3827. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  3828. function() {
  3829. if(self.signalingState == 'closed') {
  3830. console.error("createAnswer attempt on closed state");
  3831. queueCallback("createAnswer attempt on closed state");
  3832. return;
  3833. }
  3834. self.peerconnection.createAnswer(
  3835. function(modifiedAnswer) {
  3836. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  3837. if (self.pendingop !== null) {
  3838. var sdp = new SDP(modifiedAnswer.sdp);
  3839. if (sdp.media.length > 1) {
  3840. switch(self.pendingop) {
  3841. case 'mute':
  3842. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  3843. break;
  3844. case 'unmute':
  3845. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  3846. break;
  3847. }
  3848. sdp.raw = sdp.session + sdp.media.join('');
  3849. modifiedAnswer.sdp = sdp.raw;
  3850. }
  3851. self.pendingop = null;
  3852. }
  3853. // FIXME: pushing down an answer while ice connection state
  3854. // is still checking is bad...
  3855. //console.log(self.peerconnection.iceConnectionState);
  3856. // trying to work around another chrome bug
  3857. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  3858. self.peerconnection.setLocalDescription(modifiedAnswer,
  3859. function() {
  3860. //console.log('modified setLocalDescription ok');
  3861. self.setLocalDescription();
  3862. if(successCallback){
  3863. successCallback();
  3864. }
  3865. queueCallback();
  3866. },
  3867. function(error) {
  3868. console.error('modified setLocalDescription failed', error);
  3869. queueCallback(error);
  3870. }
  3871. );
  3872. },
  3873. function(error) {
  3874. console.error('modified answer failed', error);
  3875. queueCallback(error);
  3876. }
  3877. );
  3878. },
  3879. function(error) {
  3880. console.error('modify failed', error);
  3881. queueCallback(error);
  3882. }
  3883. );
  3884. };
  3885. /**
  3886. * Switches video streams.
  3887. * @param new_stream new stream that will be used as video of this session.
  3888. * @param oldStream old video stream of this session.
  3889. * @param success_callback callback executed after successful stream switch.
  3890. */
  3891. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  3892. var self = this;
  3893. // Remember SDP to figure out added/removed SSRCs
  3894. var oldSdp = null;
  3895. if(self.peerconnection) {
  3896. if(self.peerconnection.localDescription) {
  3897. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  3898. }
  3899. self.peerconnection.removeStream(oldStream, true);
  3900. if(new_stream)
  3901. self.peerconnection.addStream(new_stream);
  3902. }
  3903. // Conference is not active
  3904. if(!oldSdp || !self.peerconnection) {
  3905. success_callback();
  3906. return;
  3907. }
  3908. self.switchstreams = true;
  3909. self.modifySourcesQueue.push(function() {
  3910. console.log('modify sources done');
  3911. success_callback();
  3912. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  3913. console.log("SDPs", oldSdp, newSdp);
  3914. self.notifyMySSRCUpdate(oldSdp, newSdp);
  3915. });
  3916. };
  3917. /**
  3918. * Figures out added/removed ssrcs and send update IQs.
  3919. * @param old_sdp SDP object for old description.
  3920. * @param new_sdp SDP object for new description.
  3921. */
  3922. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  3923. if (!(this.peerconnection.signalingState == 'stable' &&
  3924. this.peerconnection.iceConnectionState == 'connected')){
  3925. console.log("Too early to send updates");
  3926. return;
  3927. }
  3928. // send source-remove IQ.
  3929. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  3930. var remove = $iq({to: this.peerjid, type: 'set'})
  3931. .c('jingle', {
  3932. xmlns: 'urn:xmpp:jingle:1',
  3933. action: 'source-remove',
  3934. initiator: this.initiator,
  3935. sid: this.sid
  3936. }
  3937. );
  3938. var removed = sdpDiffer.toJingle(remove);
  3939. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  3940. // it in the current form
  3941. if (removed)
  3942. remove = SSRCReplacement.processSourceRemove(remove);
  3943. if (removed && remove) {
  3944. console.info("Sending source-remove", remove);
  3945. this.connection.sendIQ(remove,
  3946. function (res) {
  3947. console.info('got remove result', res);
  3948. },
  3949. function (err) {
  3950. console.error('got remove error', err);
  3951. }
  3952. );
  3953. } else {
  3954. console.log('removal not necessary');
  3955. }
  3956. // send source-add IQ.
  3957. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  3958. var add = $iq({to: this.peerjid, type: 'set'})
  3959. .c('jingle', {
  3960. xmlns: 'urn:xmpp:jingle:1',
  3961. action: 'source-add',
  3962. initiator: this.initiator,
  3963. sid: this.sid
  3964. }
  3965. );
  3966. var added = sdpDiffer.toJingle(add);
  3967. // Let 'source-add' IQ through the hack and see if we're allowed to send
  3968. // it in the current form
  3969. if (added)
  3970. add = SSRCReplacement.processSourceAdd(add);
  3971. if (added && add) {
  3972. console.info("Sending source-add", add);
  3973. this.connection.sendIQ(add,
  3974. function (res) {
  3975. console.info('got add result', res);
  3976. },
  3977. function (err) {
  3978. console.error('got add error', err);
  3979. }
  3980. );
  3981. } else {
  3982. console.log('addition not necessary');
  3983. }
  3984. };
  3985. /**
  3986. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  3987. *
  3988. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  3989. * tracks; otherwise, <tt>false</tt>
  3990. * @param callback a function to be invoked with <tt>mute</tt> after all video
  3991. * tracks have been enabled/disabled. The function may, optionally, return
  3992. * another function which is to be invoked after the whole mute/unmute operation
  3993. * has completed successfully.
  3994. * @param options an object which specifies optional arguments such as the
  3995. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  3996. * specifies whether the method was initiated in response to a user command (in
  3997. * contrast to an automatic decision made by the application logic)
  3998. */
  3999. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  4000. var byUser;
  4001. if (options) {
  4002. byUser = options.byUser;
  4003. if (typeof byUser === 'undefined') {
  4004. byUser = true;
  4005. }
  4006. } else {
  4007. byUser = true;
  4008. }
  4009. // The user's command to mute the (local) video takes precedence over any
  4010. // automatic decision made by the application logic.
  4011. if (byUser) {
  4012. this.videoMuteByUser = mute;
  4013. } else if (this.videoMuteByUser) {
  4014. return;
  4015. }
  4016. this.hardMuteVideo(mute);
  4017. var self = this;
  4018. var oldSdp = null;
  4019. if(self.peerconnection) {
  4020. if(self.peerconnection.localDescription) {
  4021. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  4022. }
  4023. }
  4024. this.modifySourcesQueue.push(function() {
  4025. console.log('modify sources done');
  4026. callback(mute);
  4027. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  4028. console.log("SDPs", oldSdp, newSdp);
  4029. self.notifyMySSRCUpdate(oldSdp, newSdp);
  4030. });
  4031. };
  4032. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  4033. this.pendingop = muted ? 'mute' : 'unmute';
  4034. };
  4035. JingleSessionPC.prototype.sendMute = function (muted, content) {
  4036. var info = $iq({to: this.peerjid,
  4037. type: 'set'})
  4038. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4039. action: 'session-info',
  4040. initiator: this.initiator,
  4041. sid: this.sid });
  4042. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  4043. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  4044. if (content) {
  4045. info.attrs({'name': content});
  4046. }
  4047. this.connection.send(info);
  4048. };
  4049. JingleSessionPC.prototype.sendRinging = function () {
  4050. var info = $iq({to: this.peerjid,
  4051. type: 'set'})
  4052. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  4053. action: 'session-info',
  4054. initiator: this.initiator,
  4055. sid: this.sid });
  4056. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  4057. this.connection.send(info);
  4058. };
  4059. JingleSessionPC.prototype.getStats = function (interval) {
  4060. var self = this;
  4061. var recv = {audio: 0, video: 0};
  4062. var lost = {audio: 0, video: 0};
  4063. var lastrecv = {audio: 0, video: 0};
  4064. var lastlost = {audio: 0, video: 0};
  4065. var loss = {audio: 0, video: 0};
  4066. var delta = {audio: 0, video: 0};
  4067. this.statsinterval = window.setInterval(function () {
  4068. if (self && self.peerconnection && self.peerconnection.getStats) {
  4069. self.peerconnection.getStats(function (stats) {
  4070. var results = stats.result();
  4071. // TODO: there are so much statistics you can get from this..
  4072. for (var i = 0; i < results.length; ++i) {
  4073. if (results[i].type == 'ssrc') {
  4074. var packetsrecv = results[i].stat('packetsReceived');
  4075. var packetslost = results[i].stat('packetsLost');
  4076. if (packetsrecv && packetslost) {
  4077. packetsrecv = parseInt(packetsrecv, 10);
  4078. packetslost = parseInt(packetslost, 10);
  4079. if (results[i].stat('googFrameRateReceived')) {
  4080. lastlost.video = lost.video;
  4081. lastrecv.video = recv.video;
  4082. recv.video = packetsrecv;
  4083. lost.video = packetslost;
  4084. } else {
  4085. lastlost.audio = lost.audio;
  4086. lastrecv.audio = recv.audio;
  4087. recv.audio = packetsrecv;
  4088. lost.audio = packetslost;
  4089. }
  4090. }
  4091. }
  4092. }
  4093. delta.audio = recv.audio - lastrecv.audio;
  4094. delta.video = recv.video - lastrecv.video;
  4095. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  4096. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  4097. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  4098. });
  4099. }
  4100. }, interval || 3000);
  4101. return this.statsinterval;
  4102. };
  4103. JingleSessionPC.onJingleError = function (session, error)
  4104. {
  4105. console.error("Jingle error", error);
  4106. }
  4107. JingleSessionPC.onJingleFatalError = function (session, error)
  4108. {
  4109. this.service.sessionTerminated = true;
  4110. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  4111. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  4112. }
  4113. JingleSessionPC.prototype.setLocalDescription = function () {
  4114. var self = this;
  4115. var newssrcs = [];
  4116. var session = transform.parse(this.peerconnection.localDescription.sdp);
  4117. session.media.forEach(function (media) {
  4118. if (media.ssrcs != null && media.ssrcs.length > 0) {
  4119. // TODO(gp) maybe exclude FID streams?
  4120. media.ssrcs.forEach(function (ssrc) {
  4121. if (ssrc.attribute !== 'cname') {
  4122. return;
  4123. }
  4124. newssrcs.push({
  4125. 'ssrc': ssrc.id,
  4126. 'type': media.type
  4127. });
  4128. });
  4129. }
  4130. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  4131. {
  4132. newssrcs.push({
  4133. 'ssrc': self.localStreamsSSRC[media.type],
  4134. 'type': media.type
  4135. });
  4136. }
  4137. });
  4138. console.log('new ssrcs', newssrcs);
  4139. // Bind us as local SSRCs owner
  4140. if (newssrcs.length > 0) {
  4141. for (var i = 1; i <= newssrcs.length; i ++) {
  4142. var ssrc = newssrcs[i-1].ssrc;
  4143. var myJid = self.connection.emuc.myroomjid;
  4144. self.ssrcOwners[ssrc] = myJid;
  4145. }
  4146. }
  4147. }
  4148. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  4149. function sendKeyframe(pc) {
  4150. console.log('sendkeyframe', pc.iceConnectionState);
  4151. if (pc.iceConnectionState !== 'connected') return; // safe...
  4152. var self = this;
  4153. pc.setRemoteDescription(
  4154. pc.remoteDescription,
  4155. function () {
  4156. pc.createAnswer(
  4157. function (modifiedAnswer) {
  4158. pc.setLocalDescription(
  4159. modifiedAnswer,
  4160. function () {
  4161. // noop
  4162. },
  4163. function (error) {
  4164. console.log('triggerKeyframe setLocalDescription failed', error);
  4165. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  4166. }
  4167. );
  4168. },
  4169. function (error) {
  4170. console.log('triggerKeyframe createAnswer failed', error);
  4171. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  4172. }
  4173. );
  4174. },
  4175. function (error) {
  4176. console.log('triggerKeyframe setRemoteDescription failed', error);
  4177. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  4178. }
  4179. );
  4180. }
  4181. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  4182. var self = this;
  4183. var thessrc;
  4184. var streamId = RTC.getStreamID(data.stream);
  4185. // look up an associated JID for a stream id
  4186. if (!streamId) {
  4187. console.error("No stream ID for", data.stream);
  4188. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  4189. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  4190. var ssrclines
  4191. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  4192. ssrclines = ssrclines.filter(function (line) {
  4193. // NOTE(gp) previously we filtered on the mslabel, but that property
  4194. // is not always present.
  4195. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  4196. if (RTCBrowserType.isTemasysPluginUsed()) {
  4197. return ((line.indexOf('mslabel:' + streamId) !== -1));
  4198. } else {
  4199. return ((line.indexOf('msid:' + streamId) !== -1));
  4200. }
  4201. });
  4202. if (ssrclines.length) {
  4203. thessrc = ssrclines[0].substring(7).split(' ')[0];
  4204. if (!self.ssrcOwners[thessrc]) {
  4205. console.error("No SSRC owner known for: " + thessrc);
  4206. return;
  4207. }
  4208. data.peerjid = self.ssrcOwners[thessrc];
  4209. console.log('associated jid', self.ssrcOwners[thessrc]);
  4210. } else {
  4211. console.error("No SSRC lines for ", streamId);
  4212. }
  4213. }
  4214. RTC.createRemoteStream(data, this.sid, thessrc);
  4215. var isVideo = data.stream.getVideoTracks().length > 0;
  4216. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  4217. if (isVideo &&
  4218. data.peerjid && this.peerjid === data.peerjid &&
  4219. data.stream.getVideoTracks().length === 0 &&
  4220. RTC.localVideo.getTracks().length > 0) {
  4221. window.setTimeout(function () {
  4222. sendKeyframe(self.peerconnection);
  4223. }, 3000);
  4224. }
  4225. }
  4226. module.exports = JingleSessionPC;
  4227. },{"../../service/xmpp/XMPPEvents":73,"../RTC/RTC":11,"../RTC/RTCBrowserType":12,"./JingleSession":16,"./LocalSSRCReplacement":18,"./SDP":19,"./SDPDiffer":20,"./SDPUtil":21,"./TraceablePeerConnection":22,"async":30,"sdp-transform":63}],18:[function(require,module,exports){
  4228. /* global $ */
  4229. /*
  4230. Here we do modifications of local video SSRCs. There are 2 situations we have
  4231. to handle:
  4232. 1. We generate SSRC for local recvonly video stream. This is the case when we
  4233. have no local camera and it is not generated automatically, but SSRC=1 is
  4234. used implicitly. If that happens RTCP packets will be dropped by the JVB
  4235. and we won't be able to request video key frames correctly.
  4236. 2. A hack to re-use SSRC of the first video stream for any new stream created
  4237. in future. It turned out that Chrome may keep on using the SSRC of removed
  4238. video stream in RTCP even though a new one has been created. So we just
  4239. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  4240. notifications are blocked once first video SSRC is advertised to the focus.
  4241. What this hack does:
  4242. 1. Stores the SSRC of the first video stream created by
  4243. a) scanning Jingle session-accept/session-invite for existing video SSRC
  4244. b) watching for 'source-add' for new video stream if it has not been
  4245. created in step a)
  4246. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  4247. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  4248. returned to the other parts of the application.
  4249. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  4250. blocks those notifications. This makes Jicofo and all participants think
  4251. that it exists all the time even if the video stream has been removed or
  4252. replaced locally. Thanks to that there is no additional signaling activity
  4253. on video mute or when switching to the desktop stream.
  4254. */
  4255. var SDP = require('./SDP');
  4256. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4257. /**
  4258. * The hack is enabled on all browsers except FF by default
  4259. * FIXME finish the hack once removeStream method is implemented in FF
  4260. * @type {boolean}
  4261. */
  4262. var isEnabled = !RTCBrowserType.isFirefox();
  4263. /**
  4264. * Stored SSRC of local video stream.
  4265. */
  4266. var localVideoSSRC;
  4267. /**
  4268. * SSRC used for recvonly video stream when we have no local camera.
  4269. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  4270. * instead of 1.
  4271. */
  4272. var localRecvOnlySSRC;
  4273. /**
  4274. * cname for <tt>localRecvOnlySSRC</tt>
  4275. */
  4276. var localRecvOnlyCName;
  4277. /**
  4278. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  4279. * from given Jingle IQ.
  4280. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  4281. * @param actionName display name of the action which will be printed in log
  4282. * messages.
  4283. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  4284. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  4285. * other SSRCs left to be signaled after removing it.
  4286. */
  4287. var filterOutSource = function (modifyIq, actionName) {
  4288. var modifyIqTree = $(modifyIq.tree());
  4289. if (!localVideoSSRC)
  4290. return modifyIqTree[0];
  4291. var videoSSRC = modifyIqTree.find(
  4292. '>jingle>content[name="video"]' +
  4293. '>description>source[ssrc="' + localVideoSSRC + '"]');
  4294. if (!videoSSRC.length) {
  4295. return modifyIqTree[0];
  4296. }
  4297. console.info(
  4298. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  4299. videoSSRC.remove();
  4300. // Check if any sources still left to be added/removed
  4301. if (modifyIqTree.find('>jingle>content>description>source').length) {
  4302. return modifyIqTree[0];
  4303. } else {
  4304. return null;
  4305. }
  4306. };
  4307. /**
  4308. * Scans given Jingle IQ for video SSRC and stores it.
  4309. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  4310. */
  4311. var storeLocalVideoSSRC = function (jingleIq) {
  4312. var videoSSRCs =
  4313. $(jingleIq.tree())
  4314. .find('>jingle>content[name="video"]>description>source');
  4315. videoSSRCs.each(function (idx, ssrcElem) {
  4316. if (localVideoSSRC)
  4317. return;
  4318. // We consider SSRC real only if it has msid attribute
  4319. // recvonly streams in FF do not have it as well as local SSRCs
  4320. // we generate for recvonly streams in Chrome
  4321. var ssrSel = $(ssrcElem);
  4322. var msid = ssrSel.find('>parameter[name="msid"]');
  4323. if (msid.length) {
  4324. var ssrcVal = ssrSel.attr('ssrc');
  4325. if (ssrcVal) {
  4326. localVideoSSRC = ssrcVal;
  4327. console.info('Stored local video SSRC' +
  4328. ' for future re-use: ' + localVideoSSRC);
  4329. }
  4330. }
  4331. });
  4332. };
  4333. /**
  4334. * Generates new SSRC for local video recvonly stream.
  4335. * FIXME what about eventual SSRC collision ?
  4336. */
  4337. function generateRecvonlySSRC() {
  4338. //
  4339. localRecvOnlySSRC =
  4340. Math.random().toString(10).substring(2, 11);
  4341. localRecvOnlyCName =
  4342. Math.random().toString(36).substring(2);
  4343. console.info(
  4344. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  4345. ", cname: " + localRecvOnlyCName);
  4346. }
  4347. var LocalSSRCReplacement = {
  4348. /**
  4349. * Method must be called before 'session-initiate' or 'session-invite' is
  4350. * sent. Scans the IQ for local video SSRC and stores it if detected.
  4351. *
  4352. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  4353. * which will be scanned for local video SSRC.
  4354. */
  4355. processSessionInit: function (sessionInit) {
  4356. if (!isEnabled)
  4357. return;
  4358. if (localVideoSSRC) {
  4359. console.error("Local SSRC stored already: " + localVideoSSRC);
  4360. return;
  4361. }
  4362. storeLocalVideoSSRC(sessionInit);
  4363. },
  4364. /**
  4365. * If we have local video SSRC stored searched given
  4366. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  4367. * with the stored one.
  4368. * @param localDescription local description object that will have local
  4369. * video SSRC replaced with the stored one
  4370. * @returns modified <tt>localDescription</tt> object.
  4371. */
  4372. mungeLocalVideoSSRC: function (localDescription) {
  4373. if (!isEnabled)
  4374. return localDescription;
  4375. if (!localDescription) {
  4376. console.warn("localDescription is null or undefined");
  4377. return localDescription;
  4378. }
  4379. // IF we have local video SSRC stored make sure it is replaced
  4380. // with old SSRC
  4381. if (localVideoSSRC) {
  4382. var newSdp = new SDP(localDescription.sdp);
  4383. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  4384. !newSdp.containsSSRC(localVideoSSRC)) {
  4385. // Get new video SSRC
  4386. var map = newSdp.getMediaSsrcMap();
  4387. var videoPart = map[1];
  4388. var videoSSRCs = videoPart.ssrcs;
  4389. var newSSRC = Object.keys(videoSSRCs)[0];
  4390. console.info(
  4391. "Replacing new video SSRC: " + newSSRC +
  4392. " with " + localVideoSSRC);
  4393. localDescription.sdp =
  4394. newSdp.raw.replace(
  4395. new RegExp('a=ssrc:' + newSSRC, 'g'),
  4396. 'a=ssrc:' + localVideoSSRC);
  4397. }
  4398. } else {
  4399. // Make sure we have any SSRC for recvonly video stream
  4400. var sdp = new SDP(localDescription.sdp);
  4401. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  4402. sdp.media[1].indexOf('a=recvonly') !== -1) {
  4403. if (!localRecvOnlySSRC) {
  4404. generateRecvonlySSRC();
  4405. }
  4406. console.info('No SSRC in video recvonly stream' +
  4407. ' - adding SSRC: ' + localRecvOnlySSRC);
  4408. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  4409. ' cname:' + localRecvOnlyCName + '\r\n';
  4410. localDescription.sdp = sdp.session + sdp.media.join('');
  4411. }
  4412. }
  4413. return localDescription;
  4414. },
  4415. /**
  4416. * Method must be called before 'source-add' notification is sent. In case
  4417. * we have local video SSRC advertised already it will be removed from the
  4418. * notification. If no other SSRCs are described by given IQ null will be
  4419. * returned which means that there is no point in sending the notification.
  4420. * @param sourceAdd 'source-add' Jingle IQ to be processed
  4421. * @returns modified 'source-add' IQ which can be sent to the focus or
  4422. * <tt>null</tt> if no notification shall be sent. It is no longer
  4423. * a Strophe IQ Builder instance, but DOM element tree.
  4424. */
  4425. processSourceAdd: function (sourceAdd) {
  4426. if (!isEnabled)
  4427. return sourceAdd;
  4428. if (!localVideoSSRC) {
  4429. // Store local SSRC if available
  4430. storeLocalVideoSSRC(sourceAdd);
  4431. return sourceAdd;
  4432. } else {
  4433. return filterOutSource(sourceAdd, 'source-add');
  4434. }
  4435. },
  4436. /**
  4437. * Method must be called before 'source-remove' notification is sent.
  4438. * Removes local video SSRC from the notification. If there are no other
  4439. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  4440. * means that there is no point in sending the notification.
  4441. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  4442. * @returns modified 'source-remove' IQ which can be sent to the focus or
  4443. * <tt>null</tt> if no notification shall be sent. It is no longer
  4444. * a Strophe IQ Builder instance, but DOM element tree.
  4445. */
  4446. processSourceRemove: function (sourceRemove) {
  4447. if (!isEnabled)
  4448. return sourceRemove;
  4449. return filterOutSource(sourceRemove, 'source-remove');
  4450. },
  4451. /**
  4452. * Turns the hack on or off
  4453. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  4454. * to disable it
  4455. */
  4456. setEnabled: function (enabled) {
  4457. isEnabled = enabled;
  4458. }
  4459. };
  4460. module.exports = LocalSSRCReplacement;
  4461. },{"../RTC/RTCBrowserType":12,"./SDP":19}],19:[function(require,module,exports){
  4462. /* jshint -W117 */
  4463. var SDPUtil = require("./SDPUtil");
  4464. // SDP STUFF
  4465. function SDP(sdp) {
  4466. this.media = sdp.split('\r\nm=');
  4467. for (var i = 1; i < this.media.length; i++) {
  4468. this.media[i] = 'm=' + this.media[i];
  4469. if (i != this.media.length - 1) {
  4470. this.media[i] += '\r\n';
  4471. }
  4472. }
  4473. this.session = this.media.shift() + '\r\n';
  4474. this.raw = this.session + this.media.join('');
  4475. }
  4476. /**
  4477. * Returns map of MediaChannel mapped per channel idx.
  4478. */
  4479. SDP.prototype.getMediaSsrcMap = function() {
  4480. var self = this;
  4481. var media_ssrcs = {};
  4482. var tmp;
  4483. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  4484. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  4485. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  4486. var media = {
  4487. mediaindex: mediaindex,
  4488. mid: mid,
  4489. ssrcs: {},
  4490. ssrcGroups: []
  4491. };
  4492. media_ssrcs[mediaindex] = media;
  4493. tmp.forEach(function (line) {
  4494. var linessrc = line.substring(7).split(' ')[0];
  4495. // allocate new ChannelSsrc
  4496. if(!media.ssrcs[linessrc]) {
  4497. media.ssrcs[linessrc] = {
  4498. ssrc: linessrc,
  4499. lines: []
  4500. };
  4501. }
  4502. media.ssrcs[linessrc].lines.push(line);
  4503. });
  4504. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  4505. tmp.forEach(function(line){
  4506. var semantics = line.substr(0, idx).substr(13);
  4507. var ssrcs = line.substr(14 + semantics.length).split(' ');
  4508. if (ssrcs.length != 0) {
  4509. media.ssrcGroups.push({
  4510. semantics: semantics,
  4511. ssrcs: ssrcs
  4512. });
  4513. }
  4514. });
  4515. }
  4516. return media_ssrcs;
  4517. };
  4518. /**
  4519. * Returns <tt>true</tt> if this SDP contains given SSRC.
  4520. * @param ssrc the ssrc to check.
  4521. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  4522. */
  4523. SDP.prototype.containsSSRC = function(ssrc) {
  4524. var medias = this.getMediaSsrcMap();
  4525. var contains = false;
  4526. Object.keys(medias).forEach(function(mediaindex){
  4527. var media = medias[mediaindex];
  4528. //console.log("Check", channel, ssrc);
  4529. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  4530. contains = true;
  4531. }
  4532. });
  4533. return contains;
  4534. };
  4535. // remove iSAC and CN from SDP
  4536. SDP.prototype.mangle = function () {
  4537. var i, j, mline, lines, rtpmap, newdesc;
  4538. for (i = 0; i < this.media.length; i++) {
  4539. lines = this.media[i].split('\r\n');
  4540. lines.pop(); // remove empty last element
  4541. mline = SDPUtil.parse_mline(lines.shift());
  4542. if (mline.media != 'audio')
  4543. continue;
  4544. newdesc = '';
  4545. mline.fmt.length = 0;
  4546. for (j = 0; j < lines.length; j++) {
  4547. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  4548. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  4549. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  4550. continue;
  4551. mline.fmt.push(rtpmap.id);
  4552. newdesc += lines[j] + '\r\n';
  4553. } else {
  4554. newdesc += lines[j] + '\r\n';
  4555. }
  4556. }
  4557. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  4558. this.media[i] += newdesc;
  4559. }
  4560. this.raw = this.session + this.media.join('');
  4561. };
  4562. // remove lines matching prefix from session section
  4563. SDP.prototype.removeSessionLines = function(prefix) {
  4564. var self = this;
  4565. var lines = SDPUtil.find_lines(this.session, prefix);
  4566. lines.forEach(function(line) {
  4567. self.session = self.session.replace(line + '\r\n', '');
  4568. });
  4569. this.raw = this.session + this.media.join('');
  4570. return lines;
  4571. }
  4572. // remove lines matching prefix from a media section specified by mediaindex
  4573. // TODO: non-numeric mediaindex could match mid
  4574. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  4575. var self = this;
  4576. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  4577. lines.forEach(function(line) {
  4578. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  4579. });
  4580. this.raw = this.session + this.media.join('');
  4581. return lines;
  4582. }
  4583. // add content's to a jingle element
  4584. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  4585. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  4586. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  4587. var self = this;
  4588. // new bundle plan
  4589. if (SDPUtil.find_line(this.session, 'a=group:')) {
  4590. lines = SDPUtil.find_lines(this.session, 'a=group:');
  4591. for (i = 0; i < lines.length; i++) {
  4592. tmp = lines[i].split(' ');
  4593. var semantics = tmp.shift().substr(8);
  4594. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  4595. for (j = 0; j < tmp.length; j++) {
  4596. elem.c('content', {name: tmp[j]}).up();
  4597. }
  4598. elem.up();
  4599. }
  4600. }
  4601. for (i = 0; i < this.media.length; i++) {
  4602. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  4603. if (!(mline.media === 'audio' ||
  4604. mline.media === 'video' ||
  4605. mline.media === 'application'))
  4606. {
  4607. continue;
  4608. }
  4609. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  4610. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  4611. } else {
  4612. if(ssrcs && ssrcs[mline.media])
  4613. {
  4614. ssrc = ssrcs[mline.media];
  4615. }
  4616. else
  4617. ssrc = false;
  4618. }
  4619. elem.c('content', {creator: thecreator, name: mline.media});
  4620. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  4621. // prefer identifier from a=mid if present
  4622. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  4623. elem.attrs({ name: mid });
  4624. }
  4625. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  4626. {
  4627. elem.c('description',
  4628. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  4629. media: mline.media });
  4630. if (ssrc) {
  4631. elem.attrs({ssrc: ssrc});
  4632. }
  4633. for (j = 0; j < mline.fmt.length; j++) {
  4634. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  4635. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  4636. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  4637. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  4638. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  4639. for (k = 0; k < tmp.length; k++) {
  4640. elem.c('parameter', tmp[k]).up();
  4641. }
  4642. }
  4643. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  4644. elem.up();
  4645. }
  4646. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  4647. elem.c('encryption', {required: 1});
  4648. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  4649. crypto.forEach(function(line) {
  4650. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  4651. });
  4652. elem.up(); // end of encryption
  4653. }
  4654. if (ssrc) {
  4655. // new style mapping
  4656. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  4657. // FIXME: group by ssrc and support multiple different ssrcs
  4658. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  4659. if(ssrclines.length > 0) {
  4660. ssrclines.forEach(function (line) {
  4661. idx = line.indexOf(' ');
  4662. var linessrc = line.substr(0, idx).substr(7);
  4663. if (linessrc != ssrc) {
  4664. elem.up();
  4665. ssrc = linessrc;
  4666. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  4667. }
  4668. var kv = line.substr(idx + 1);
  4669. elem.c('parameter');
  4670. if (kv.indexOf(':') == -1) {
  4671. elem.attrs({ name: kv });
  4672. } else {
  4673. var k = kv.split(':', 2)[0];
  4674. elem.attrs({ name: k });
  4675. var v = kv.split(':', 2)[1];
  4676. v = SDPUtil.filter_special_chars(v);
  4677. elem.attrs({ value: v });
  4678. }
  4679. elem.up();
  4680. });
  4681. }
  4682. else
  4683. {
  4684. elem.up();
  4685. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  4686. elem.c('parameter');
  4687. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  4688. elem.up();
  4689. var msid = null;
  4690. if(mline.media == "audio")
  4691. {
  4692. msid = APP.RTC.localAudio.getId();
  4693. }
  4694. else
  4695. {
  4696. msid = APP.RTC.localVideo.getId();
  4697. }
  4698. if(msid != null)
  4699. {
  4700. msid = SDPUtil.filter_special_chars(msid);
  4701. elem.c('parameter');
  4702. elem.attrs({name: "msid", value:msid});
  4703. elem.up();
  4704. elem.c('parameter');
  4705. elem.attrs({name: "mslabel", value:msid});
  4706. elem.up();
  4707. elem.c('parameter');
  4708. elem.attrs({name: "label", value:msid});
  4709. elem.up();
  4710. }
  4711. }
  4712. elem.up();
  4713. // XEP-0339 handle ssrc-group attributes
  4714. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  4715. ssrc_group_lines.forEach(function(line) {
  4716. idx = line.indexOf(' ');
  4717. var semantics = line.substr(0, idx).substr(13);
  4718. var ssrcs = line.substr(14 + semantics.length).split(' ');
  4719. if (ssrcs.length != 0) {
  4720. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  4721. ssrcs.forEach(function(ssrc) {
  4722. elem.c('source', { ssrc: ssrc })
  4723. .up();
  4724. });
  4725. elem.up();
  4726. }
  4727. });
  4728. }
  4729. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  4730. elem.c('rtcp-mux').up();
  4731. }
  4732. // XEP-0293 -- map a=rtcp-fb:*
  4733. this.RtcpFbToJingle(i, elem, '*');
  4734. // XEP-0294
  4735. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  4736. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  4737. for (j = 0; j < lines.length; j++) {
  4738. tmp = SDPUtil.parse_extmap(lines[j]);
  4739. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  4740. uri: tmp.uri,
  4741. id: tmp.value });
  4742. if (tmp.hasOwnProperty('direction')) {
  4743. switch (tmp.direction) {
  4744. case 'sendonly':
  4745. elem.attrs({senders: 'responder'});
  4746. break;
  4747. case 'recvonly':
  4748. elem.attrs({senders: 'initiator'});
  4749. break;
  4750. case 'sendrecv':
  4751. elem.attrs({senders: 'both'});
  4752. break;
  4753. case 'inactive':
  4754. elem.attrs({senders: 'none'});
  4755. break;
  4756. }
  4757. }
  4758. // TODO: handle params
  4759. elem.up();
  4760. }
  4761. }
  4762. elem.up(); // end of description
  4763. }
  4764. // map ice-ufrag/pwd, dtls fingerprint, candidates
  4765. this.TransportToJingle(i, elem);
  4766. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  4767. elem.attrs({senders: 'both'});
  4768. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  4769. elem.attrs({senders: 'initiator'});
  4770. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  4771. elem.attrs({senders: 'responder'});
  4772. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  4773. elem.attrs({senders: 'none'});
  4774. }
  4775. if (mline.port == '0') {
  4776. // estos hack to reject an m-line
  4777. elem.attrs({senders: 'rejected'});
  4778. }
  4779. elem.up(); // end of content
  4780. }
  4781. elem.up();
  4782. return elem;
  4783. };
  4784. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  4785. var i = mediaindex;
  4786. var tmp;
  4787. var self = this;
  4788. elem.c('transport');
  4789. // XEP-0343 DTLS/SCTP
  4790. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  4791. {
  4792. var sctpmap = SDPUtil.find_line(
  4793. this.media[i], 'a=sctpmap:', self.session);
  4794. if (sctpmap)
  4795. {
  4796. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  4797. elem.c('sctpmap',
  4798. {
  4799. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  4800. number: sctpAttrs[0], /* SCTP port */
  4801. protocol: sctpAttrs[1], /* protocol */
  4802. });
  4803. // Optional stream count attribute
  4804. if (sctpAttrs.length > 2)
  4805. elem.attrs({ streams: sctpAttrs[2]});
  4806. elem.up();
  4807. }
  4808. }
  4809. // XEP-0320
  4810. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  4811. fingerprints.forEach(function(line) {
  4812. tmp = SDPUtil.parse_fingerprint(line);
  4813. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  4814. elem.c('fingerprint').t(tmp.fingerprint);
  4815. delete tmp.fingerprint;
  4816. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  4817. if (line) {
  4818. tmp.setup = line.substr(8);
  4819. }
  4820. elem.attrs(tmp);
  4821. elem.up(); // end of fingerprint
  4822. });
  4823. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  4824. if (tmp) {
  4825. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  4826. elem.attrs(tmp);
  4827. // XEP-0176
  4828. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  4829. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  4830. lines.forEach(function (line) {
  4831. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  4832. });
  4833. }
  4834. }
  4835. elem.up(); // end of transport
  4836. }
  4837. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  4838. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  4839. lines.forEach(function (line) {
  4840. var tmp = SDPUtil.parse_rtcpfb(line);
  4841. if (tmp.type == 'trr-int') {
  4842. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  4843. elem.up();
  4844. } else {
  4845. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  4846. if (tmp.params.length > 0) {
  4847. elem.attrs({'subtype': tmp.params[0]});
  4848. }
  4849. elem.up();
  4850. }
  4851. });
  4852. };
  4853. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  4854. var media = '';
  4855. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  4856. if (tmp.length) {
  4857. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  4858. if (tmp.attr('value')) {
  4859. media += tmp.attr('value');
  4860. } else {
  4861. media += '0';
  4862. }
  4863. media += '\r\n';
  4864. }
  4865. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  4866. tmp.each(function () {
  4867. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  4868. if ($(this).attr('subtype')) {
  4869. media += ' ' + $(this).attr('subtype');
  4870. }
  4871. media += '\r\n';
  4872. });
  4873. return media;
  4874. };
  4875. // construct an SDP from a jingle stanza
  4876. SDP.prototype.fromJingle = function (jingle) {
  4877. var self = this;
  4878. this.raw = 'v=0\r\n' +
  4879. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  4880. 's=-\r\n' +
  4881. 't=0 0\r\n';
  4882. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  4883. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  4884. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  4885. var contents = $(group).find('>content').map(function (idx, content) {
  4886. return content.getAttribute('name');
  4887. }).get();
  4888. if (contents.length > 0) {
  4889. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  4890. }
  4891. });
  4892. }
  4893. this.session = this.raw;
  4894. jingle.find('>content').each(function () {
  4895. var m = self.jingle2media($(this));
  4896. self.media.push(m);
  4897. });
  4898. // reconstruct msid-semantic -- apparently not necessary
  4899. /*
  4900. var msid = SDPUtil.parse_ssrc(this.raw);
  4901. if (msid.hasOwnProperty('mslabel')) {
  4902. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  4903. }
  4904. */
  4905. this.raw = this.session + this.media.join('');
  4906. };
  4907. // translate a jingle content element into an an SDP media part
  4908. SDP.prototype.jingle2media = function (content) {
  4909. var media = '',
  4910. desc = content.find('description'),
  4911. ssrc = desc.attr('ssrc'),
  4912. self = this,
  4913. tmp;
  4914. var sctp = content.find(
  4915. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  4916. tmp = { media: desc.attr('media') };
  4917. tmp.port = '1';
  4918. if (content.attr('senders') == 'rejected') {
  4919. // estos hack to reject an m-line.
  4920. tmp.port = '0';
  4921. }
  4922. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  4923. if (sctp.length)
  4924. tmp.proto = 'DTLS/SCTP';
  4925. else
  4926. tmp.proto = 'RTP/SAVPF';
  4927. } else {
  4928. tmp.proto = 'RTP/AVPF';
  4929. }
  4930. if (!sctp.length)
  4931. {
  4932. tmp.fmt = desc.find('payload-type').map(
  4933. function () { return this.getAttribute('id'); }).get();
  4934. media += SDPUtil.build_mline(tmp) + '\r\n';
  4935. }
  4936. else
  4937. {
  4938. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  4939. media += 'a=sctpmap:' + sctp.attr('number') +
  4940. ' ' + sctp.attr('protocol');
  4941. var streamCount = sctp.attr('streams');
  4942. if (streamCount)
  4943. media += ' ' + streamCount + '\r\n';
  4944. else
  4945. media += '\r\n';
  4946. }
  4947. media += 'c=IN IP4 0.0.0.0\r\n';
  4948. if (!sctp.length)
  4949. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  4950. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  4951. if (tmp.length) {
  4952. if (tmp.attr('ufrag')) {
  4953. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  4954. }
  4955. if (tmp.attr('pwd')) {
  4956. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  4957. }
  4958. tmp.find('>fingerprint').each(function () {
  4959. // FIXME: check namespace at some point
  4960. media += 'a=fingerprint:' + this.getAttribute('hash');
  4961. media += ' ' + $(this).text();
  4962. media += '\r\n';
  4963. if (this.getAttribute('setup')) {
  4964. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  4965. }
  4966. });
  4967. }
  4968. switch (content.attr('senders')) {
  4969. case 'initiator':
  4970. media += 'a=sendonly\r\n';
  4971. break;
  4972. case 'responder':
  4973. media += 'a=recvonly\r\n';
  4974. break;
  4975. case 'none':
  4976. media += 'a=inactive\r\n';
  4977. break;
  4978. case 'both':
  4979. media += 'a=sendrecv\r\n';
  4980. break;
  4981. }
  4982. media += 'a=mid:' + content.attr('name') + '\r\n';
  4983. // <description><rtcp-mux/></description>
  4984. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  4985. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  4986. if (desc.find('rtcp-mux').length) {
  4987. media += 'a=rtcp-mux\r\n';
  4988. }
  4989. if (desc.find('encryption').length) {
  4990. desc.find('encryption>crypto').each(function () {
  4991. media += 'a=crypto:' + this.getAttribute('tag');
  4992. media += ' ' + this.getAttribute('crypto-suite');
  4993. media += ' ' + this.getAttribute('key-params');
  4994. if (this.getAttribute('session-params')) {
  4995. media += ' ' + this.getAttribute('session-params');
  4996. }
  4997. media += '\r\n';
  4998. });
  4999. }
  5000. desc.find('payload-type').each(function () {
  5001. media += SDPUtil.build_rtpmap(this) + '\r\n';
  5002. if ($(this).find('>parameter').length) {
  5003. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  5004. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  5005. media += '\r\n';
  5006. }
  5007. // xep-0293
  5008. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  5009. });
  5010. // xep-0293
  5011. media += self.RtcpFbFromJingle(desc, '*');
  5012. // xep-0294
  5013. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  5014. tmp.each(function () {
  5015. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  5016. });
  5017. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  5018. media += SDPUtil.candidateFromJingle(this);
  5019. });
  5020. // XEP-0339 handle ssrc-group attributes
  5021. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  5022. var semantics = this.getAttribute('semantics');
  5023. var ssrcs = $(this).find('>source').map(function() {
  5024. return this.getAttribute('ssrc');
  5025. }).get();
  5026. if (ssrcs.length != 0) {
  5027. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  5028. }
  5029. });
  5030. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  5031. tmp.each(function () {
  5032. var ssrc = this.getAttribute('ssrc');
  5033. $(this).find('>parameter').each(function () {
  5034. var name = this.getAttribute('name');
  5035. var value = this.getAttribute('value');
  5036. value = SDPUtil.filter_special_chars(value);
  5037. media += 'a=ssrc:' + ssrc + ' ' + name;
  5038. if (value && value.length)
  5039. media += ':' + value;
  5040. media += '\r\n';
  5041. });
  5042. });
  5043. return media;
  5044. };
  5045. module.exports = SDP;
  5046. },{"./SDPUtil":21}],20:[function(require,module,exports){
  5047. var SDPUtil = require("./SDPUtil");
  5048. function SDPDiffer(mySDP, otherSDP) {
  5049. this.mySDP = mySDP;
  5050. this.otherSDP = otherSDP;
  5051. }
  5052. /**
  5053. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  5054. * @param otherSdp the other SDP to check ssrc with.
  5055. */
  5056. SDPDiffer.prototype.getNewMedia = function() {
  5057. // this could be useful in Array.prototype.
  5058. function arrayEquals(array) {
  5059. // if the other array is a falsy value, return
  5060. if (!array)
  5061. return false;
  5062. // compare lengths - can save a lot of time
  5063. if (this.length != array.length)
  5064. return false;
  5065. for (var i = 0, l=this.length; i < l; i++) {
  5066. // Check if we have nested arrays
  5067. if (this[i] instanceof Array && array[i] instanceof Array) {
  5068. // recurse into the nested arrays
  5069. if (!this[i].equals(array[i]))
  5070. return false;
  5071. }
  5072. else if (this[i] != array[i]) {
  5073. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  5074. return false;
  5075. }
  5076. }
  5077. return true;
  5078. }
  5079. var myMedias = this.mySDP.getMediaSsrcMap();
  5080. var othersMedias = this.otherSDP.getMediaSsrcMap();
  5081. var newMedia = {};
  5082. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  5083. var myMedia = myMedias[othersMediaIdx];
  5084. var othersMedia = othersMedias[othersMediaIdx];
  5085. if(!myMedia && othersMedia) {
  5086. // Add whole channel
  5087. newMedia[othersMediaIdx] = othersMedia;
  5088. return;
  5089. }
  5090. // Look for new ssrcs accross the channel
  5091. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  5092. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  5093. // Allocate channel if we've found ssrc that doesn't exist in our channel
  5094. if(!newMedia[othersMediaIdx]){
  5095. newMedia[othersMediaIdx] = {
  5096. mediaindex: othersMedia.mediaindex,
  5097. mid: othersMedia.mid,
  5098. ssrcs: {},
  5099. ssrcGroups: []
  5100. };
  5101. }
  5102. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  5103. }
  5104. });
  5105. // Look for new ssrc groups across the channels
  5106. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  5107. // try to match the other ssrc-group with an ssrc-group of ours
  5108. var matched = false;
  5109. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  5110. var mySsrcGroup = myMedia.ssrcGroups[i];
  5111. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  5112. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  5113. matched = true;
  5114. break;
  5115. }
  5116. }
  5117. if (!matched) {
  5118. // Allocate channel if we've found an ssrc-group that doesn't
  5119. // exist in our channel
  5120. if(!newMedia[othersMediaIdx]){
  5121. newMedia[othersMediaIdx] = {
  5122. mediaindex: othersMedia.mediaindex,
  5123. mid: othersMedia.mid,
  5124. ssrcs: {},
  5125. ssrcGroups: []
  5126. };
  5127. }
  5128. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  5129. }
  5130. });
  5131. });
  5132. return newMedia;
  5133. };
  5134. /**
  5135. * Sends SSRC update IQ.
  5136. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  5137. * @param sid session identifier that will be put into the IQ.
  5138. * @param initiator initiator identifier.
  5139. * @param toJid destination Jid
  5140. * @param isAdd indicates if this is remove or add operation.
  5141. */
  5142. SDPDiffer.prototype.toJingle = function(modify) {
  5143. var sdpMediaSsrcs = this.getNewMedia();
  5144. var self = this;
  5145. // FIXME: only announce video ssrcs since we mix audio and dont need
  5146. // the audio ssrcs therefore
  5147. var modified = false;
  5148. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  5149. modified = true;
  5150. var media = sdpMediaSsrcs[mediaindex];
  5151. modify.c('content', {name: media.mid});
  5152. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  5153. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  5154. // generate sources from lines
  5155. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  5156. var mediaSsrc = media.ssrcs[ssrcNum];
  5157. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  5158. modify.attrs({ssrc: mediaSsrc.ssrc});
  5159. // iterate over ssrc lines
  5160. mediaSsrc.lines.forEach(function (line) {
  5161. var idx = line.indexOf(' ');
  5162. var kv = line.substr(idx + 1);
  5163. modify.c('parameter');
  5164. if (kv.indexOf(':') == -1) {
  5165. modify.attrs({ name: kv });
  5166. } else {
  5167. var nv = kv.split(':', 2);
  5168. var name = nv[0];
  5169. var value = SDPUtil.filter_special_chars(nv[1]);
  5170. modify.attrs({ name: name });
  5171. modify.attrs({ value: value });
  5172. }
  5173. modify.up(); // end of parameter
  5174. });
  5175. modify.up(); // end of source
  5176. });
  5177. // generate source groups from lines
  5178. media.ssrcGroups.forEach(function(ssrcGroup) {
  5179. if (ssrcGroup.ssrcs.length != 0) {
  5180. modify.c('ssrc-group', {
  5181. semantics: ssrcGroup.semantics,
  5182. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  5183. });
  5184. ssrcGroup.ssrcs.forEach(function (ssrc) {
  5185. modify.c('source', { ssrc: ssrc })
  5186. .up(); // end of source
  5187. });
  5188. modify.up(); // end of ssrc-group
  5189. }
  5190. });
  5191. modify.up(); // end of description
  5192. modify.up(); // end of content
  5193. });
  5194. return modified;
  5195. };
  5196. module.exports = SDPDiffer;
  5197. },{"./SDPUtil":21}],21:[function(require,module,exports){
  5198. SDPUtil = {
  5199. filter_special_chars: function (text) {
  5200. return text.replace(/[\\\/\{,\}\+]/g, "");
  5201. },
  5202. iceparams: function (mediadesc, sessiondesc) {
  5203. var data = null;
  5204. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  5205. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  5206. data = {
  5207. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  5208. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  5209. };
  5210. }
  5211. return data;
  5212. },
  5213. parse_iceufrag: function (line) {
  5214. return line.substring(12);
  5215. },
  5216. build_iceufrag: function (frag) {
  5217. return 'a=ice-ufrag:' + frag;
  5218. },
  5219. parse_icepwd: function (line) {
  5220. return line.substring(10);
  5221. },
  5222. build_icepwd: function (pwd) {
  5223. return 'a=ice-pwd:' + pwd;
  5224. },
  5225. parse_mid: function (line) {
  5226. return line.substring(6);
  5227. },
  5228. parse_mline: function (line) {
  5229. var parts = line.substring(2).split(' '),
  5230. data = {};
  5231. data.media = parts.shift();
  5232. data.port = parts.shift();
  5233. data.proto = parts.shift();
  5234. if (parts[parts.length - 1] === '') { // trailing whitespace
  5235. parts.pop();
  5236. }
  5237. data.fmt = parts;
  5238. return data;
  5239. },
  5240. build_mline: function (mline) {
  5241. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  5242. },
  5243. parse_rtpmap: function (line) {
  5244. var parts = line.substring(9).split(' '),
  5245. data = {};
  5246. data.id = parts.shift();
  5247. parts = parts[0].split('/');
  5248. data.name = parts.shift();
  5249. data.clockrate = parts.shift();
  5250. data.channels = parts.length ? parts.shift() : '1';
  5251. return data;
  5252. },
  5253. /**
  5254. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  5255. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  5256. * @returns [SCTP port number, protocol, streams]
  5257. */
  5258. parse_sctpmap: function (line)
  5259. {
  5260. var parts = line.substring(10).split(' ');
  5261. var sctpPort = parts[0];
  5262. var protocol = parts[1];
  5263. // Stream count is optional
  5264. var streamCount = parts.length > 2 ? parts[2] : null;
  5265. return [sctpPort, protocol, streamCount];// SCTP port
  5266. },
  5267. build_rtpmap: function (el) {
  5268. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  5269. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  5270. line += '/' + el.getAttribute('channels');
  5271. }
  5272. return line;
  5273. },
  5274. parse_crypto: function (line) {
  5275. var parts = line.substring(9).split(' '),
  5276. data = {};
  5277. data.tag = parts.shift();
  5278. data['crypto-suite'] = parts.shift();
  5279. data['key-params'] = parts.shift();
  5280. if (parts.length) {
  5281. data['session-params'] = parts.join(' ');
  5282. }
  5283. return data;
  5284. },
  5285. parse_fingerprint: function (line) { // RFC 4572
  5286. var parts = line.substring(14).split(' '),
  5287. data = {};
  5288. data.hash = parts.shift();
  5289. data.fingerprint = parts.shift();
  5290. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  5291. return data;
  5292. },
  5293. parse_fmtp: function (line) {
  5294. var parts = line.split(' '),
  5295. i, key, value,
  5296. data = [];
  5297. parts.shift();
  5298. parts = parts.join(' ').split(';');
  5299. for (i = 0; i < parts.length; i++) {
  5300. key = parts[i].split('=')[0];
  5301. while (key.length && key[0] == ' ') {
  5302. key = key.substring(1);
  5303. }
  5304. value = parts[i].split('=')[1];
  5305. if (key && value) {
  5306. data.push({name: key, value: value});
  5307. } else if (key) {
  5308. // rfc 4733 (DTMF) style stuff
  5309. data.push({name: '', value: key});
  5310. }
  5311. }
  5312. return data;
  5313. },
  5314. parse_icecandidate: function (line) {
  5315. var candidate = {},
  5316. elems = line.split(' ');
  5317. candidate.foundation = elems[0].substring(12);
  5318. candidate.component = elems[1];
  5319. candidate.protocol = elems[2].toLowerCase();
  5320. candidate.priority = elems[3];
  5321. candidate.ip = elems[4];
  5322. candidate.port = elems[5];
  5323. // elems[6] => "typ"
  5324. candidate.type = elems[7];
  5325. candidate.generation = 0; // default value, may be overwritten below
  5326. for (var i = 8; i < elems.length; i += 2) {
  5327. switch (elems[i]) {
  5328. case 'raddr':
  5329. candidate['rel-addr'] = elems[i + 1];
  5330. break;
  5331. case 'rport':
  5332. candidate['rel-port'] = elems[i + 1];
  5333. break;
  5334. case 'generation':
  5335. candidate.generation = elems[i + 1];
  5336. break;
  5337. case 'tcptype':
  5338. candidate.tcptype = elems[i + 1];
  5339. break;
  5340. default: // TODO
  5341. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  5342. }
  5343. }
  5344. candidate.network = '1';
  5345. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  5346. return candidate;
  5347. },
  5348. build_icecandidate: function (cand) {
  5349. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  5350. line += ' ';
  5351. switch (cand.type) {
  5352. case 'srflx':
  5353. case 'prflx':
  5354. case 'relay':
  5355. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  5356. line += 'raddr';
  5357. line += ' ';
  5358. line += cand['rel-addr'];
  5359. line += ' ';
  5360. line += 'rport';
  5361. line += ' ';
  5362. line += cand['rel-port'];
  5363. line += ' ';
  5364. }
  5365. break;
  5366. }
  5367. if (cand.hasOwnAttribute('tcptype')) {
  5368. line += 'tcptype';
  5369. line += ' ';
  5370. line += cand.tcptype;
  5371. line += ' ';
  5372. }
  5373. line += 'generation';
  5374. line += ' ';
  5375. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  5376. return line;
  5377. },
  5378. parse_ssrc: function (desc) {
  5379. // proprietary mapping of a=ssrc lines
  5380. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  5381. // and parse according to that
  5382. var lines = desc.split('\r\n'),
  5383. data = {};
  5384. for (var i = 0; i < lines.length; i++) {
  5385. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  5386. var idx = lines[i].indexOf(' ');
  5387. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  5388. }
  5389. }
  5390. return data;
  5391. },
  5392. parse_rtcpfb: function (line) {
  5393. var parts = line.substr(10).split(' ');
  5394. var data = {};
  5395. data.pt = parts.shift();
  5396. data.type = parts.shift();
  5397. data.params = parts;
  5398. return data;
  5399. },
  5400. parse_extmap: function (line) {
  5401. var parts = line.substr(9).split(' ');
  5402. var data = {};
  5403. data.value = parts.shift();
  5404. if (data.value.indexOf('/') != -1) {
  5405. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  5406. data.value = data.value.substr(0, data.value.indexOf('/'));
  5407. } else {
  5408. data.direction = 'both';
  5409. }
  5410. data.uri = parts.shift();
  5411. data.params = parts;
  5412. return data;
  5413. },
  5414. find_line: function (haystack, needle, sessionpart) {
  5415. var lines = haystack.split('\r\n');
  5416. for (var i = 0; i < lines.length; i++) {
  5417. if (lines[i].substring(0, needle.length) == needle) {
  5418. return lines[i];
  5419. }
  5420. }
  5421. if (!sessionpart) {
  5422. return false;
  5423. }
  5424. // search session part
  5425. lines = sessionpart.split('\r\n');
  5426. for (var j = 0; j < lines.length; j++) {
  5427. if (lines[j].substring(0, needle.length) == needle) {
  5428. return lines[j];
  5429. }
  5430. }
  5431. return false;
  5432. },
  5433. find_lines: function (haystack, needle, sessionpart) {
  5434. var lines = haystack.split('\r\n'),
  5435. needles = [];
  5436. for (var i = 0; i < lines.length; i++) {
  5437. if (lines[i].substring(0, needle.length) == needle)
  5438. needles.push(lines[i]);
  5439. }
  5440. if (needles.length || !sessionpart) {
  5441. return needles;
  5442. }
  5443. // search session part
  5444. lines = sessionpart.split('\r\n');
  5445. for (var j = 0; j < lines.length; j++) {
  5446. if (lines[j].substring(0, needle.length) == needle) {
  5447. needles.push(lines[j]);
  5448. }
  5449. }
  5450. return needles;
  5451. },
  5452. candidateToJingle: function (line) {
  5453. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  5454. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  5455. if (line.indexOf('candidate:') === 0) {
  5456. line = 'a=' + line;
  5457. } else if (line.substring(0, 12) != 'a=candidate:') {
  5458. console.log('parseCandidate called with a line that is not a candidate line');
  5459. console.log(line);
  5460. return null;
  5461. }
  5462. if (line.substring(line.length - 2) == '\r\n') // chomp it
  5463. line = line.substring(0, line.length - 2);
  5464. var candidate = {},
  5465. elems = line.split(' '),
  5466. i;
  5467. if (elems[6] != 'typ') {
  5468. console.log('did not find typ in the right place');
  5469. console.log(line);
  5470. return null;
  5471. }
  5472. candidate.foundation = elems[0].substring(12);
  5473. candidate.component = elems[1];
  5474. candidate.protocol = elems[2].toLowerCase();
  5475. candidate.priority = elems[3];
  5476. candidate.ip = elems[4];
  5477. candidate.port = elems[5];
  5478. // elems[6] => "typ"
  5479. candidate.type = elems[7];
  5480. candidate.generation = '0'; // default, may be overwritten below
  5481. for (i = 8; i < elems.length; i += 2) {
  5482. switch (elems[i]) {
  5483. case 'raddr':
  5484. candidate['rel-addr'] = elems[i + 1];
  5485. break;
  5486. case 'rport':
  5487. candidate['rel-port'] = elems[i + 1];
  5488. break;
  5489. case 'generation':
  5490. candidate.generation = elems[i + 1];
  5491. break;
  5492. case 'tcptype':
  5493. candidate.tcptype = elems[i + 1];
  5494. break;
  5495. default: // TODO
  5496. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  5497. }
  5498. }
  5499. candidate.network = '1';
  5500. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  5501. return candidate;
  5502. },
  5503. candidateFromJingle: function (cand) {
  5504. var line = 'a=candidate:';
  5505. line += cand.getAttribute('foundation');
  5506. line += ' ';
  5507. line += cand.getAttribute('component');
  5508. line += ' ';
  5509. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  5510. line += ' ';
  5511. line += cand.getAttribute('priority');
  5512. line += ' ';
  5513. line += cand.getAttribute('ip');
  5514. line += ' ';
  5515. line += cand.getAttribute('port');
  5516. line += ' ';
  5517. line += 'typ';
  5518. line += ' ' + cand.getAttribute('type');
  5519. line += ' ';
  5520. switch (cand.getAttribute('type')) {
  5521. case 'srflx':
  5522. case 'prflx':
  5523. case 'relay':
  5524. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  5525. line += 'raddr';
  5526. line += ' ';
  5527. line += cand.getAttribute('rel-addr');
  5528. line += ' ';
  5529. line += 'rport';
  5530. line += ' ';
  5531. line += cand.getAttribute('rel-port');
  5532. line += ' ';
  5533. }
  5534. break;
  5535. }
  5536. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  5537. line += 'tcptype';
  5538. line += ' ';
  5539. line += cand.getAttribute('tcptype');
  5540. line += ' ';
  5541. }
  5542. line += 'generation';
  5543. line += ' ';
  5544. line += cand.getAttribute('generation') || '0';
  5545. return line + '\r\n';
  5546. }
  5547. };
  5548. module.exports = SDPUtil;
  5549. },{}],22:[function(require,module,exports){
  5550. var RTC = require('../RTC/RTC');
  5551. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  5552. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5553. var SSRCReplacement = require("./LocalSSRCReplacement");
  5554. function TraceablePeerConnection(ice_config, constraints, session) {
  5555. var self = this;
  5556. var RTCPeerConnectionType = null;
  5557. if (RTCBrowserType.isFirefox()) {
  5558. RTCPeerConnectionType = mozRTCPeerConnection;
  5559. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  5560. RTCPeerConnectionType = RTCPeerConnection;
  5561. } else {
  5562. RTCPeerConnectionType = webkitRTCPeerConnection;
  5563. }
  5564. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  5565. this.updateLog = [];
  5566. this.stats = {};
  5567. this.statsinterval = null;
  5568. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  5569. var Interop = require('sdp-interop').Interop;
  5570. this.interop = new Interop();
  5571. var Simulcast = require('sdp-simulcast');
  5572. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  5573. // override as desired
  5574. this.trace = function (what, info) {
  5575. /*console.warn('WTRACE', what, info);
  5576. if (info && RTCBrowserType.isIExplorer()) {
  5577. if (info.length > 1024) {
  5578. console.warn('WTRACE', what, info.substr(1024));
  5579. }
  5580. if (info.length > 2048) {
  5581. console.warn('WTRACE', what, info.substr(2048));
  5582. }
  5583. }*/
  5584. self.updateLog.push({
  5585. time: new Date(),
  5586. type: what,
  5587. value: info || ""
  5588. });
  5589. };
  5590. this.onicecandidate = null;
  5591. this.peerconnection.onicecandidate = function (event) {
  5592. // FIXME: this causes stack overflow with Temasys Plugin
  5593. if (!RTCBrowserType.isTemasysPluginUsed())
  5594. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  5595. if (self.onicecandidate !== null) {
  5596. self.onicecandidate(event);
  5597. }
  5598. };
  5599. this.onaddstream = null;
  5600. this.peerconnection.onaddstream = function (event) {
  5601. self.trace('onaddstream', event.stream.id);
  5602. if (self.onaddstream !== null) {
  5603. self.onaddstream(event);
  5604. }
  5605. };
  5606. this.onremovestream = null;
  5607. this.peerconnection.onremovestream = function (event) {
  5608. self.trace('onremovestream', event.stream.id);
  5609. if (self.onremovestream !== null) {
  5610. self.onremovestream(event);
  5611. }
  5612. };
  5613. this.onsignalingstatechange = null;
  5614. this.peerconnection.onsignalingstatechange = function (event) {
  5615. self.trace('onsignalingstatechange', self.signalingState);
  5616. if (self.onsignalingstatechange !== null) {
  5617. self.onsignalingstatechange(event);
  5618. }
  5619. };
  5620. this.oniceconnectionstatechange = null;
  5621. this.peerconnection.oniceconnectionstatechange = function (event) {
  5622. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  5623. if (self.oniceconnectionstatechange !== null) {
  5624. self.oniceconnectionstatechange(event);
  5625. }
  5626. };
  5627. this.onnegotiationneeded = null;
  5628. this.peerconnection.onnegotiationneeded = function (event) {
  5629. self.trace('onnegotiationneeded');
  5630. if (self.onnegotiationneeded !== null) {
  5631. self.onnegotiationneeded(event);
  5632. }
  5633. };
  5634. self.ondatachannel = null;
  5635. this.peerconnection.ondatachannel = function (event) {
  5636. self.trace('ondatachannel', event);
  5637. if (self.ondatachannel !== null) {
  5638. self.ondatachannel(event);
  5639. }
  5640. };
  5641. // XXX: do all non-firefox browsers which we support also support this?
  5642. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  5643. this.statsinterval = window.setInterval(function() {
  5644. self.peerconnection.getStats(function(stats) {
  5645. var results = stats.result();
  5646. var now = new Date();
  5647. for (var i = 0; i < results.length; ++i) {
  5648. results[i].names().forEach(function (name) {
  5649. var id = results[i].id + '-' + name;
  5650. if (!self.stats[id]) {
  5651. self.stats[id] = {
  5652. startTime: now,
  5653. endTime: now,
  5654. values: [],
  5655. times: []
  5656. };
  5657. }
  5658. self.stats[id].values.push(results[i].stat(name));
  5659. self.stats[id].times.push(now.getTime());
  5660. if (self.stats[id].values.length > self.maxstats) {
  5661. self.stats[id].values.shift();
  5662. self.stats[id].times.shift();
  5663. }
  5664. self.stats[id].endTime = now;
  5665. });
  5666. }
  5667. });
  5668. }, 1000);
  5669. }
  5670. }
  5671. /**
  5672. * Returns a string representation of a SessionDescription object.
  5673. */
  5674. var dumpSDP = function(description) {
  5675. if (typeof description === 'undefined' || description == null) {
  5676. return '';
  5677. }
  5678. return 'type: ' + description.type + '\r\n' + description.sdp;
  5679. };
  5680. /**
  5681. * Takes a SessionDescription object and returns a "normalized" version.
  5682. * Currently it only takes care of ordering the a=ssrc lines.
  5683. */
  5684. var normalizePlanB = function(desc) {
  5685. if (typeof desc !== 'object' || desc === null ||
  5686. typeof desc.sdp !== 'string') {
  5687. console.warn('An empty description was passed as an argument.');
  5688. return desc;
  5689. }
  5690. var transform = require('sdp-transform');
  5691. var session = transform.parse(desc.sdp);
  5692. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  5693. Array.isArray(session.media)) {
  5694. session.media.forEach(function (mLine) {
  5695. // Chrome appears to be picky about the order in which a=ssrc lines
  5696. // are listed in an m-line when rtx is enabled (and thus there are
  5697. // a=ssrc-group lines with FID semantics). Specifically if we have
  5698. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  5699. // the "a=ssrc:S1" lines, SRD fails.
  5700. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  5701. // first.
  5702. var firstSsrcs = [];
  5703. var newSsrcLines = [];
  5704. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  5705. mLine.ssrcGroups.forEach(function (group) {
  5706. if (typeof group.semantics !== 'undefined' &&
  5707. group.semantics === 'FID') {
  5708. if (typeof group.ssrcs !== 'undefined') {
  5709. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  5710. }
  5711. }
  5712. });
  5713. }
  5714. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  5715. for (var i = 0; i<mLine.ssrcs.length; i++){
  5716. if (typeof mLine.ssrcs[i] === 'object'
  5717. && typeof mLine.ssrcs[i].id !== 'undefined'
  5718. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  5719. newSsrcLines.push(mLine.ssrcs[i]);
  5720. delete mLine.ssrcs[i];
  5721. }
  5722. }
  5723. for (var i = 0; i<mLine.ssrcs.length; i++){
  5724. if (typeof mLine.ssrcs[i] !== 'undefined') {
  5725. newSsrcLines.push(mLine.ssrcs[i]);
  5726. }
  5727. }
  5728. mLine.ssrcs = newSsrcLines;
  5729. }
  5730. });
  5731. }
  5732. var resStr = transform.write(session);
  5733. return new RTCSessionDescription({
  5734. type: desc.type,
  5735. sdp: resStr
  5736. });
  5737. };
  5738. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  5739. TraceablePeerConnection.prototype.__defineGetter__(
  5740. 'signalingState',
  5741. function() { return this.peerconnection.signalingState; });
  5742. TraceablePeerConnection.prototype.__defineGetter__(
  5743. 'iceConnectionState',
  5744. function() { return this.peerconnection.iceConnectionState; });
  5745. TraceablePeerConnection.prototype.__defineGetter__(
  5746. 'localDescription',
  5747. function() {
  5748. var desc = this.peerconnection.localDescription;
  5749. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  5750. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  5751. // if we're running on FF, transform to Plan B first.
  5752. if (RTCBrowserType.usesUnifiedPlan()) {
  5753. desc = this.interop.toPlanB(desc);
  5754. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  5755. }
  5756. return desc;
  5757. });
  5758. TraceablePeerConnection.prototype.__defineGetter__(
  5759. 'remoteDescription',
  5760. function() {
  5761. var desc = this.peerconnection.remoteDescription;
  5762. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  5763. // if we're running on FF, transform to Plan B first.
  5764. if (RTCBrowserType.usesUnifiedPlan()) {
  5765. desc = this.interop.toPlanB(desc);
  5766. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  5767. }
  5768. return desc;
  5769. });
  5770. }
  5771. TraceablePeerConnection.prototype.addStream = function (stream) {
  5772. this.trace('addStream', stream.id);
  5773. try
  5774. {
  5775. this.peerconnection.addStream(stream);
  5776. }
  5777. catch (e)
  5778. {
  5779. console.error(e);
  5780. }
  5781. };
  5782. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  5783. this.trace('removeStream', stream.id);
  5784. if(stopStreams) {
  5785. stream.getAudioTracks().forEach(function (track) {
  5786. // stop() not supported with IE
  5787. if (track.stop) {
  5788. track.stop();
  5789. }
  5790. });
  5791. stream.getVideoTracks().forEach(function (track) {
  5792. // stop() not supported with IE
  5793. if (track.stop) {
  5794. track.stop();
  5795. }
  5796. });
  5797. if (stream.stop) {
  5798. stream.stop();
  5799. }
  5800. }
  5801. try {
  5802. // FF doesn't support this yet.
  5803. if (this.peerconnection.removeStream)
  5804. this.peerconnection.removeStream(stream);
  5805. } catch (e) {
  5806. console.error(e);
  5807. }
  5808. };
  5809. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  5810. this.trace('createDataChannel', label, opts);
  5811. return this.peerconnection.createDataChannel(label, opts);
  5812. };
  5813. TraceablePeerConnection.prototype.setLocalDescription
  5814. = function (description, successCallback, failureCallback) {
  5815. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  5816. // if we're running on FF, transform to Plan A first.
  5817. if (RTCBrowserType.usesUnifiedPlan()) {
  5818. description = this.interop.toUnifiedPlan(description);
  5819. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  5820. }
  5821. var self = this;
  5822. this.peerconnection.setLocalDescription(description,
  5823. function () {
  5824. self.trace('setLocalDescriptionOnSuccess');
  5825. successCallback();
  5826. },
  5827. function (err) {
  5828. self.trace('setLocalDescriptionOnFailure', err);
  5829. failureCallback(err);
  5830. }
  5831. );
  5832. /*
  5833. if (this.statsinterval === null && this.maxstats > 0) {
  5834. // start gathering stats
  5835. }
  5836. */
  5837. };
  5838. TraceablePeerConnection.prototype.setRemoteDescription
  5839. = function (description, successCallback, failureCallback) {
  5840. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  5841. // TODO the focus should squeze or explode the remote simulcast
  5842. description = this.simulcast.mungeRemoteDescription(description);
  5843. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  5844. // if we're running on FF, transform to Plan A first.
  5845. if (RTCBrowserType.usesUnifiedPlan()) {
  5846. description = this.interop.toUnifiedPlan(description);
  5847. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  5848. }
  5849. if (RTCBrowserType.usesPlanB()) {
  5850. description = normalizePlanB(description);
  5851. }
  5852. var self = this;
  5853. this.peerconnection.setRemoteDescription(description,
  5854. function () {
  5855. self.trace('setRemoteDescriptionOnSuccess');
  5856. successCallback();
  5857. },
  5858. function (err) {
  5859. self.trace('setRemoteDescriptionOnFailure', err);
  5860. failureCallback(err);
  5861. }
  5862. );
  5863. /*
  5864. if (this.statsinterval === null && this.maxstats > 0) {
  5865. // start gathering stats
  5866. }
  5867. */
  5868. };
  5869. TraceablePeerConnection.prototype.close = function () {
  5870. this.trace('stop');
  5871. if (this.statsinterval !== null) {
  5872. window.clearInterval(this.statsinterval);
  5873. this.statsinterval = null;
  5874. }
  5875. this.peerconnection.close();
  5876. };
  5877. TraceablePeerConnection.prototype.createOffer
  5878. = function (successCallback, failureCallback, constraints) {
  5879. var self = this;
  5880. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  5881. this.peerconnection.createOffer(
  5882. function (offer) {
  5883. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  5884. // NOTE this is not tested because in meet the focus generates the
  5885. // offer.
  5886. // if we're running on FF, transform to Plan B first.
  5887. if (RTCBrowserType.usesUnifiedPlan()) {
  5888. offer = self.interop.toPlanB(offer);
  5889. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  5890. }
  5891. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  5892. if (config.enableSimulcast && self.simulcast.isSupported()) {
  5893. offer = self.simulcast.mungeLocalDescription(offer);
  5894. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  5895. }
  5896. successCallback(offer);
  5897. },
  5898. function(err) {
  5899. self.trace('createOfferOnFailure', err);
  5900. failureCallback(err);
  5901. },
  5902. constraints
  5903. );
  5904. };
  5905. TraceablePeerConnection.prototype.createAnswer
  5906. = function (successCallback, failureCallback, constraints) {
  5907. var self = this;
  5908. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  5909. this.peerconnection.createAnswer(
  5910. function (answer) {
  5911. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  5912. // if we're running on FF, transform to Plan A first.
  5913. if (RTCBrowserType.usesUnifiedPlan()) {
  5914. answer = self.interop.toPlanB(answer);
  5915. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  5916. }
  5917. // munge local video SSRC
  5918. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  5919. if (config.enableSimulcast && self.simulcast.isSupported()) {
  5920. answer = self.simulcast.mungeLocalDescription(answer);
  5921. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  5922. }
  5923. successCallback(answer);
  5924. },
  5925. function(err) {
  5926. self.trace('createAnswerOnFailure', err);
  5927. failureCallback(err);
  5928. },
  5929. constraints
  5930. );
  5931. };
  5932. TraceablePeerConnection.prototype.addIceCandidate
  5933. = function (candidate, successCallback, failureCallback) {
  5934. //var self = this;
  5935. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  5936. this.peerconnection.addIceCandidate(candidate);
  5937. /* maybe later
  5938. this.peerconnection.addIceCandidate(candidate,
  5939. function () {
  5940. self.trace('addIceCandidateOnSuccess');
  5941. successCallback();
  5942. },
  5943. function (err) {
  5944. self.trace('addIceCandidateOnFailure', err);
  5945. failureCallback(err);
  5946. }
  5947. );
  5948. */
  5949. };
  5950. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  5951. // TODO: Is this the correct way to handle Opera, Temasys?
  5952. if (RTCBrowserType.isFirefox()) {
  5953. // ignore for now...
  5954. if(!errback)
  5955. errback = function () {};
  5956. this.peerconnection.getStats(null, callback, errback);
  5957. } else {
  5958. this.peerconnection.getStats(callback);
  5959. }
  5960. };
  5961. module.exports = TraceablePeerConnection;
  5962. },{"../../service/xmpp/XMPPEvents":73,"../RTC/RTC":11,"../RTC/RTCBrowserType.js":12,"./LocalSSRCReplacement":18,"sdp-interop":49,"sdp-simulcast":56,"sdp-transform":63}],23:[function(require,module,exports){
  5963. /* global $, $iq, APP, config, messageHandler,
  5964. roomName, sessionTerminated, Strophe, Util */
  5965. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5966. var Settings = require("../settings/Settings");
  5967. var AuthenticationEvents
  5968. = require("../../service/authentication/AuthenticationEvents");
  5969. function createExpBackoffTimer(step) {
  5970. var count = 1;
  5971. return function (reset) {
  5972. // Reset call
  5973. if (reset) {
  5974. count = 1;
  5975. return;
  5976. }
  5977. // Calculate next timeout
  5978. var timeout = Math.pow(2, count - 1);
  5979. count += 1;
  5980. return timeout * step;
  5981. };
  5982. }
  5983. function Moderator(roomName, xmpp, emitter) {
  5984. this.roomName = roomName;
  5985. this.xmppService = xmpp;
  5986. this.getNextTimeout = createExpBackoffTimer(1000);
  5987. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  5988. // External authentication stuff
  5989. this.externalAuthEnabled = false;
  5990. this.settings = new Settings(roomName);
  5991. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  5992. // it will be enabled automatically if focus detects the component through
  5993. // service discovery.
  5994. this.sipGatewayEnabled = this.xmppService.options.hosts.call_control !== undefined;
  5995. this.eventEmitter = emitter;
  5996. this.connection = this.xmppService.connection;
  5997. this.focusUserJid;
  5998. //FIXME:
  5999. // Message listener that talks to POPUP window
  6000. function listener(event) {
  6001. if (event.data && event.data.sessionId) {
  6002. if (event.origin !== window.location.origin) {
  6003. console.warn("Ignoring sessionId from different origin: " +
  6004. event.origin);
  6005. return;
  6006. }
  6007. localStorage.setItem('sessionId', event.data.sessionId);
  6008. // After popup is closed we will authenticate
  6009. }
  6010. }
  6011. // Register
  6012. if (window.addEventListener) {
  6013. window.addEventListener("message", listener, false);
  6014. } else {
  6015. window.attachEvent("onmessage", listener);
  6016. }
  6017. }
  6018. Moderator.prototype.isExternalAuthEnabled = function () {
  6019. return this.externalAuthEnabled;
  6020. };
  6021. Moderator.prototype.isSipGatewayEnabled = function () {
  6022. return this.sipGatewayEnabled;
  6023. };
  6024. Moderator.prototype.onMucMemberLeft = function (jid) {
  6025. console.info("Someone left is it focus ? " + jid);
  6026. var resource = Strophe.getResourceFromJid(jid);
  6027. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  6028. console.info(
  6029. "Focus has left the room - leaving conference");
  6030. //hangUp();
  6031. // We'd rather reload to have everything re-initialized
  6032. //FIXME: show some message before reload
  6033. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  6034. }
  6035. };
  6036. Moderator.prototype.setFocusUserJid = function (focusJid) {
  6037. if (!this.focusUserJid) {
  6038. this.focusUserJid = focusJid;
  6039. console.info("Focus jid set to: " + this.focusUserJid);
  6040. }
  6041. };
  6042. Moderator.prototype.getFocusUserJid = function () {
  6043. return this.focusUserJid;
  6044. };
  6045. Moderator.prototype.getFocusComponent = function () {
  6046. // Get focus component address
  6047. var focusComponent = this.xmppService.options.hosts.focus;
  6048. // If not specified use default: 'focus.domain'
  6049. if (!focusComponent) {
  6050. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  6051. }
  6052. return focusComponent;
  6053. };
  6054. Moderator.prototype.createConferenceIq = function () {
  6055. // Generate create conference IQ
  6056. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  6057. // Session Id used for authentication
  6058. var sessionId = localStorage.getItem('sessionId');
  6059. var machineUID = this.settings.getSettings().uid;
  6060. console.info(
  6061. "Session ID: " + sessionId + " machine UID: " + machineUID);
  6062. elem.c('conference', {
  6063. xmlns: 'http://jitsi.org/protocol/focus',
  6064. room: this.roomName,
  6065. 'machine-uid': machineUID
  6066. });
  6067. if (sessionId) {
  6068. elem.attrs({ 'session-id': sessionId});
  6069. }
  6070. if (this.xmppService.options.hosts.bridge !== undefined) {
  6071. elem.c(
  6072. 'property',
  6073. {name: 'bridge',value: this.xmppService.options.hosts.bridge})
  6074. .up();
  6075. }
  6076. // Tell the focus we have Jigasi configured
  6077. if (this.xmppService.options.hosts.call_control !== undefined) {
  6078. elem.c(
  6079. 'property',
  6080. {name: 'call_control',value: this.xmppService.options.hosts.call_control})
  6081. .up();
  6082. }
  6083. if (this.xmppService.options.channelLastN !== undefined) {
  6084. elem.c(
  6085. 'property',
  6086. {name: 'channelLastN',value: this.xmppService.options.channelLastN})
  6087. .up();
  6088. }
  6089. if (this.xmppService.options.adaptiveLastN !== undefined) {
  6090. elem.c(
  6091. 'property',
  6092. {name: 'adaptiveLastN',value: this.xmppService.options.adaptiveLastN})
  6093. .up();
  6094. }
  6095. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  6096. elem.c(
  6097. 'property',
  6098. {name: 'adaptiveSimulcast',value: this.xmppService.options.adaptiveSimulcast})
  6099. .up();
  6100. }
  6101. if (this.xmppService.options.openSctp !== undefined) {
  6102. elem.c(
  6103. 'property',
  6104. {name: 'openSctp',value: this.xmppService.options.openSctp})
  6105. .up();
  6106. }
  6107. if(this.xmppService.options.startAudioMuted !== undefined)
  6108. {
  6109. elem.c(
  6110. 'property',
  6111. {name: 'startAudioMuted',value: this.xmppService.options.startAudioMuted})
  6112. .up();
  6113. }
  6114. if(this.xmppService.options.startVideoMuted !== undefined)
  6115. {
  6116. elem.c(
  6117. 'property',
  6118. {name: 'startVideoMuted',value: this.xmppService.options.startVideoMuted})
  6119. .up();
  6120. }
  6121. elem.c(
  6122. 'property',
  6123. {name: 'simulcastMode',value: 'rewriting'})
  6124. .up();
  6125. elem.up();
  6126. return elem;
  6127. };
  6128. Moderator.prototype.parseSessionId = function (resultIq) {
  6129. var sessionId = $(resultIq).find('conference').attr('session-id');
  6130. if (sessionId) {
  6131. console.info('Received sessionId: ' + sessionId);
  6132. localStorage.setItem('sessionId', sessionId);
  6133. }
  6134. };
  6135. Moderator.prototype.parseConfigOptions = function (resultIq) {
  6136. this.setFocusUserJid(
  6137. $(resultIq).find('conference').attr('focusjid'));
  6138. var authenticationEnabled
  6139. = $(resultIq).find(
  6140. '>conference>property' +
  6141. '[name=\'authentication\'][value=\'true\']').length > 0;
  6142. console.info("Authentication enabled: " + authenticationEnabled);
  6143. this.externalAuthEnabled = $(resultIq).find(
  6144. '>conference>property' +
  6145. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  6146. console.info('External authentication enabled: ' + this.externalAuthEnabled);
  6147. if (!this.externalAuthEnabled) {
  6148. // We expect to receive sessionId in 'internal' authentication mode
  6149. this.parseSessionId(resultIq);
  6150. }
  6151. var authIdentity = $(resultIq).find('>conference').attr('identity');
  6152. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  6153. authenticationEnabled, authIdentity);
  6154. // Check if focus has auto-detected Jigasi component(this will be also
  6155. // included if we have passed our host from the config)
  6156. if ($(resultIq).find(
  6157. '>conference>property' +
  6158. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  6159. this.sipGatewayEnabled = true;
  6160. }
  6161. console.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  6162. };
  6163. // FIXME = we need to show the fact that we're waiting for the focus
  6164. // to the user(or that focus is not available)
  6165. Moderator.prototype.allocateConferenceFocus = function ( callback) {
  6166. // Try to use focus user JID from the config
  6167. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  6168. // Send create conference IQ
  6169. var iq = this.createConferenceIq();
  6170. var self = this;
  6171. this.connection.sendIQ(
  6172. iq,
  6173. function (result) {
  6174. // Setup config options
  6175. self.parseConfigOptions(result);
  6176. if ('true' === $(result).find('conference').attr('ready')) {
  6177. // Reset both timers
  6178. self.getNextTimeout(true);
  6179. self.getNextErrorTimeout(true);
  6180. // Exec callback
  6181. callback();
  6182. } else {
  6183. var waitMs = self.getNextTimeout();
  6184. console.info("Waiting for the focus... " + waitMs);
  6185. // Reset error timeout
  6186. self.getNextErrorTimeout(true);
  6187. window.setTimeout(
  6188. function () {
  6189. self.allocateConferenceFocus(callback);
  6190. }, waitMs);
  6191. }
  6192. },
  6193. function (error) {
  6194. // Invalid session ? remove and try again
  6195. // without session ID to get a new one
  6196. var invalidSession
  6197. = $(error).find('>error>session-invalid').length;
  6198. if (invalidSession) {
  6199. console.info("Session expired! - removing");
  6200. localStorage.removeItem("sessionId");
  6201. }
  6202. if ($(error).find('>error>graceful-shutdown').length) {
  6203. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  6204. return;
  6205. }
  6206. // Check for error returned by the reservation system
  6207. var reservationErr = $(error).find('>error>reservation-error');
  6208. if (reservationErr.length) {
  6209. // Trigger error event
  6210. var errorCode = reservationErr.attr('error-code');
  6211. var errorMsg;
  6212. if ($(error).find('>error>text')) {
  6213. errorMsg = $(error).find('>error>text').text();
  6214. }
  6215. self.eventEmitter.emit(
  6216. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  6217. return;
  6218. }
  6219. // Not authorized to create new room
  6220. if ($(error).find('>error>not-authorized').length) {
  6221. console.warn("Unauthorized to start the conference", error);
  6222. var toDomain
  6223. = Strophe.getDomainFromJid(error.getAttribute('to'));
  6224. if (toDomain !== this.xmppService.options.hosts.anonymousdomain) {
  6225. //FIXME: "is external" should come either from
  6226. // the focus or config.js
  6227. self.externalAuthEnabled = true;
  6228. }
  6229. self.eventEmitter.emit(
  6230. XMPPEvents.AUTHENTICATION_REQUIRED,
  6231. function () {
  6232. self.allocateConferenceFocus(
  6233. callback);
  6234. });
  6235. return;
  6236. }
  6237. var waitMs = self.getNextErrorTimeout();
  6238. console.error("Focus error, retry after " + waitMs, error);
  6239. // Show message
  6240. var focusComponent = self.getFocusComponent();
  6241. var retrySec = waitMs / 1000;
  6242. //FIXME: message is duplicated ?
  6243. // Do not show in case of session invalid
  6244. // which means just a retry
  6245. if (!invalidSession) {
  6246. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  6247. focusComponent, retrySec);
  6248. }
  6249. // Reset response timeout
  6250. self.getNextTimeout(true);
  6251. window.setTimeout(
  6252. function () {
  6253. self.allocateConferenceFocus(callback);
  6254. }, waitMs);
  6255. }
  6256. );
  6257. };
  6258. Moderator.prototype.getLoginUrl = function (urlCallback) {
  6259. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  6260. iq.c('login-url', {
  6261. xmlns: 'http://jitsi.org/protocol/focus',
  6262. room: this.roomName,
  6263. 'machine-uid': this.settings.getSettings().uid
  6264. });
  6265. this.connection.sendIQ(
  6266. iq,
  6267. function (result) {
  6268. var url = $(result).find('login-url').attr('url');
  6269. url = url = decodeURIComponent(url);
  6270. if (url) {
  6271. console.info("Got auth url: " + url);
  6272. urlCallback(url);
  6273. } else {
  6274. console.error(
  6275. "Failed to get auth url from the focus", result);
  6276. }
  6277. },
  6278. function (error) {
  6279. console.error("Get auth url error", error);
  6280. }
  6281. );
  6282. };
  6283. Moderator.prototype.getPopupLoginUrl = function (urlCallback) {
  6284. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  6285. iq.c('login-url', {
  6286. xmlns: 'http://jitsi.org/protocol/focus',
  6287. room: this.roomName,
  6288. 'machine-uid': this.settings.getSettings().uid,
  6289. popup: true
  6290. });
  6291. this.connection.sendIQ(
  6292. iq,
  6293. function (result) {
  6294. var url = $(result).find('login-url').attr('url');
  6295. url = url = decodeURIComponent(url);
  6296. if (url) {
  6297. console.info("Got POPUP auth url: " + url);
  6298. urlCallback(url);
  6299. } else {
  6300. console.error(
  6301. "Failed to get POPUP auth url from the focus", result);
  6302. }
  6303. },
  6304. function (error) {
  6305. console.error('Get POPUP auth url error', error);
  6306. }
  6307. );
  6308. };
  6309. Moderator.prototype.logout = function (callback) {
  6310. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  6311. var sessionId = localStorage.getItem('sessionId');
  6312. if (!sessionId) {
  6313. callback();
  6314. return;
  6315. }
  6316. iq.c('logout', {
  6317. xmlns: 'http://jitsi.org/protocol/focus',
  6318. 'session-id': sessionId
  6319. });
  6320. this.connection.sendIQ(
  6321. iq,
  6322. function (result) {
  6323. var logoutUrl = $(result).find('logout').attr('logout-url');
  6324. if (logoutUrl) {
  6325. logoutUrl = decodeURIComponent(logoutUrl);
  6326. }
  6327. console.info("Log out OK, url: " + logoutUrl, result);
  6328. localStorage.removeItem('sessionId');
  6329. callback(logoutUrl);
  6330. },
  6331. function (error) {
  6332. console.error("Logout error", error);
  6333. }
  6334. );
  6335. };
  6336. module.exports = Moderator;
  6337. },{"../../service/authentication/AuthenticationEvents":71,"../../service/xmpp/XMPPEvents":73,"../settings/Settings":15}],24:[function(require,module,exports){
  6338. /* jshint -W117 */
  6339. /* a simple MUC connection plugin
  6340. * can only handle a single MUC room
  6341. */
  6342. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6343. var Moderator = require("./moderator");
  6344. var RTC = require("../RTC/RTC");
  6345. var parser = {
  6346. packet2JSON: function (packet, nodes) {
  6347. var self = this;
  6348. $(packet).children().each(function (index) {
  6349. var tagName = $(this).prop("tagName");
  6350. var node = {}
  6351. node["tagName"] = tagName;
  6352. node.attributes = {};
  6353. $($(this)[0].attributes).each(function( index, attr ) {
  6354. node.attributes[ attr.name ] = attr.value;
  6355. } );
  6356. var text = Strophe.getText($(this)[0]);
  6357. if(text)
  6358. node.value = text;
  6359. node.children = [];
  6360. nodes.push(node);
  6361. self.packet2JSON($(this), node.children);
  6362. })
  6363. },
  6364. JSON2packet: function (nodes, packet) {
  6365. for(var i = 0; i < nodes.length; i++)
  6366. {
  6367. var node = nodes[i];
  6368. if(!node || node === null){
  6369. continue;
  6370. }
  6371. packet.c(node.tagName, node.attributes);
  6372. if(node.value)
  6373. packet.t(node.value);
  6374. if(node.children)
  6375. this.JSON2packet(node.children, packet);
  6376. packet.up();
  6377. }
  6378. packet.up();
  6379. }
  6380. };
  6381. function ChatRoom(connection, jid, password, XMPP, eventEmitter)
  6382. {
  6383. this.eventEmitter = eventEmitter;
  6384. this.xmpp = XMPP;
  6385. this.connection = connection;
  6386. this.roomjid = Strophe.getBareJidFromJid(jid);
  6387. this.myroomjid = jid;
  6388. this.password = password;
  6389. console.info("Joined MUC as " + this.myroomjid);
  6390. this.members = {};
  6391. this.presMap = {};
  6392. this.joined = false;
  6393. this.role = null;
  6394. this.focusMucJid = null;
  6395. this.bridgeIsDown = false;
  6396. this.moderator = new Moderator(this.roomjid, this.xmpp, eventEmitter);
  6397. this.initPresenceMap();
  6398. }
  6399. ChatRoom.prototype.initPresenceMap = function () {
  6400. this.presMap['to'] = this.myroomjid;
  6401. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  6402. this.presMap["nodes"] = [];
  6403. if (RTC.localAudio && RTC.localAudio.isMuted()) {
  6404. this.nodes.push({
  6405. tagName: "audiomuted",
  6406. attributes: {xmlns: "http://jitsi.org/jitmeet/audio"},
  6407. value: "true"});
  6408. }
  6409. if (RTC.localVideo && RTC.localVideo.isMuted()) {
  6410. this.nodes.push({
  6411. tagName: "videomuted",
  6412. attributes: {xmlns: "http://jitsi.org/jitmeet/video"},
  6413. value: "true"});
  6414. }
  6415. this.presMap["nodes"].push( {
  6416. "tagName": "user-agent",
  6417. "value": navigator.userAgent,
  6418. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  6419. });
  6420. };
  6421. ChatRoom.prototype.join = function () {
  6422. this.moderator.allocateConferenceFocus(this.sendPresence.bind(this));
  6423. }
  6424. ChatRoom.prototype.sendPresence = function () {
  6425. if (!this.presMap['to']) {
  6426. // Too early to send presence - not initialized
  6427. return;
  6428. }
  6429. var pres = $pres({to: this.presMap['to'] });
  6430. pres.c('x', {xmlns: this.presMap['xns']});
  6431. if (this.password) {
  6432. pres.c('password').t(this.password).up();
  6433. }
  6434. pres.up();
  6435. // Send XEP-0115 'c' stanza that contains our capabilities info
  6436. if (this.connection.caps) {
  6437. this.connection.caps.node = this.xmpp.options.clientNode;
  6438. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  6439. }
  6440. parser.JSON2packet(this.presMap.nodes, pres);
  6441. this.connection.send(pres);
  6442. };
  6443. ChatRoom.prototype.doLeave = function () {
  6444. console.log("do leave", this.myroomjid);
  6445. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  6446. this.presMap.length = 0;
  6447. this.connection.send(pres);
  6448. };
  6449. ChatRoom.prototype.createNonAnonymousRoom = function () {
  6450. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  6451. var getForm = $iq({type: 'get', to: this.roomjid})
  6452. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  6453. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6454. var self = this;
  6455. this.connection.sendIQ(getForm, function (form) {
  6456. if (!$(form).find(
  6457. '>query>x[xmlns="jabber:x:data"]' +
  6458. '>field[var="muc#roomconfig_whois"]').length) {
  6459. console.error('non-anonymous rooms not supported');
  6460. return;
  6461. }
  6462. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  6463. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6464. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6465. formSubmit.c('field', {'var': 'FORM_TYPE'})
  6466. .c('value')
  6467. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6468. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  6469. .c('value').t('anyone').up().up();
  6470. self.connection.sendIQ(formSubmit);
  6471. }, function (error) {
  6472. console.error("Error getting room configuration form");
  6473. });
  6474. };
  6475. ChatRoom.prototype.onPresence = function (pres) {
  6476. var from = pres.getAttribute('from');
  6477. // Parse roles.
  6478. var member = {};
  6479. member.show = $(pres).find('>show').text();
  6480. member.status = $(pres).find('>status').text();
  6481. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  6482. member.affiliation = tmp.attr('affiliation');
  6483. member.role = tmp.attr('role');
  6484. // Focus recognition
  6485. member.jid = tmp.attr('jid');
  6486. member.isFocus = false;
  6487. if (member.jid
  6488. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") == 0) {
  6489. member.isFocus = true;
  6490. }
  6491. $(pres).find(">x").remove();
  6492. var nodes = [];
  6493. parser.packet2JSON(pres, nodes);
  6494. for(var i = 0; i < nodes.length; i++)
  6495. {
  6496. var node = nodes[i];
  6497. switch(node.tagName)
  6498. {
  6499. case "nick":
  6500. member.nick = node.value;
  6501. if(!member.isFocus) {
  6502. var displayName = !this.xmpp.options.displayJids
  6503. ? member.nick : Strophe.getResourceFromJid(from);
  6504. if (displayName && displayName.length > 0) {
  6505. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  6506. }
  6507. console.info("Display name: " + displayName, pres);
  6508. }
  6509. break;
  6510. case "userId":
  6511. member.id = node.value;
  6512. break;
  6513. case "email":
  6514. member.email = node.value;
  6515. break;
  6516. case "bridgeIsDown":
  6517. if(!this.bridgeIsDown) {
  6518. this.bridgeIsDown = true;
  6519. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  6520. }
  6521. break;
  6522. default :
  6523. this.processNode(node);
  6524. }
  6525. }
  6526. if (from == this.myroomjid) {
  6527. if (member.affiliation == 'owner')
  6528. if (this.role !== member.role) {
  6529. this.role = member.role;
  6530. this.eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  6531. member, this.isModerator());
  6532. }
  6533. if (!this.joined) {
  6534. this.joined = true;
  6535. this.eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  6536. }
  6537. } else if (this.members[from] === undefined) {
  6538. // new participant
  6539. this.members[from] = member;
  6540. console.log('entered', from, member);
  6541. if (member.isFocus) {
  6542. this.focusMucJid = from;
  6543. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  6544. }
  6545. else {
  6546. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, member.id || member.email, member.nick);
  6547. }
  6548. } else {
  6549. // Presence update for existing participant
  6550. // Watch role change:
  6551. if (this.members[from].role != member.role) {
  6552. this.members[from].role = member.role;
  6553. this.eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  6554. member.role, member.nick);
  6555. }
  6556. }
  6557. if(!member.isFocus)
  6558. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id || member.email);
  6559. // Trigger status message update
  6560. if (member.status) {
  6561. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  6562. }
  6563. };
  6564. ChatRoom.prototype.processNode = function (node) {
  6565. this.eventEmitter.emit(XMPPEvents.PRESENCE_SETTING, node);
  6566. };
  6567. ChatRoom.prototype.sendMessage = function (body, nickname) {
  6568. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6569. msg.c('body', body).up();
  6570. if (nickname) {
  6571. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  6572. }
  6573. this.connection.send(msg);
  6574. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  6575. };
  6576. ChatRoom.prototype.setSubject = function (subject) {
  6577. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6578. msg.c('subject', subject);
  6579. this.connection.send(msg);
  6580. console.log("topic changed to " + subject);
  6581. };
  6582. ChatRoom.prototype.onParticipantLeft = function (jid) {
  6583. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  6584. this.moderator.onMucMemberLeft(jid);
  6585. };
  6586. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  6587. // room destroyed ?
  6588. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6589. '>destroy').length) {
  6590. var reason;
  6591. var reasonSelect = $(pres).find(
  6592. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6593. '>destroy>reason');
  6594. if (reasonSelect.length) {
  6595. reason = reasonSelect.text();
  6596. }
  6597. this.xmpp.disposeConference(false);
  6598. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  6599. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(jid)];
  6600. return true;
  6601. }
  6602. // Status code 110 indicates that this notification is "self-presence".
  6603. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  6604. delete this.members[from];
  6605. this.onParticipantLeft(from);
  6606. }
  6607. // If the status code is 110 this means we're leaving and we would like
  6608. // to remove everyone else from our view, so we trigger the event.
  6609. else if (Object.keys(this.members).length > 1) {
  6610. for (var i in this.members) {
  6611. var member = this.members[i];
  6612. delete this.members[i];
  6613. this.onParticipantLeft(member);
  6614. }
  6615. }
  6616. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  6617. if (this.myroomjid === from) {
  6618. this.xmpp.disposeConference(false);
  6619. this.eventEmitter.emit(XMPPEvents.KICKED);
  6620. }
  6621. }
  6622. };
  6623. ChatRoom.prototype.onMessage = function (msg, from) {
  6624. var nick =
  6625. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  6626. .text() ||
  6627. Strophe.getResourceFromJid(from);
  6628. var txt = $(msg).find('>body').text();
  6629. var type = msg.getAttribute("type");
  6630. if (type == "error") {
  6631. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  6632. $(msg).find('>text').text(), txt);
  6633. return true;
  6634. }
  6635. var subject = $(msg).find('>subject');
  6636. if (subject.length) {
  6637. var subjectText = subject.text();
  6638. if (subjectText || subjectText == "") {
  6639. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  6640. console.log("Subject is changed to " + subjectText);
  6641. }
  6642. }
  6643. // xep-0203 delay
  6644. var stamp = $(msg).find('>delay').attr('stamp');
  6645. if (!stamp) {
  6646. // or xep-0091 delay, UTC timestamp
  6647. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  6648. if (stamp) {
  6649. // the format is CCYYMMDDThh:mm:ss
  6650. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  6651. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  6652. }
  6653. }
  6654. if (txt) {
  6655. console.log('chat', nick, txt);
  6656. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  6657. from, nick, txt, this.myroomjid, stamp);
  6658. }
  6659. }
  6660. ChatRoom.prototype.onPresenceError = function (pres, from) {
  6661. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  6662. console.log('on password required', from);
  6663. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  6664. } else if ($(pres).find(
  6665. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  6666. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  6667. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  6668. // enter the room by replying with 'not-authorized'. This would
  6669. // result in reconnection from authorized domain.
  6670. // We're either missing Jicofo/Prosody config for anonymous
  6671. // domains or something is wrong.
  6672. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  6673. } else {
  6674. console.warn('onPresError ', pres);
  6675. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6676. }
  6677. } else {
  6678. console.warn('onPresError ', pres);
  6679. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6680. }
  6681. };
  6682. ChatRoom.prototype.kick = function (jid) {
  6683. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  6684. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  6685. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  6686. .c('reason').t('You have been kicked.').up().up().up();
  6687. this.connection.sendIQ(
  6688. kickIQ,
  6689. function (result) {
  6690. console.log('Kick participant with jid: ', jid, result);
  6691. },
  6692. function (error) {
  6693. console.log('Kick participant error: ', error);
  6694. });
  6695. };
  6696. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  6697. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  6698. var ob = this;
  6699. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  6700. function (res) {
  6701. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  6702. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6703. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6704. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6705. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  6706. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  6707. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  6708. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  6709. ob.connection.sendIQ(formsubmit,
  6710. onSuccess,
  6711. onError);
  6712. } else {
  6713. onNotSupported();
  6714. }
  6715. }, onError);
  6716. };
  6717. ChatRoom.prototype.addToPresence = function (key, values) {
  6718. values.tagName = key;
  6719. this.presMap["nodes"].push(values);
  6720. };
  6721. ChatRoom.prototype.removeFromPresence = function (key) {
  6722. for(var i = 0; i < this.presMap.nodes.length; i++)
  6723. {
  6724. if(key === this.presMap.nodes[i].tagName)
  6725. this.presMap.nodes.splice(i, 1);
  6726. }
  6727. };
  6728. ChatRoom.prototype.isModerator = function (jid) {
  6729. return this.role === 'moderator';
  6730. };
  6731. ChatRoom.prototype.getMemberRole = function (peerJid) {
  6732. if (this.members[peerJid]) {
  6733. return this.members[peerJid].role;
  6734. }
  6735. return null;
  6736. };
  6737. module.exports = function(XMPP) {
  6738. Strophe.addConnectionPlugin('emuc', {
  6739. connection: null,
  6740. rooms: {},//map with the rooms
  6741. init: function (conn) {
  6742. this.connection = conn;
  6743. // add handlers (just once)
  6744. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, null, null);
  6745. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null);
  6746. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null);
  6747. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null);
  6748. },
  6749. doJoin: function (jid, password, eventEmitter) {
  6750. var roomJid = Strophe.getBareJidFromJid(jid);
  6751. if(this.rooms[roomJid])
  6752. {
  6753. console.error("You are already in the room!");
  6754. return;
  6755. }
  6756. this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, eventEmitter);
  6757. this.rooms[roomJid].join();
  6758. return this.rooms[roomJid];
  6759. },
  6760. doLeave: function (jid) {
  6761. this.rooms[jid].doLeave();
  6762. delete this.rooms[jid];
  6763. },
  6764. onPresence: function (pres) {
  6765. var from = pres.getAttribute('from');
  6766. // What is this for? A workaround for something?
  6767. if (pres.getAttribute('type')) {
  6768. return true;
  6769. }
  6770. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  6771. if(!room)
  6772. return;
  6773. // Parse status.
  6774. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  6775. room.createNonAnonymousRoom();
  6776. }
  6777. room.onPresence(pres);
  6778. return true;
  6779. },
  6780. onPresenceUnavailable: function (pres) {
  6781. var from = pres.getAttribute('from');
  6782. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  6783. if(!room)
  6784. return;
  6785. room.onPresenceUnavailable(pres, from);
  6786. return true;
  6787. },
  6788. onPresenceError: function (pres) {
  6789. var from = pres.getAttribute('from');
  6790. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  6791. if(!room)
  6792. return;
  6793. room.onPresenceError(pres, from);
  6794. return true;
  6795. },
  6796. onMessage: function (msg) {
  6797. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  6798. var from = msg.getAttribute('from');
  6799. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  6800. if(!room)
  6801. return;
  6802. room.onMessage(msg, from);
  6803. return true;
  6804. }
  6805. });
  6806. };
  6807. },{"../../service/xmpp/XMPPEvents":73,"../RTC/RTC":11,"./moderator":23}],25:[function(require,module,exports){
  6808. /* jshint -W117 */
  6809. var JingleSession = require("./JingleSessionPC");
  6810. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6811. var RTCBrowserType = require("../RTC/RTCBrowserType");
  6812. module.exports = function(XMPP, eventEmitter) {
  6813. Strophe.addConnectionPlugin('jingle', {
  6814. connection: null,
  6815. sessions: {},
  6816. jid2session: {},
  6817. ice_config: {iceServers: []},
  6818. media_constraints: {
  6819. mandatory: {
  6820. 'OfferToReceiveAudio': true,
  6821. 'OfferToReceiveVideo': true
  6822. }
  6823. // MozDontOfferDataChannel: true when this is firefox
  6824. },
  6825. init: function (conn) {
  6826. this.connection = conn;
  6827. if (this.connection.disco) {
  6828. // http://xmpp.org/extensions/xep-0167.html#support
  6829. // http://xmpp.org/extensions/xep-0176.html#support
  6830. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  6831. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  6832. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  6833. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  6834. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  6835. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  6836. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  6837. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  6838. || RTCBrowserType.isTemasysPluginUsed()) {
  6839. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  6840. }
  6841. // this is dealt with by SDP O/A so we don't need to announce this
  6842. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  6843. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  6844. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  6845. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  6846. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  6847. }
  6848. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  6849. },
  6850. onJingle: function (iq) {
  6851. var sid = $(iq).find('jingle').attr('sid');
  6852. var action = $(iq).find('jingle').attr('action');
  6853. var fromJid = iq.getAttribute('from');
  6854. // send ack first
  6855. var ack = $iq({type: 'result',
  6856. to: fromJid,
  6857. id: iq.getAttribute('id')
  6858. });
  6859. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  6860. var sess = this.sessions[sid];
  6861. if ('session-initiate' != action) {
  6862. if (sess === null) {
  6863. ack.type = 'error';
  6864. ack.c('error', {type: 'cancel'})
  6865. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  6866. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  6867. this.connection.send(ack);
  6868. return true;
  6869. }
  6870. // local jid is not checked
  6871. if (fromJid != sess.peerjid) {
  6872. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  6873. ack.type = 'error';
  6874. ack.c('error', {type: 'cancel'})
  6875. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  6876. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  6877. this.connection.send(ack);
  6878. return true;
  6879. }
  6880. } else if (sess !== undefined) {
  6881. // existing session with same session id
  6882. // this might be out-of-order if the sess.peerjid is the same as from
  6883. ack.type = 'error';
  6884. ack.c('error', {type: 'cancel'})
  6885. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  6886. console.warn('duplicate session id', sid);
  6887. this.connection.send(ack);
  6888. return true;
  6889. }
  6890. // FIXME: check for a defined action
  6891. this.connection.send(ack);
  6892. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  6893. switch (action) {
  6894. case 'session-initiate':
  6895. var startMuted = $(iq).find('jingle>startmuted');
  6896. if (startMuted && startMuted.length > 0) {
  6897. var audioMuted = startMuted.attr("audio");
  6898. var videoMuted = startMuted.attr("video");
  6899. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  6900. audioMuted === "true", videoMuted === "true");
  6901. }
  6902. sess = new JingleSession(
  6903. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  6904. this.connection, XMPP, eventEmitter);
  6905. // configure session
  6906. sess.media_constraints = this.media_constraints;
  6907. sess.ice_config = this.ice_config;
  6908. sess.initialize(Strophe.getBareJidFromJid(fromJid), false);
  6909. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  6910. sess.setOffer($(iq).find('>jingle'));
  6911. this.sessions[sess.sid] = sess;
  6912. this.jid2session[sess.peerjid] = sess;
  6913. // the callback should either
  6914. // .sendAnswer and .accept
  6915. // or .sendTerminate -- not necessarily synchronous
  6916. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  6917. sess.sendAnswer();
  6918. sess.accept();
  6919. break;
  6920. case 'session-accept':
  6921. sess.setAnswer($(iq).find('>jingle'));
  6922. sess.accept();
  6923. break;
  6924. case 'session-terminate':
  6925. // If this is not the focus sending the terminate, we have
  6926. // nothing more to do here.
  6927. if (Object.keys(this.sessions).length < 1
  6928. || !(this.sessions[Object.keys(this.sessions)[0]]
  6929. instanceof JingleSession))
  6930. {
  6931. break;
  6932. }
  6933. console.log('terminating...', sess.sid);
  6934. sess.terminate();
  6935. this.terminate(sess.sid);
  6936. if ($(iq).find('>jingle>reason').length) {
  6937. $(document).trigger('callterminated.jingle', [
  6938. sess.sid,
  6939. sess.peerjid,
  6940. $(iq).find('>jingle>reason>:first')[0].tagName,
  6941. $(iq).find('>jingle>reason>text').text()
  6942. ]);
  6943. } else {
  6944. $(document).trigger('callterminated.jingle',
  6945. [sess.sid, sess.peerjid]);
  6946. }
  6947. break;
  6948. case 'transport-info':
  6949. sess.addIceCandidate($(iq).find('>jingle>content'));
  6950. break;
  6951. case 'session-info':
  6952. var affected;
  6953. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  6954. $(document).trigger('ringing.jingle', [sess.sid]);
  6955. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  6956. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  6957. $(document).trigger('mute.jingle', [sess.sid, affected]);
  6958. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  6959. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  6960. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  6961. }
  6962. break;
  6963. case 'addsource': // FIXME: proprietary, un-jingleish
  6964. case 'source-add': // FIXME: proprietary
  6965. sess.addSource($(iq).find('>jingle>content'), fromJid);
  6966. break;
  6967. case 'removesource': // FIXME: proprietary, un-jingleish
  6968. case 'source-remove': // FIXME: proprietary
  6969. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  6970. break;
  6971. default:
  6972. console.warn('jingle action not implemented', action);
  6973. break;
  6974. }
  6975. return true;
  6976. },
  6977. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  6978. if (sid === null || sid === undefined) {
  6979. for (sid in this.sessions) {
  6980. if (this.sessions[sid].state != 'ended') {
  6981. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  6982. this.sessions[sid].terminate();
  6983. }
  6984. delete this.jid2session[this.sessions[sid].peerjid];
  6985. delete this.sessions[sid];
  6986. }
  6987. } else if (this.sessions.hasOwnProperty(sid)) {
  6988. if (this.sessions[sid].state != 'ended') {
  6989. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  6990. this.sessions[sid].terminate();
  6991. }
  6992. delete this.jid2session[this.sessions[sid].peerjid];
  6993. delete this.sessions[sid];
  6994. }
  6995. },
  6996. getStunAndTurnCredentials: function () {
  6997. // get stun and turn configuration from server via xep-0215
  6998. // uses time-limited credentials as described in
  6999. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  7000. //
  7001. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  7002. // for a prosody module which implements this
  7003. //
  7004. // currently, this doesn't work with updateIce and therefore credentials with a long
  7005. // validity have to be fetched before creating the peerconnection
  7006. // TODO: implement refresh via updateIce as described in
  7007. // https://code.google.com/p/webrtc/issues/detail?id=1650
  7008. var self = this;
  7009. this.connection.sendIQ(
  7010. $iq({type: 'get', to: this.connection.domain})
  7011. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  7012. function (res) {
  7013. var iceservers = [];
  7014. $(res).find('>services>service').each(function (idx, el) {
  7015. el = $(el);
  7016. var dict = {};
  7017. var type = el.attr('type');
  7018. switch (type) {
  7019. case 'stun':
  7020. dict.url = 'stun:' + el.attr('host');
  7021. if (el.attr('port')) {
  7022. dict.url += ':' + el.attr('port');
  7023. }
  7024. iceservers.push(dict);
  7025. break;
  7026. case 'turn':
  7027. case 'turns':
  7028. dict.url = type + ':';
  7029. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  7030. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  7031. dict.url += el.attr('username') + '@';
  7032. } else {
  7033. dict.username = el.attr('username'); // only works in M28
  7034. }
  7035. }
  7036. dict.url += el.attr('host');
  7037. if (el.attr('port') && el.attr('port') != '3478') {
  7038. dict.url += ':' + el.attr('port');
  7039. }
  7040. if (el.attr('transport') && el.attr('transport') != 'udp') {
  7041. dict.url += '?transport=' + el.attr('transport');
  7042. }
  7043. if (el.attr('password')) {
  7044. dict.credential = el.attr('password');
  7045. }
  7046. iceservers.push(dict);
  7047. break;
  7048. }
  7049. });
  7050. self.ice_config.iceServers = iceservers;
  7051. },
  7052. function (err) {
  7053. console.warn('getting turn credentials failed', err);
  7054. console.warn('is mod_turncredentials or similar installed?');
  7055. }
  7056. );
  7057. // implement push?
  7058. },
  7059. /**
  7060. * Returns the data saved in 'updateLog' in a format to be logged.
  7061. */
  7062. getLog: function () {
  7063. var data = {};
  7064. var self = this;
  7065. Object.keys(this.sessions).forEach(function (sid) {
  7066. var session = self.sessions[sid];
  7067. if (session.peerconnection && session.peerconnection.updateLog) {
  7068. // FIXME: should probably be a .dump call
  7069. data["jingle_" + session.sid] = {
  7070. updateLog: session.peerconnection.updateLog,
  7071. stats: session.peerconnection.stats,
  7072. url: window.location.href
  7073. };
  7074. }
  7075. });
  7076. return data;
  7077. }
  7078. });
  7079. };
  7080. },{"../../service/xmpp/XMPPEvents":73,"../RTC/RTCBrowserType":12,"./JingleSessionPC":17}],26:[function(require,module,exports){
  7081. /* global Strophe */
  7082. module.exports = function () {
  7083. Strophe.addConnectionPlugin('logger', {
  7084. // logs raw stanzas and makes them available for download as JSON
  7085. connection: null,
  7086. log: [],
  7087. init: function (conn) {
  7088. this.connection = conn;
  7089. this.connection.rawInput = this.log_incoming.bind(this);
  7090. this.connection.rawOutput = this.log_outgoing.bind(this);
  7091. },
  7092. log_incoming: function (stanza) {
  7093. this.log.push([new Date().getTime(), 'incoming', stanza]);
  7094. },
  7095. log_outgoing: function (stanza) {
  7096. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  7097. }
  7098. });
  7099. };
  7100. },{}],27:[function(require,module,exports){
  7101. /* jshint -W117 */
  7102. module.exports = function() {
  7103. Strophe.addConnectionPlugin('rayo',
  7104. {
  7105. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  7106. connection: null,
  7107. init: function (conn) {
  7108. this.connection = conn;
  7109. if (this.connection.disco) {
  7110. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  7111. }
  7112. this.connection.addHandler(
  7113. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  7114. },
  7115. onRayo: function (iq) {
  7116. console.info("Rayo IQ", iq);
  7117. },
  7118. dial: function (to, from, roomName, roomPass) {
  7119. var self = this;
  7120. var req = $iq(
  7121. {
  7122. type: 'set',
  7123. to: this.connection.emuc.focusMucJid
  7124. }
  7125. );
  7126. req.c('dial',
  7127. {
  7128. xmlns: this.RAYO_XMLNS,
  7129. to: to,
  7130. from: from
  7131. });
  7132. req.c('header',
  7133. {
  7134. name: 'JvbRoomName',
  7135. value: roomName
  7136. }).up();
  7137. if (roomPass !== null && roomPass.length) {
  7138. req.c('header',
  7139. {
  7140. name: 'JvbRoomPassword',
  7141. value: roomPass
  7142. }).up();
  7143. }
  7144. this.connection.sendIQ(
  7145. req,
  7146. function (result) {
  7147. console.info('Dial result ', result);
  7148. var resource = $(result).find('ref').attr('uri');
  7149. this.call_resource = resource.substr('xmpp:'.length);
  7150. console.info(
  7151. "Received call resource: " + this.call_resource);
  7152. },
  7153. function (error) {
  7154. console.info('Dial error ', error);
  7155. }
  7156. );
  7157. },
  7158. hang_up: function () {
  7159. if (!this.call_resource) {
  7160. console.warn("No call in progress");
  7161. return;
  7162. }
  7163. var self = this;
  7164. var req = $iq(
  7165. {
  7166. type: 'set',
  7167. to: this.call_resource
  7168. }
  7169. );
  7170. req.c('hangup',
  7171. {
  7172. xmlns: this.RAYO_XMLNS
  7173. });
  7174. this.connection.sendIQ(
  7175. req,
  7176. function (result) {
  7177. console.info('Hangup result ', result);
  7178. self.call_resource = null;
  7179. },
  7180. function (error) {
  7181. console.info('Hangup error ', error);
  7182. self.call_resource = null;
  7183. }
  7184. );
  7185. }
  7186. }
  7187. );
  7188. };
  7189. },{}],28:[function(require,module,exports){
  7190. /**
  7191. * Strophe logger implementation. Logs from level WARN and above.
  7192. */
  7193. module.exports = function () {
  7194. Strophe.log = function (level, msg) {
  7195. switch (level) {
  7196. case Strophe.LogLevel.WARN:
  7197. console.warn("Strophe: " + msg);
  7198. break;
  7199. case Strophe.LogLevel.ERROR:
  7200. case Strophe.LogLevel.FATAL:
  7201. console.error("Strophe: " + msg);
  7202. break;
  7203. }
  7204. };
  7205. Strophe.getStatusString = function (status) {
  7206. switch (status) {
  7207. case Strophe.Status.ERROR:
  7208. return "ERROR";
  7209. case Strophe.Status.CONNECTING:
  7210. return "CONNECTING";
  7211. case Strophe.Status.CONNFAIL:
  7212. return "CONNFAIL";
  7213. case Strophe.Status.AUTHENTICATING:
  7214. return "AUTHENTICATING";
  7215. case Strophe.Status.AUTHFAIL:
  7216. return "AUTHFAIL";
  7217. case Strophe.Status.CONNECTED:
  7218. return "CONNECTED";
  7219. case Strophe.Status.DISCONNECTED:
  7220. return "DISCONNECTED";
  7221. case Strophe.Status.DISCONNECTING:
  7222. return "DISCONNECTING";
  7223. case Strophe.Status.ATTACHED:
  7224. return "ATTACHED";
  7225. default:
  7226. return "unknown";
  7227. }
  7228. };
  7229. };
  7230. },{}],29:[function(require,module,exports){
  7231. /* global $, APP, config, Strophe*/
  7232. var Moderator = require("./moderator");
  7233. var EventEmitter = require("events");
  7234. var Pako = require("pako");
  7235. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  7236. var RTCEvents = require("../../service/RTC/RTCEvents");
  7237. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7238. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  7239. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  7240. var RTC = require("../RTC/RTC");
  7241. var authenticatedUser = false;
  7242. function createConnection(bosh) {
  7243. bosh = bosh || '/http-bind';
  7244. return new Strophe.Connection(bosh);
  7245. };
  7246. //!!!!!!!!!! FIXME: ...
  7247. function initStrophePlugins(XMPP)
  7248. {
  7249. require("./strophe.emuc")(XMPP);
  7250. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  7251. // require("./strophe.moderate")(XMPP, eventEmitter);
  7252. require("./strophe.util")();
  7253. require("./strophe.rayo")();
  7254. require("./strophe.logger")();
  7255. }
  7256. //!!!!!!!!!! FIXME: ...
  7257. ///**
  7258. // * If given <tt>localStream</tt> is video one this method will advertise it's
  7259. // * video type in MUC presence.
  7260. // * @param localStream new or modified <tt>LocalStream</tt>.
  7261. // */
  7262. //function broadcastLocalVideoType(localStream) {
  7263. // if (localStream.videoType)
  7264. // XMPP.addToPresence('videoType', localStream.videoType);
  7265. //}
  7266. //
  7267. //function registerListeners() {
  7268. // RTC.addStreamListener(
  7269. // broadcastLocalVideoType,
  7270. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  7271. // );
  7272. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  7273. // XMPP.addToPresence("devices", devices);
  7274. // });
  7275. //}
  7276. function XMPP(options) {
  7277. this.sessionTerminated = false;
  7278. this.eventEmitter = new EventEmitter();
  7279. this.connection = null;
  7280. this.disconnectInProgress = false;
  7281. this.forceMuted = false;
  7282. this.options = options;
  7283. initStrophePlugins(this);
  7284. // registerListeners();
  7285. this.connection = createConnection(options.bosh);
  7286. }
  7287. XMPP.prototype.getConnection = function(){ return connection; };
  7288. XMPP.prototype._connect = function (jid, password) {
  7289. var self = this;
  7290. // connection.connect() starts the connection process.
  7291. //
  7292. // As the connection process proceeds, the user supplied callback will
  7293. // be triggered multiple times with status updates. The callback should
  7294. // take two arguments - the status code and the error condition.
  7295. //
  7296. // The status code will be one of the values in the Strophe.Status
  7297. // constants. The error condition will be one of the conditions defined
  7298. // in RFC 3920 or the condition ‘strophe-parsererror’.
  7299. //
  7300. // The Parameters wait, hold and route are optional and only relevant
  7301. // for BOSH connections. Please see XEP 124 for a more detailed
  7302. // explanation of the optional parameters.
  7303. //
  7304. // Connection status constants for use by the connection handler
  7305. // callback.
  7306. //
  7307. // Status.ERROR - An error has occurred (websockets specific)
  7308. // Status.CONNECTING - The connection is currently being made
  7309. // Status.CONNFAIL - The connection attempt failed
  7310. // Status.AUTHENTICATING - The connection is authenticating
  7311. // Status.AUTHFAIL - The authentication attempt failed
  7312. // Status.CONNECTED - The connection has succeeded
  7313. // Status.DISCONNECTED - The connection has been terminated
  7314. // Status.DISCONNECTING - The connection is currently being terminated
  7315. // Status.ATTACHED - The connection has been attached
  7316. var anonymousConnectionFailed = false;
  7317. var connectionFailed = false;
  7318. var lastErrorMsg;
  7319. this.connection.connect(jid, password, function (status, msg) {
  7320. console.log('Strophe status changed to',
  7321. Strophe.getStatusString(status), msg);
  7322. if (status === Strophe.Status.CONNECTED) {
  7323. if (self.options.useStunTurn) {
  7324. self.connection.jingle.getStunAndTurnCredentials();
  7325. }
  7326. console.info("My Jabber ID: " + self.connection.jid);
  7327. if (password)
  7328. authenticatedUser = true;
  7329. if (self.connection && self.connection.connected &&
  7330. Strophe.getResourceFromJid(self.connection.jid)) {
  7331. // .connected is true while connecting?
  7332. // self.connection.send($pres());
  7333. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  7334. Strophe.getResourceFromJid(self.connection.jid));
  7335. }
  7336. } else if (status === Strophe.Status.CONNFAIL) {
  7337. if (msg === 'x-strophe-bad-non-anon-jid') {
  7338. anonymousConnectionFailed = true;
  7339. }
  7340. else
  7341. {
  7342. connectionFailed = true;
  7343. }
  7344. lastErrorMsg = msg;
  7345. } else if (status === Strophe.Status.DISCONNECTED) {
  7346. self.disconnectInProgress = false;
  7347. if (anonymousConnectionFailed) {
  7348. // prompt user for username and password
  7349. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  7350. JitsiConnectionErrors.PASSWORD_REQUIRED);
  7351. } else if(connectionFailed) {
  7352. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  7353. JitsiConnectionErrors.OTHER_ERROR,
  7354. msg ? msg : lastErrorMsg);
  7355. } else {
  7356. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  7357. msg ? msg : lastErrorMsg);
  7358. }
  7359. } else if (status === Strophe.Status.AUTHFAIL) {
  7360. // wrong password or username, prompt user
  7361. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  7362. JitsiConnectionErrors.PASSWORD_REQUIRED);
  7363. }
  7364. });
  7365. }
  7366. XMPP.prototype.connect = function (jid, password) {
  7367. if(!jid) {
  7368. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  7369. // Force authenticated domain if room is appended with '?login=true'
  7370. if (this.options.hosts.anonymousdomain &&
  7371. window.location.search.indexOf("login=true") !== -1) {
  7372. configDomain = this.options.hosts.domain;
  7373. }
  7374. jid = configDomain || window.location.hostname;
  7375. }
  7376. return this._connect(jid, password);
  7377. };
  7378. XMPP.prototype.joinRoom = function(roomName, useNicks, nick) {
  7379. var roomjid = roomName + '@' + this.options.hosts.muc;
  7380. if (useNicks) {
  7381. if (nick) {
  7382. roomjid += '/' + nick;
  7383. } else {
  7384. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  7385. }
  7386. } else {
  7387. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  7388. if(!authenticatedUser)
  7389. tmpJid = tmpJid.substr(0, 8);
  7390. roomjid += '/' + tmpJid;
  7391. }
  7392. return this.connection.emuc.doJoin(roomjid, null, this.eventEmitter);
  7393. };
  7394. XMPP.prototype.disposeConference = function (onUnload) {
  7395. var handler = this.connection.jingle.activecall;
  7396. if (handler && handler.peerconnection) {
  7397. // FIXME: probably removing streams is not required and close() should
  7398. // be enough
  7399. if (RTC.localAudio) {
  7400. handler.peerconnection.removeStream(
  7401. RTC.localAudio.getOriginalStream(), onUnload);
  7402. }
  7403. if (RTC.localVideo) {
  7404. handler.peerconnection.removeStream(
  7405. RTC.localVideo.getOriginalStream(), onUnload);
  7406. }
  7407. handler.peerconnection.close();
  7408. }
  7409. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  7410. this.connection.jingle.activecall = null;
  7411. if (!onUnload) {
  7412. this.sessionTerminated = true;
  7413. this.connection.emuc.doLeave();
  7414. }
  7415. };
  7416. XMPP.prototype.addListener = function(type, listener) {
  7417. this.eventEmitter.on(type, listener);
  7418. };
  7419. XMPP.prototype.removeListener = function (type, listener) {
  7420. this.eventEmitter.removeListener(type, listener);
  7421. };
  7422. XMPP.prototype.leaveRoom = function (jid) {
  7423. this.connection.emuc.doLeave(jid);
  7424. };
  7425. XMPP.prototype.isConferenceInProgress = function () {
  7426. return this.connection && this.connection.jingle.activecall &&
  7427. this.connection.jingle.activecall.peerconnection;
  7428. };
  7429. XMPP.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  7430. if (this.isConferenceInProgress()) {
  7431. // FIXME: will block switchInProgress on true value in case of exception
  7432. this.connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  7433. } else {
  7434. // We are done immediately
  7435. console.warn("No conference handler or conference not started yet");
  7436. callback();
  7437. }
  7438. };
  7439. XMPP.prototype.sendVideoInfoPresence = function (mute) {
  7440. if(!this.connection)
  7441. return;
  7442. this.connection.emuc.addVideoInfoToPresence(mute);
  7443. this.connection.emuc.sendPresence();
  7444. };
  7445. XMPP.prototype.setVideoMute = function (mute, callback, options) {
  7446. if(!this.connection)
  7447. return;
  7448. var self = this;
  7449. var localCallback = function (mute) {
  7450. self.sendVideoInfoPresence(mute);
  7451. return callback(mute);
  7452. };
  7453. if(this.connection.jingle.activecall)
  7454. {
  7455. this.connection.jingle.activecall.setVideoMute(
  7456. mute, localCallback, options);
  7457. }
  7458. else {
  7459. localCallback(mute);
  7460. }
  7461. };
  7462. XMPP.prototype.setAudioMute = function (mute, callback) {
  7463. if (!(this.connection && RTC.localAudio)) {
  7464. return false;
  7465. }
  7466. if (this.forceMuted && !mute) {
  7467. console.info("Asking focus for unmute");
  7468. this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  7469. // FIXME: wait for result before resetting muted status
  7470. this.forceMuted = false;
  7471. }
  7472. if (mute == RTC.localAudio.isMuted()) {
  7473. // Nothing to do
  7474. return true;
  7475. }
  7476. RTC.localAudio.setMute(mute);
  7477. this.sendAudioInfoPresence(mute, callback);
  7478. return true;
  7479. };
  7480. XMPP.prototype.sendAudioInfoPresence = function(mute, callback) {
  7481. if(this.connection) {
  7482. this.connection.emuc.addAudioInfoToPresence(mute);
  7483. this.connection.emuc.sendPresence();
  7484. }
  7485. callback();
  7486. return true;
  7487. };
  7488. /**
  7489. * Sends 'data' as a log message to the focus. Returns true iff a message
  7490. * was sent.
  7491. * @param data
  7492. * @returns {boolean} true iff a message was sent.
  7493. */
  7494. XMPP.prototype.sendLogs = function (data) {
  7495. if(!this.connection.emuc.focusMucJid)
  7496. return false;
  7497. var deflate = true;
  7498. var content = JSON.stringify(data);
  7499. if (deflate) {
  7500. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  7501. }
  7502. content = Base64.encode(content);
  7503. // XEP-0337-ish
  7504. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  7505. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  7506. id: 'PeerConnectionStats'});
  7507. message.c('message').t(content).up();
  7508. if (deflate) {
  7509. message.c('tag', {name: "deflated", value: "true"}).up();
  7510. }
  7511. message.up();
  7512. this.connection.send(message);
  7513. return true;
  7514. };
  7515. // Gets the logs from strophe.jingle.
  7516. XMPP.prototype.getJingleLog = function () {
  7517. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  7518. };
  7519. // Gets the logs from strophe.
  7520. XMPP.prototype.getXmppLog = function () {
  7521. return this.connection.logger ? this.connection.logger.log : null;
  7522. };
  7523. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  7524. this.connection.rayo.dial(to, from, roomName,roomPass);
  7525. };
  7526. XMPP.prototype.setMute = function (jid, mute) {
  7527. this.connection.moderate.setMute(jid, mute);
  7528. };
  7529. XMPP.prototype.eject = function (jid) {
  7530. this.connection.moderate.eject(jid);
  7531. };
  7532. XMPP.prototype.getJidFromSSRC = function (ssrc) {
  7533. if (!this.isConferenceInProgress())
  7534. return null;
  7535. return this.connection.jingle.activecall.getSsrcOwner(ssrc);
  7536. };
  7537. XMPP.prototype.getSessions = function () {
  7538. return this.connection.jingle.sessions;
  7539. };
  7540. XMPP.prototype.removeStream = function (stream) {
  7541. if (!this.isConferenceInProgress())
  7542. return;
  7543. this.connection.jingle.activecall.peerconnection.removeStream(stream);
  7544. };
  7545. XMPP.prototype.disconnect = function (callback) {
  7546. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  7547. {
  7548. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  7549. return;
  7550. }
  7551. this.disconnectInProgress = true;
  7552. this.connection.disconnect();
  7553. };
  7554. module.exports = XMPP;
  7555. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":67,"../../service/RTC/StreamEventTypes":69,"../../service/xmpp/XMPPEvents":73,"../RTC/RTC":11,"./moderator":23,"./strophe.emuc":24,"./strophe.jingle":25,"./strophe.logger":26,"./strophe.rayo":27,"./strophe.util":28,"events":74,"pako":32}],30:[function(require,module,exports){
  7556. (function (process){
  7557. /*!
  7558. * async
  7559. * https://github.com/caolan/async
  7560. *
  7561. * Copyright 2010-2014 Caolan McMahon
  7562. * Released under the MIT license
  7563. */
  7564. /*jshint onevar: false, indent:4 */
  7565. /*global setImmediate: false, setTimeout: false, console: false */
  7566. (function () {
  7567. var async = {};
  7568. // global on the server, window in the browser
  7569. var root, previous_async;
  7570. root = this;
  7571. if (root != null) {
  7572. previous_async = root.async;
  7573. }
  7574. async.noConflict = function () {
  7575. root.async = previous_async;
  7576. return async;
  7577. };
  7578. function only_once(fn) {
  7579. var called = false;
  7580. return function() {
  7581. if (called) throw new Error("Callback was already called.");
  7582. called = true;
  7583. fn.apply(root, arguments);
  7584. }
  7585. }
  7586. //// cross-browser compatiblity functions ////
  7587. var _toString = Object.prototype.toString;
  7588. var _isArray = Array.isArray || function (obj) {
  7589. return _toString.call(obj) === '[object Array]';
  7590. };
  7591. var _each = function (arr, iterator) {
  7592. if (arr.forEach) {
  7593. return arr.forEach(iterator);
  7594. }
  7595. for (var i = 0; i < arr.length; i += 1) {
  7596. iterator(arr[i], i, arr);
  7597. }
  7598. };
  7599. var _map = function (arr, iterator) {
  7600. if (arr.map) {
  7601. return arr.map(iterator);
  7602. }
  7603. var results = [];
  7604. _each(arr, function (x, i, a) {
  7605. results.push(iterator(x, i, a));
  7606. });
  7607. return results;
  7608. };
  7609. var _reduce = function (arr, iterator, memo) {
  7610. if (arr.reduce) {
  7611. return arr.reduce(iterator, memo);
  7612. }
  7613. _each(arr, function (x, i, a) {
  7614. memo = iterator(memo, x, i, a);
  7615. });
  7616. return memo;
  7617. };
  7618. var _keys = function (obj) {
  7619. if (Object.keys) {
  7620. return Object.keys(obj);
  7621. }
  7622. var keys = [];
  7623. for (var k in obj) {
  7624. if (obj.hasOwnProperty(k)) {
  7625. keys.push(k);
  7626. }
  7627. }
  7628. return keys;
  7629. };
  7630. //// exported async module functions ////
  7631. //// nextTick implementation with browser-compatible fallback ////
  7632. if (typeof process === 'undefined' || !(process.nextTick)) {
  7633. if (typeof setImmediate === 'function') {
  7634. async.nextTick = function (fn) {
  7635. // not a direct alias for IE10 compatibility
  7636. setImmediate(fn);
  7637. };
  7638. async.setImmediate = async.nextTick;
  7639. }
  7640. else {
  7641. async.nextTick = function (fn) {
  7642. setTimeout(fn, 0);
  7643. };
  7644. async.setImmediate = async.nextTick;
  7645. }
  7646. }
  7647. else {
  7648. async.nextTick = process.nextTick;
  7649. if (typeof setImmediate !== 'undefined') {
  7650. async.setImmediate = function (fn) {
  7651. // not a direct alias for IE10 compatibility
  7652. setImmediate(fn);
  7653. };
  7654. }
  7655. else {
  7656. async.setImmediate = async.nextTick;
  7657. }
  7658. }
  7659. async.each = function (arr, iterator, callback) {
  7660. callback = callback || function () {};
  7661. if (!arr.length) {
  7662. return callback();
  7663. }
  7664. var completed = 0;
  7665. _each(arr, function (x) {
  7666. iterator(x, only_once(done) );
  7667. });
  7668. function done(err) {
  7669. if (err) {
  7670. callback(err);
  7671. callback = function () {};
  7672. }
  7673. else {
  7674. completed += 1;
  7675. if (completed >= arr.length) {
  7676. callback();
  7677. }
  7678. }
  7679. }
  7680. };
  7681. async.forEach = async.each;
  7682. async.eachSeries = function (arr, iterator, callback) {
  7683. callback = callback || function () {};
  7684. if (!arr.length) {
  7685. return callback();
  7686. }
  7687. var completed = 0;
  7688. var iterate = function () {
  7689. iterator(arr[completed], function (err) {
  7690. if (err) {
  7691. callback(err);
  7692. callback = function () {};
  7693. }
  7694. else {
  7695. completed += 1;
  7696. if (completed >= arr.length) {
  7697. callback();
  7698. }
  7699. else {
  7700. iterate();
  7701. }
  7702. }
  7703. });
  7704. };
  7705. iterate();
  7706. };
  7707. async.forEachSeries = async.eachSeries;
  7708. async.eachLimit = function (arr, limit, iterator, callback) {
  7709. var fn = _eachLimit(limit);
  7710. fn.apply(null, [arr, iterator, callback]);
  7711. };
  7712. async.forEachLimit = async.eachLimit;
  7713. var _eachLimit = function (limit) {
  7714. return function (arr, iterator, callback) {
  7715. callback = callback || function () {};
  7716. if (!arr.length || limit <= 0) {
  7717. return callback();
  7718. }
  7719. var completed = 0;
  7720. var started = 0;
  7721. var running = 0;
  7722. (function replenish () {
  7723. if (completed >= arr.length) {
  7724. return callback();
  7725. }
  7726. while (running < limit && started < arr.length) {
  7727. started += 1;
  7728. running += 1;
  7729. iterator(arr[started - 1], function (err) {
  7730. if (err) {
  7731. callback(err);
  7732. callback = function () {};
  7733. }
  7734. else {
  7735. completed += 1;
  7736. running -= 1;
  7737. if (completed >= arr.length) {
  7738. callback();
  7739. }
  7740. else {
  7741. replenish();
  7742. }
  7743. }
  7744. });
  7745. }
  7746. })();
  7747. };
  7748. };
  7749. var doParallel = function (fn) {
  7750. return function () {
  7751. var args = Array.prototype.slice.call(arguments);
  7752. return fn.apply(null, [async.each].concat(args));
  7753. };
  7754. };
  7755. var doParallelLimit = function(limit, fn) {
  7756. return function () {
  7757. var args = Array.prototype.slice.call(arguments);
  7758. return fn.apply(null, [_eachLimit(limit)].concat(args));
  7759. };
  7760. };
  7761. var doSeries = function (fn) {
  7762. return function () {
  7763. var args = Array.prototype.slice.call(arguments);
  7764. return fn.apply(null, [async.eachSeries].concat(args));
  7765. };
  7766. };
  7767. var _asyncMap = function (eachfn, arr, iterator, callback) {
  7768. arr = _map(arr, function (x, i) {
  7769. return {index: i, value: x};
  7770. });
  7771. if (!callback) {
  7772. eachfn(arr, function (x, callback) {
  7773. iterator(x.value, function (err) {
  7774. callback(err);
  7775. });
  7776. });
  7777. } else {
  7778. var results = [];
  7779. eachfn(arr, function (x, callback) {
  7780. iterator(x.value, function (err, v) {
  7781. results[x.index] = v;
  7782. callback(err);
  7783. });
  7784. }, function (err) {
  7785. callback(err, results);
  7786. });
  7787. }
  7788. };
  7789. async.map = doParallel(_asyncMap);
  7790. async.mapSeries = doSeries(_asyncMap);
  7791. async.mapLimit = function (arr, limit, iterator, callback) {
  7792. return _mapLimit(limit)(arr, iterator, callback);
  7793. };
  7794. var _mapLimit = function(limit) {
  7795. return doParallelLimit(limit, _asyncMap);
  7796. };
  7797. // reduce only has a series version, as doing reduce in parallel won't
  7798. // work in many situations.
  7799. async.reduce = function (arr, memo, iterator, callback) {
  7800. async.eachSeries(arr, function (x, callback) {
  7801. iterator(memo, x, function (err, v) {
  7802. memo = v;
  7803. callback(err);
  7804. });
  7805. }, function (err) {
  7806. callback(err, memo);
  7807. });
  7808. };
  7809. // inject alias
  7810. async.inject = async.reduce;
  7811. // foldl alias
  7812. async.foldl = async.reduce;
  7813. async.reduceRight = function (arr, memo, iterator, callback) {
  7814. var reversed = _map(arr, function (x) {
  7815. return x;
  7816. }).reverse();
  7817. async.reduce(reversed, memo, iterator, callback);
  7818. };
  7819. // foldr alias
  7820. async.foldr = async.reduceRight;
  7821. var _filter = function (eachfn, arr, iterator, callback) {
  7822. var results = [];
  7823. arr = _map(arr, function (x, i) {
  7824. return {index: i, value: x};
  7825. });
  7826. eachfn(arr, function (x, callback) {
  7827. iterator(x.value, function (v) {
  7828. if (v) {
  7829. results.push(x);
  7830. }
  7831. callback();
  7832. });
  7833. }, function (err) {
  7834. callback(_map(results.sort(function (a, b) {
  7835. return a.index - b.index;
  7836. }), function (x) {
  7837. return x.value;
  7838. }));
  7839. });
  7840. };
  7841. async.filter = doParallel(_filter);
  7842. async.filterSeries = doSeries(_filter);
  7843. // select alias
  7844. async.select = async.filter;
  7845. async.selectSeries = async.filterSeries;
  7846. var _reject = function (eachfn, arr, iterator, callback) {
  7847. var results = [];
  7848. arr = _map(arr, function (x, i) {
  7849. return {index: i, value: x};
  7850. });
  7851. eachfn(arr, function (x, callback) {
  7852. iterator(x.value, function (v) {
  7853. if (!v) {
  7854. results.push(x);
  7855. }
  7856. callback();
  7857. });
  7858. }, function (err) {
  7859. callback(_map(results.sort(function (a, b) {
  7860. return a.index - b.index;
  7861. }), function (x) {
  7862. return x.value;
  7863. }));
  7864. });
  7865. };
  7866. async.reject = doParallel(_reject);
  7867. async.rejectSeries = doSeries(_reject);
  7868. var _detect = function (eachfn, arr, iterator, main_callback) {
  7869. eachfn(arr, function (x, callback) {
  7870. iterator(x, function (result) {
  7871. if (result) {
  7872. main_callback(x);
  7873. main_callback = function () {};
  7874. }
  7875. else {
  7876. callback();
  7877. }
  7878. });
  7879. }, function (err) {
  7880. main_callback();
  7881. });
  7882. };
  7883. async.detect = doParallel(_detect);
  7884. async.detectSeries = doSeries(_detect);
  7885. async.some = function (arr, iterator, main_callback) {
  7886. async.each(arr, function (x, callback) {
  7887. iterator(x, function (v) {
  7888. if (v) {
  7889. main_callback(true);
  7890. main_callback = function () {};
  7891. }
  7892. callback();
  7893. });
  7894. }, function (err) {
  7895. main_callback(false);
  7896. });
  7897. };
  7898. // any alias
  7899. async.any = async.some;
  7900. async.every = function (arr, iterator, main_callback) {
  7901. async.each(arr, function (x, callback) {
  7902. iterator(x, function (v) {
  7903. if (!v) {
  7904. main_callback(false);
  7905. main_callback = function () {};
  7906. }
  7907. callback();
  7908. });
  7909. }, function (err) {
  7910. main_callback(true);
  7911. });
  7912. };
  7913. // all alias
  7914. async.all = async.every;
  7915. async.sortBy = function (arr, iterator, callback) {
  7916. async.map(arr, function (x, callback) {
  7917. iterator(x, function (err, criteria) {
  7918. if (err) {
  7919. callback(err);
  7920. }
  7921. else {
  7922. callback(null, {value: x, criteria: criteria});
  7923. }
  7924. });
  7925. }, function (err, results) {
  7926. if (err) {
  7927. return callback(err);
  7928. }
  7929. else {
  7930. var fn = function (left, right) {
  7931. var a = left.criteria, b = right.criteria;
  7932. return a < b ? -1 : a > b ? 1 : 0;
  7933. };
  7934. callback(null, _map(results.sort(fn), function (x) {
  7935. return x.value;
  7936. }));
  7937. }
  7938. });
  7939. };
  7940. async.auto = function (tasks, callback) {
  7941. callback = callback || function () {};
  7942. var keys = _keys(tasks);
  7943. var remainingTasks = keys.length
  7944. if (!remainingTasks) {
  7945. return callback();
  7946. }
  7947. var results = {};
  7948. var listeners = [];
  7949. var addListener = function (fn) {
  7950. listeners.unshift(fn);
  7951. };
  7952. var removeListener = function (fn) {
  7953. for (var i = 0; i < listeners.length; i += 1) {
  7954. if (listeners[i] === fn) {
  7955. listeners.splice(i, 1);
  7956. return;
  7957. }
  7958. }
  7959. };
  7960. var taskComplete = function () {
  7961. remainingTasks--
  7962. _each(listeners.slice(0), function (fn) {
  7963. fn();
  7964. });
  7965. };
  7966. addListener(function () {
  7967. if (!remainingTasks) {
  7968. var theCallback = callback;
  7969. // prevent final callback from calling itself if it errors
  7970. callback = function () {};
  7971. theCallback(null, results);
  7972. }
  7973. });
  7974. _each(keys, function (k) {
  7975. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  7976. var taskCallback = function (err) {
  7977. var args = Array.prototype.slice.call(arguments, 1);
  7978. if (args.length <= 1) {
  7979. args = args[0];
  7980. }
  7981. if (err) {
  7982. var safeResults = {};
  7983. _each(_keys(results), function(rkey) {
  7984. safeResults[rkey] = results[rkey];
  7985. });
  7986. safeResults[k] = args;
  7987. callback(err, safeResults);
  7988. // stop subsequent errors hitting callback multiple times
  7989. callback = function () {};
  7990. }
  7991. else {
  7992. results[k] = args;
  7993. async.setImmediate(taskComplete);
  7994. }
  7995. };
  7996. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  7997. var ready = function () {
  7998. return _reduce(requires, function (a, x) {
  7999. return (a && results.hasOwnProperty(x));
  8000. }, true) && !results.hasOwnProperty(k);
  8001. };
  8002. if (ready()) {
  8003. task[task.length - 1](taskCallback, results);
  8004. }
  8005. else {
  8006. var listener = function () {
  8007. if (ready()) {
  8008. removeListener(listener);
  8009. task[task.length - 1](taskCallback, results);
  8010. }
  8011. };
  8012. addListener(listener);
  8013. }
  8014. });
  8015. };
  8016. async.retry = function(times, task, callback) {
  8017. var DEFAULT_TIMES = 5;
  8018. var attempts = [];
  8019. // Use defaults if times not passed
  8020. if (typeof times === 'function') {
  8021. callback = task;
  8022. task = times;
  8023. times = DEFAULT_TIMES;
  8024. }
  8025. // Make sure times is a number
  8026. times = parseInt(times, 10) || DEFAULT_TIMES;
  8027. var wrappedTask = function(wrappedCallback, wrappedResults) {
  8028. var retryAttempt = function(task, finalAttempt) {
  8029. return function(seriesCallback) {
  8030. task(function(err, result){
  8031. seriesCallback(!err || finalAttempt, {err: err, result: result});
  8032. }, wrappedResults);
  8033. };
  8034. };
  8035. while (times) {
  8036. attempts.push(retryAttempt(task, !(times-=1)));
  8037. }
  8038. async.series(attempts, function(done, data){
  8039. data = data[data.length - 1];
  8040. (wrappedCallback || callback)(data.err, data.result);
  8041. });
  8042. }
  8043. // If a callback is passed, run this as a controll flow
  8044. return callback ? wrappedTask() : wrappedTask
  8045. };
  8046. async.waterfall = function (tasks, callback) {
  8047. callback = callback || function () {};
  8048. if (!_isArray(tasks)) {
  8049. var err = new Error('First argument to waterfall must be an array of functions');
  8050. return callback(err);
  8051. }
  8052. if (!tasks.length) {
  8053. return callback();
  8054. }
  8055. var wrapIterator = function (iterator) {
  8056. return function (err) {
  8057. if (err) {
  8058. callback.apply(null, arguments);
  8059. callback = function () {};
  8060. }
  8061. else {
  8062. var args = Array.prototype.slice.call(arguments, 1);
  8063. var next = iterator.next();
  8064. if (next) {
  8065. args.push(wrapIterator(next));
  8066. }
  8067. else {
  8068. args.push(callback);
  8069. }
  8070. async.setImmediate(function () {
  8071. iterator.apply(null, args);
  8072. });
  8073. }
  8074. };
  8075. };
  8076. wrapIterator(async.iterator(tasks))();
  8077. };
  8078. var _parallel = function(eachfn, tasks, callback) {
  8079. callback = callback || function () {};
  8080. if (_isArray(tasks)) {
  8081. eachfn.map(tasks, function (fn, callback) {
  8082. if (fn) {
  8083. fn(function (err) {
  8084. var args = Array.prototype.slice.call(arguments, 1);
  8085. if (args.length <= 1) {
  8086. args = args[0];
  8087. }
  8088. callback.call(null, err, args);
  8089. });
  8090. }
  8091. }, callback);
  8092. }
  8093. else {
  8094. var results = {};
  8095. eachfn.each(_keys(tasks), function (k, callback) {
  8096. tasks[k](function (err) {
  8097. var args = Array.prototype.slice.call(arguments, 1);
  8098. if (args.length <= 1) {
  8099. args = args[0];
  8100. }
  8101. results[k] = args;
  8102. callback(err);
  8103. });
  8104. }, function (err) {
  8105. callback(err, results);
  8106. });
  8107. }
  8108. };
  8109. async.parallel = function (tasks, callback) {
  8110. _parallel({ map: async.map, each: async.each }, tasks, callback);
  8111. };
  8112. async.parallelLimit = function(tasks, limit, callback) {
  8113. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  8114. };
  8115. async.series = function (tasks, callback) {
  8116. callback = callback || function () {};
  8117. if (_isArray(tasks)) {
  8118. async.mapSeries(tasks, function (fn, callback) {
  8119. if (fn) {
  8120. fn(function (err) {
  8121. var args = Array.prototype.slice.call(arguments, 1);
  8122. if (args.length <= 1) {
  8123. args = args[0];
  8124. }
  8125. callback.call(null, err, args);
  8126. });
  8127. }
  8128. }, callback);
  8129. }
  8130. else {
  8131. var results = {};
  8132. async.eachSeries(_keys(tasks), function (k, callback) {
  8133. tasks[k](function (err) {
  8134. var args = Array.prototype.slice.call(arguments, 1);
  8135. if (args.length <= 1) {
  8136. args = args[0];
  8137. }
  8138. results[k] = args;
  8139. callback(err);
  8140. });
  8141. }, function (err) {
  8142. callback(err, results);
  8143. });
  8144. }
  8145. };
  8146. async.iterator = function (tasks) {
  8147. var makeCallback = function (index) {
  8148. var fn = function () {
  8149. if (tasks.length) {
  8150. tasks[index].apply(null, arguments);
  8151. }
  8152. return fn.next();
  8153. };
  8154. fn.next = function () {
  8155. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  8156. };
  8157. return fn;
  8158. };
  8159. return makeCallback(0);
  8160. };
  8161. async.apply = function (fn) {
  8162. var args = Array.prototype.slice.call(arguments, 1);
  8163. return function () {
  8164. return fn.apply(
  8165. null, args.concat(Array.prototype.slice.call(arguments))
  8166. );
  8167. };
  8168. };
  8169. var _concat = function (eachfn, arr, fn, callback) {
  8170. var r = [];
  8171. eachfn(arr, function (x, cb) {
  8172. fn(x, function (err, y) {
  8173. r = r.concat(y || []);
  8174. cb(err);
  8175. });
  8176. }, function (err) {
  8177. callback(err, r);
  8178. });
  8179. };
  8180. async.concat = doParallel(_concat);
  8181. async.concatSeries = doSeries(_concat);
  8182. async.whilst = function (test, iterator, callback) {
  8183. if (test()) {
  8184. iterator(function (err) {
  8185. if (err) {
  8186. return callback(err);
  8187. }
  8188. async.whilst(test, iterator, callback);
  8189. });
  8190. }
  8191. else {
  8192. callback();
  8193. }
  8194. };
  8195. async.doWhilst = function (iterator, test, callback) {
  8196. iterator(function (err) {
  8197. if (err) {
  8198. return callback(err);
  8199. }
  8200. var args = Array.prototype.slice.call(arguments, 1);
  8201. if (test.apply(null, args)) {
  8202. async.doWhilst(iterator, test, callback);
  8203. }
  8204. else {
  8205. callback();
  8206. }
  8207. });
  8208. };
  8209. async.until = function (test, iterator, callback) {
  8210. if (!test()) {
  8211. iterator(function (err) {
  8212. if (err) {
  8213. return callback(err);
  8214. }
  8215. async.until(test, iterator, callback);
  8216. });
  8217. }
  8218. else {
  8219. callback();
  8220. }
  8221. };
  8222. async.doUntil = function (iterator, test, callback) {
  8223. iterator(function (err) {
  8224. if (err) {
  8225. return callback(err);
  8226. }
  8227. var args = Array.prototype.slice.call(arguments, 1);
  8228. if (!test.apply(null, args)) {
  8229. async.doUntil(iterator, test, callback);
  8230. }
  8231. else {
  8232. callback();
  8233. }
  8234. });
  8235. };
  8236. async.queue = function (worker, concurrency) {
  8237. if (concurrency === undefined) {
  8238. concurrency = 1;
  8239. }
  8240. function _insert(q, data, pos, callback) {
  8241. if (!q.started){
  8242. q.started = true;
  8243. }
  8244. if (!_isArray(data)) {
  8245. data = [data];
  8246. }
  8247. if(data.length == 0) {
  8248. // call drain immediately if there are no tasks
  8249. return async.setImmediate(function() {
  8250. if (q.drain) {
  8251. q.drain();
  8252. }
  8253. });
  8254. }
  8255. _each(data, function(task) {
  8256. var item = {
  8257. data: task,
  8258. callback: typeof callback === 'function' ? callback : null
  8259. };
  8260. if (pos) {
  8261. q.tasks.unshift(item);
  8262. } else {
  8263. q.tasks.push(item);
  8264. }
  8265. if (q.saturated && q.tasks.length === q.concurrency) {
  8266. q.saturated();
  8267. }
  8268. async.setImmediate(q.process);
  8269. });
  8270. }
  8271. var workers = 0;
  8272. var q = {
  8273. tasks: [],
  8274. concurrency: concurrency,
  8275. saturated: null,
  8276. empty: null,
  8277. drain: null,
  8278. started: false,
  8279. paused: false,
  8280. push: function (data, callback) {
  8281. _insert(q, data, false, callback);
  8282. },
  8283. kill: function () {
  8284. q.drain = null;
  8285. q.tasks = [];
  8286. },
  8287. unshift: function (data, callback) {
  8288. _insert(q, data, true, callback);
  8289. },
  8290. process: function () {
  8291. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  8292. var task = q.tasks.shift();
  8293. if (q.empty && q.tasks.length === 0) {
  8294. q.empty();
  8295. }
  8296. workers += 1;
  8297. var next = function () {
  8298. workers -= 1;
  8299. if (task.callback) {
  8300. task.callback.apply(task, arguments);
  8301. }
  8302. if (q.drain && q.tasks.length + workers === 0) {
  8303. q.drain();
  8304. }
  8305. q.process();
  8306. };
  8307. var cb = only_once(next);
  8308. worker(task.data, cb);
  8309. }
  8310. },
  8311. length: function () {
  8312. return q.tasks.length;
  8313. },
  8314. running: function () {
  8315. return workers;
  8316. },
  8317. idle: function() {
  8318. return q.tasks.length + workers === 0;
  8319. },
  8320. pause: function () {
  8321. if (q.paused === true) { return; }
  8322. q.paused = true;
  8323. q.process();
  8324. },
  8325. resume: function () {
  8326. if (q.paused === false) { return; }
  8327. q.paused = false;
  8328. q.process();
  8329. }
  8330. };
  8331. return q;
  8332. };
  8333. async.priorityQueue = function (worker, concurrency) {
  8334. function _compareTasks(a, b){
  8335. return a.priority - b.priority;
  8336. };
  8337. function _binarySearch(sequence, item, compare) {
  8338. var beg = -1,
  8339. end = sequence.length - 1;
  8340. while (beg < end) {
  8341. var mid = beg + ((end - beg + 1) >>> 1);
  8342. if (compare(item, sequence[mid]) >= 0) {
  8343. beg = mid;
  8344. } else {
  8345. end = mid - 1;
  8346. }
  8347. }
  8348. return beg;
  8349. }
  8350. function _insert(q, data, priority, callback) {
  8351. if (!q.started){
  8352. q.started = true;
  8353. }
  8354. if (!_isArray(data)) {
  8355. data = [data];
  8356. }
  8357. if(data.length == 0) {
  8358. // call drain immediately if there are no tasks
  8359. return async.setImmediate(function() {
  8360. if (q.drain) {
  8361. q.drain();
  8362. }
  8363. });
  8364. }
  8365. _each(data, function(task) {
  8366. var item = {
  8367. data: task,
  8368. priority: priority,
  8369. callback: typeof callback === 'function' ? callback : null
  8370. };
  8371. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  8372. if (q.saturated && q.tasks.length === q.concurrency) {
  8373. q.saturated();
  8374. }
  8375. async.setImmediate(q.process);
  8376. });
  8377. }
  8378. // Start with a normal queue
  8379. var q = async.queue(worker, concurrency);
  8380. // Override push to accept second parameter representing priority
  8381. q.push = function (data, priority, callback) {
  8382. _insert(q, data, priority, callback);
  8383. };
  8384. // Remove unshift function
  8385. delete q.unshift;
  8386. return q;
  8387. };
  8388. async.cargo = function (worker, payload) {
  8389. var working = false,
  8390. tasks = [];
  8391. var cargo = {
  8392. tasks: tasks,
  8393. payload: payload,
  8394. saturated: null,
  8395. empty: null,
  8396. drain: null,
  8397. drained: true,
  8398. push: function (data, callback) {
  8399. if (!_isArray(data)) {
  8400. data = [data];
  8401. }
  8402. _each(data, function(task) {
  8403. tasks.push({
  8404. data: task,
  8405. callback: typeof callback === 'function' ? callback : null
  8406. });
  8407. cargo.drained = false;
  8408. if (cargo.saturated && tasks.length === payload) {
  8409. cargo.saturated();
  8410. }
  8411. });
  8412. async.setImmediate(cargo.process);
  8413. },
  8414. process: function process() {
  8415. if (working) return;
  8416. if (tasks.length === 0) {
  8417. if(cargo.drain && !cargo.drained) cargo.drain();
  8418. cargo.drained = true;
  8419. return;
  8420. }
  8421. var ts = typeof payload === 'number'
  8422. ? tasks.splice(0, payload)
  8423. : tasks.splice(0, tasks.length);
  8424. var ds = _map(ts, function (task) {
  8425. return task.data;
  8426. });
  8427. if(cargo.empty) cargo.empty();
  8428. working = true;
  8429. worker(ds, function () {
  8430. working = false;
  8431. var args = arguments;
  8432. _each(ts, function (data) {
  8433. if (data.callback) {
  8434. data.callback.apply(null, args);
  8435. }
  8436. });
  8437. process();
  8438. });
  8439. },
  8440. length: function () {
  8441. return tasks.length;
  8442. },
  8443. running: function () {
  8444. return working;
  8445. }
  8446. };
  8447. return cargo;
  8448. };
  8449. var _console_fn = function (name) {
  8450. return function (fn) {
  8451. var args = Array.prototype.slice.call(arguments, 1);
  8452. fn.apply(null, args.concat([function (err) {
  8453. var args = Array.prototype.slice.call(arguments, 1);
  8454. if (typeof console !== 'undefined') {
  8455. if (err) {
  8456. if (console.error) {
  8457. console.error(err);
  8458. }
  8459. }
  8460. else if (console[name]) {
  8461. _each(args, function (x) {
  8462. console[name](x);
  8463. });
  8464. }
  8465. }
  8466. }]));
  8467. };
  8468. };
  8469. async.log = _console_fn('log');
  8470. async.dir = _console_fn('dir');
  8471. /*async.info = _console_fn('info');
  8472. async.warn = _console_fn('warn');
  8473. async.error = _console_fn('error');*/
  8474. async.memoize = function (fn, hasher) {
  8475. var memo = {};
  8476. var queues = {};
  8477. hasher = hasher || function (x) {
  8478. return x;
  8479. };
  8480. var memoized = function () {
  8481. var args = Array.prototype.slice.call(arguments);
  8482. var callback = args.pop();
  8483. var key = hasher.apply(null, args);
  8484. if (key in memo) {
  8485. async.nextTick(function () {
  8486. callback.apply(null, memo[key]);
  8487. });
  8488. }
  8489. else if (key in queues) {
  8490. queues[key].push(callback);
  8491. }
  8492. else {
  8493. queues[key] = [callback];
  8494. fn.apply(null, args.concat([function () {
  8495. memo[key] = arguments;
  8496. var q = queues[key];
  8497. delete queues[key];
  8498. for (var i = 0, l = q.length; i < l; i++) {
  8499. q[i].apply(null, arguments);
  8500. }
  8501. }]));
  8502. }
  8503. };
  8504. memoized.memo = memo;
  8505. memoized.unmemoized = fn;
  8506. return memoized;
  8507. };
  8508. async.unmemoize = function (fn) {
  8509. return function () {
  8510. return (fn.unmemoized || fn).apply(null, arguments);
  8511. };
  8512. };
  8513. async.times = function (count, iterator, callback) {
  8514. var counter = [];
  8515. for (var i = 0; i < count; i++) {
  8516. counter.push(i);
  8517. }
  8518. return async.map(counter, iterator, callback);
  8519. };
  8520. async.timesSeries = function (count, iterator, callback) {
  8521. var counter = [];
  8522. for (var i = 0; i < count; i++) {
  8523. counter.push(i);
  8524. }
  8525. return async.mapSeries(counter, iterator, callback);
  8526. };
  8527. async.seq = function (/* functions... */) {
  8528. var fns = arguments;
  8529. return function () {
  8530. var that = this;
  8531. var args = Array.prototype.slice.call(arguments);
  8532. var callback = args.pop();
  8533. async.reduce(fns, args, function (newargs, fn, cb) {
  8534. fn.apply(that, newargs.concat([function () {
  8535. var err = arguments[0];
  8536. var nextargs = Array.prototype.slice.call(arguments, 1);
  8537. cb(err, nextargs);
  8538. }]))
  8539. },
  8540. function (err, results) {
  8541. callback.apply(that, [err].concat(results));
  8542. });
  8543. };
  8544. };
  8545. async.compose = function (/* functions... */) {
  8546. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  8547. };
  8548. var _applyEach = function (eachfn, fns /*args...*/) {
  8549. var go = function () {
  8550. var that = this;
  8551. var args = Array.prototype.slice.call(arguments);
  8552. var callback = args.pop();
  8553. return eachfn(fns, function (fn, cb) {
  8554. fn.apply(that, args.concat([cb]));
  8555. },
  8556. callback);
  8557. };
  8558. if (arguments.length > 2) {
  8559. var args = Array.prototype.slice.call(arguments, 2);
  8560. return go.apply(this, args);
  8561. }
  8562. else {
  8563. return go;
  8564. }
  8565. };
  8566. async.applyEach = doParallel(_applyEach);
  8567. async.applyEachSeries = doSeries(_applyEach);
  8568. async.forever = function (fn, callback) {
  8569. function next(err) {
  8570. if (err) {
  8571. if (callback) {
  8572. return callback(err);
  8573. }
  8574. throw err;
  8575. }
  8576. fn(next);
  8577. }
  8578. next();
  8579. };
  8580. // Node.js
  8581. if (typeof module !== 'undefined' && module.exports) {
  8582. module.exports = async;
  8583. }
  8584. // AMD / RequireJS
  8585. else if (typeof define !== 'undefined' && define.amd) {
  8586. define([], function () {
  8587. return async;
  8588. });
  8589. }
  8590. // included directly via <script> tag
  8591. else {
  8592. root.async = async;
  8593. }
  8594. }());
  8595. }).call(this,require('_process'))
  8596. },{"_process":75}],31:[function(require,module,exports){
  8597. (function (process,global){
  8598. /*!
  8599. * @overview es6-promise - a tiny implementation of Promises/A+.
  8600. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  8601. * @license Licensed under MIT license
  8602. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  8603. * @version 3.0.2
  8604. */
  8605. (function() {
  8606. "use strict";
  8607. function lib$es6$promise$utils$$objectOrFunction(x) {
  8608. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  8609. }
  8610. function lib$es6$promise$utils$$isFunction(x) {
  8611. return typeof x === 'function';
  8612. }
  8613. function lib$es6$promise$utils$$isMaybeThenable(x) {
  8614. return typeof x === 'object' && x !== null;
  8615. }
  8616. var lib$es6$promise$utils$$_isArray;
  8617. if (!Array.isArray) {
  8618. lib$es6$promise$utils$$_isArray = function (x) {
  8619. return Object.prototype.toString.call(x) === '[object Array]';
  8620. };
  8621. } else {
  8622. lib$es6$promise$utils$$_isArray = Array.isArray;
  8623. }
  8624. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  8625. var lib$es6$promise$asap$$len = 0;
  8626. var lib$es6$promise$asap$$toString = {}.toString;
  8627. var lib$es6$promise$asap$$vertxNext;
  8628. var lib$es6$promise$asap$$customSchedulerFn;
  8629. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  8630. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  8631. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  8632. lib$es6$promise$asap$$len += 2;
  8633. if (lib$es6$promise$asap$$len === 2) {
  8634. // If len is 2, that means that we need to schedule an async flush.
  8635. // If additional callbacks are queued before the queue is flushed, they
  8636. // will be processed by this flush that we are scheduling.
  8637. if (lib$es6$promise$asap$$customSchedulerFn) {
  8638. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  8639. } else {
  8640. lib$es6$promise$asap$$scheduleFlush();
  8641. }
  8642. }
  8643. }
  8644. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  8645. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  8646. }
  8647. function lib$es6$promise$asap$$setAsap(asapFn) {
  8648. lib$es6$promise$asap$$asap = asapFn;
  8649. }
  8650. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  8651. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  8652. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  8653. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  8654. // test for web worker but not in IE10
  8655. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  8656. typeof importScripts !== 'undefined' &&
  8657. typeof MessageChannel !== 'undefined';
  8658. // node
  8659. function lib$es6$promise$asap$$useNextTick() {
  8660. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  8661. // see https://github.com/cujojs/when/issues/410 for details
  8662. return function() {
  8663. process.nextTick(lib$es6$promise$asap$$flush);
  8664. };
  8665. }
  8666. // vertx
  8667. function lib$es6$promise$asap$$useVertxTimer() {
  8668. return function() {
  8669. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  8670. };
  8671. }
  8672. function lib$es6$promise$asap$$useMutationObserver() {
  8673. var iterations = 0;
  8674. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  8675. var node = document.createTextNode('');
  8676. observer.observe(node, { characterData: true });
  8677. return function() {
  8678. node.data = (iterations = ++iterations % 2);
  8679. };
  8680. }
  8681. // web worker
  8682. function lib$es6$promise$asap$$useMessageChannel() {
  8683. var channel = new MessageChannel();
  8684. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  8685. return function () {
  8686. channel.port2.postMessage(0);
  8687. };
  8688. }
  8689. function lib$es6$promise$asap$$useSetTimeout() {
  8690. return function() {
  8691. setTimeout(lib$es6$promise$asap$$flush, 1);
  8692. };
  8693. }
  8694. var lib$es6$promise$asap$$queue = new Array(1000);
  8695. function lib$es6$promise$asap$$flush() {
  8696. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  8697. var callback = lib$es6$promise$asap$$queue[i];
  8698. var arg = lib$es6$promise$asap$$queue[i+1];
  8699. callback(arg);
  8700. lib$es6$promise$asap$$queue[i] = undefined;
  8701. lib$es6$promise$asap$$queue[i+1] = undefined;
  8702. }
  8703. lib$es6$promise$asap$$len = 0;
  8704. }
  8705. function lib$es6$promise$asap$$attemptVertx() {
  8706. try {
  8707. var r = require;
  8708. var vertx = r('vertx');
  8709. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  8710. return lib$es6$promise$asap$$useVertxTimer();
  8711. } catch(e) {
  8712. return lib$es6$promise$asap$$useSetTimeout();
  8713. }
  8714. }
  8715. var lib$es6$promise$asap$$scheduleFlush;
  8716. // Decide what async method to use to triggering processing of queued callbacks:
  8717. if (lib$es6$promise$asap$$isNode) {
  8718. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  8719. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  8720. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  8721. } else if (lib$es6$promise$asap$$isWorker) {
  8722. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  8723. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  8724. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  8725. } else {
  8726. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  8727. }
  8728. function lib$es6$promise$$internal$$noop() {}
  8729. var lib$es6$promise$$internal$$PENDING = void 0;
  8730. var lib$es6$promise$$internal$$FULFILLED = 1;
  8731. var lib$es6$promise$$internal$$REJECTED = 2;
  8732. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  8733. function lib$es6$promise$$internal$$selfFulfillment() {
  8734. return new TypeError("You cannot resolve a promise with itself");
  8735. }
  8736. function lib$es6$promise$$internal$$cannotReturnOwn() {
  8737. return new TypeError('A promises callback cannot return that same promise.');
  8738. }
  8739. function lib$es6$promise$$internal$$getThen(promise) {
  8740. try {
  8741. return promise.then;
  8742. } catch(error) {
  8743. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  8744. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  8745. }
  8746. }
  8747. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  8748. try {
  8749. then.call(value, fulfillmentHandler, rejectionHandler);
  8750. } catch(e) {
  8751. return e;
  8752. }
  8753. }
  8754. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  8755. lib$es6$promise$asap$$asap(function(promise) {
  8756. var sealed = false;
  8757. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  8758. if (sealed) { return; }
  8759. sealed = true;
  8760. if (thenable !== value) {
  8761. lib$es6$promise$$internal$$resolve(promise, value);
  8762. } else {
  8763. lib$es6$promise$$internal$$fulfill(promise, value);
  8764. }
  8765. }, function(reason) {
  8766. if (sealed) { return; }
  8767. sealed = true;
  8768. lib$es6$promise$$internal$$reject(promise, reason);
  8769. }, 'Settle: ' + (promise._label || ' unknown promise'));
  8770. if (!sealed && error) {
  8771. sealed = true;
  8772. lib$es6$promise$$internal$$reject(promise, error);
  8773. }
  8774. }, promise);
  8775. }
  8776. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  8777. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  8778. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  8779. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  8780. lib$es6$promise$$internal$$reject(promise, thenable._result);
  8781. } else {
  8782. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  8783. lib$es6$promise$$internal$$resolve(promise, value);
  8784. }, function(reason) {
  8785. lib$es6$promise$$internal$$reject(promise, reason);
  8786. });
  8787. }
  8788. }
  8789. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  8790. if (maybeThenable.constructor === promise.constructor) {
  8791. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  8792. } else {
  8793. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  8794. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  8795. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  8796. } else if (then === undefined) {
  8797. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  8798. } else if (lib$es6$promise$utils$$isFunction(then)) {
  8799. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  8800. } else {
  8801. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  8802. }
  8803. }
  8804. }
  8805. function lib$es6$promise$$internal$$resolve(promise, value) {
  8806. if (promise === value) {
  8807. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  8808. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  8809. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  8810. } else {
  8811. lib$es6$promise$$internal$$fulfill(promise, value);
  8812. }
  8813. }
  8814. function lib$es6$promise$$internal$$publishRejection(promise) {
  8815. if (promise._onerror) {
  8816. promise._onerror(promise._result);
  8817. }
  8818. lib$es6$promise$$internal$$publish(promise);
  8819. }
  8820. function lib$es6$promise$$internal$$fulfill(promise, value) {
  8821. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  8822. promise._result = value;
  8823. promise._state = lib$es6$promise$$internal$$FULFILLED;
  8824. if (promise._subscribers.length !== 0) {
  8825. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  8826. }
  8827. }
  8828. function lib$es6$promise$$internal$$reject(promise, reason) {
  8829. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  8830. promise._state = lib$es6$promise$$internal$$REJECTED;
  8831. promise._result = reason;
  8832. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  8833. }
  8834. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  8835. var subscribers = parent._subscribers;
  8836. var length = subscribers.length;
  8837. parent._onerror = null;
  8838. subscribers[length] = child;
  8839. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  8840. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  8841. if (length === 0 && parent._state) {
  8842. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  8843. }
  8844. }
  8845. function lib$es6$promise$$internal$$publish(promise) {
  8846. var subscribers = promise._subscribers;
  8847. var settled = promise._state;
  8848. if (subscribers.length === 0) { return; }
  8849. var child, callback, detail = promise._result;
  8850. for (var i = 0; i < subscribers.length; i += 3) {
  8851. child = subscribers[i];
  8852. callback = subscribers[i + settled];
  8853. if (child) {
  8854. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  8855. } else {
  8856. callback(detail);
  8857. }
  8858. }
  8859. promise._subscribers.length = 0;
  8860. }
  8861. function lib$es6$promise$$internal$$ErrorObject() {
  8862. this.error = null;
  8863. }
  8864. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  8865. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  8866. try {
  8867. return callback(detail);
  8868. } catch(e) {
  8869. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  8870. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  8871. }
  8872. }
  8873. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  8874. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  8875. value, error, succeeded, failed;
  8876. if (hasCallback) {
  8877. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  8878. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  8879. failed = true;
  8880. error = value.error;
  8881. value = null;
  8882. } else {
  8883. succeeded = true;
  8884. }
  8885. if (promise === value) {
  8886. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  8887. return;
  8888. }
  8889. } else {
  8890. value = detail;
  8891. succeeded = true;
  8892. }
  8893. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  8894. // noop
  8895. } else if (hasCallback && succeeded) {
  8896. lib$es6$promise$$internal$$resolve(promise, value);
  8897. } else if (failed) {
  8898. lib$es6$promise$$internal$$reject(promise, error);
  8899. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  8900. lib$es6$promise$$internal$$fulfill(promise, value);
  8901. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  8902. lib$es6$promise$$internal$$reject(promise, value);
  8903. }
  8904. }
  8905. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  8906. try {
  8907. resolver(function resolvePromise(value){
  8908. lib$es6$promise$$internal$$resolve(promise, value);
  8909. }, function rejectPromise(reason) {
  8910. lib$es6$promise$$internal$$reject(promise, reason);
  8911. });
  8912. } catch(e) {
  8913. lib$es6$promise$$internal$$reject(promise, e);
  8914. }
  8915. }
  8916. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  8917. var enumerator = this;
  8918. enumerator._instanceConstructor = Constructor;
  8919. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  8920. if (enumerator._validateInput(input)) {
  8921. enumerator._input = input;
  8922. enumerator.length = input.length;
  8923. enumerator._remaining = input.length;
  8924. enumerator._init();
  8925. if (enumerator.length === 0) {
  8926. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  8927. } else {
  8928. enumerator.length = enumerator.length || 0;
  8929. enumerator._enumerate();
  8930. if (enumerator._remaining === 0) {
  8931. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  8932. }
  8933. }
  8934. } else {
  8935. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  8936. }
  8937. }
  8938. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  8939. return lib$es6$promise$utils$$isArray(input);
  8940. };
  8941. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  8942. return new Error('Array Methods must be provided an Array');
  8943. };
  8944. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  8945. this._result = new Array(this.length);
  8946. };
  8947. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  8948. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  8949. var enumerator = this;
  8950. var length = enumerator.length;
  8951. var promise = enumerator.promise;
  8952. var input = enumerator._input;
  8953. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  8954. enumerator._eachEntry(input[i], i);
  8955. }
  8956. };
  8957. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  8958. var enumerator = this;
  8959. var c = enumerator._instanceConstructor;
  8960. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  8961. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  8962. entry._onerror = null;
  8963. enumerator._settledAt(entry._state, i, entry._result);
  8964. } else {
  8965. enumerator._willSettleAt(c.resolve(entry), i);
  8966. }
  8967. } else {
  8968. enumerator._remaining--;
  8969. enumerator._result[i] = entry;
  8970. }
  8971. };
  8972. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  8973. var enumerator = this;
  8974. var promise = enumerator.promise;
  8975. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  8976. enumerator._remaining--;
  8977. if (state === lib$es6$promise$$internal$$REJECTED) {
  8978. lib$es6$promise$$internal$$reject(promise, value);
  8979. } else {
  8980. enumerator._result[i] = value;
  8981. }
  8982. }
  8983. if (enumerator._remaining === 0) {
  8984. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  8985. }
  8986. };
  8987. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  8988. var enumerator = this;
  8989. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  8990. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  8991. }, function(reason) {
  8992. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  8993. });
  8994. };
  8995. function lib$es6$promise$promise$all$$all(entries) {
  8996. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  8997. }
  8998. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  8999. function lib$es6$promise$promise$race$$race(entries) {
  9000. /*jshint validthis:true */
  9001. var Constructor = this;
  9002. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9003. if (!lib$es6$promise$utils$$isArray(entries)) {
  9004. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  9005. return promise;
  9006. }
  9007. var length = entries.length;
  9008. function onFulfillment(value) {
  9009. lib$es6$promise$$internal$$resolve(promise, value);
  9010. }
  9011. function onRejection(reason) {
  9012. lib$es6$promise$$internal$$reject(promise, reason);
  9013. }
  9014. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  9015. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  9016. }
  9017. return promise;
  9018. }
  9019. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  9020. function lib$es6$promise$promise$resolve$$resolve(object) {
  9021. /*jshint validthis:true */
  9022. var Constructor = this;
  9023. if (object && typeof object === 'object' && object.constructor === Constructor) {
  9024. return object;
  9025. }
  9026. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9027. lib$es6$promise$$internal$$resolve(promise, object);
  9028. return promise;
  9029. }
  9030. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  9031. function lib$es6$promise$promise$reject$$reject(reason) {
  9032. /*jshint validthis:true */
  9033. var Constructor = this;
  9034. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  9035. lib$es6$promise$$internal$$reject(promise, reason);
  9036. return promise;
  9037. }
  9038. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  9039. var lib$es6$promise$promise$$counter = 0;
  9040. function lib$es6$promise$promise$$needsResolver() {
  9041. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  9042. }
  9043. function lib$es6$promise$promise$$needsNew() {
  9044. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  9045. }
  9046. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  9047. /**
  9048. Promise objects represent the eventual result of an asynchronous operation. The
  9049. primary way of interacting with a promise is through its `then` method, which
  9050. registers callbacks to receive either a promise's eventual value or the reason
  9051. why the promise cannot be fulfilled.
  9052. Terminology
  9053. -----------
  9054. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  9055. - `thenable` is an object or function that defines a `then` method.
  9056. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  9057. - `exception` is a value that is thrown using the throw statement.
  9058. - `reason` is a value that indicates why a promise was rejected.
  9059. - `settled` the final resting state of a promise, fulfilled or rejected.
  9060. A promise can be in one of three states: pending, fulfilled, or rejected.
  9061. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  9062. state. Promises that are rejected have a rejection reason and are in the
  9063. rejected state. A fulfillment value is never a thenable.
  9064. Promises can also be said to *resolve* a value. If this value is also a
  9065. promise, then the original promise's settled state will match the value's
  9066. settled state. So a promise that *resolves* a promise that rejects will
  9067. itself reject, and a promise that *resolves* a promise that fulfills will
  9068. itself fulfill.
  9069. Basic Usage:
  9070. ------------
  9071. ```js
  9072. var promise = new Promise(function(resolve, reject) {
  9073. // on success
  9074. resolve(value);
  9075. // on failure
  9076. reject(reason);
  9077. });
  9078. promise.then(function(value) {
  9079. // on fulfillment
  9080. }, function(reason) {
  9081. // on rejection
  9082. });
  9083. ```
  9084. Advanced Usage:
  9085. ---------------
  9086. Promises shine when abstracting away asynchronous interactions such as
  9087. `XMLHttpRequest`s.
  9088. ```js
  9089. function getJSON(url) {
  9090. return new Promise(function(resolve, reject){
  9091. var xhr = new XMLHttpRequest();
  9092. xhr.open('GET', url);
  9093. xhr.onreadystatechange = handler;
  9094. xhr.responseType = 'json';
  9095. xhr.setRequestHeader('Accept', 'application/json');
  9096. xhr.send();
  9097. function handler() {
  9098. if (this.readyState === this.DONE) {
  9099. if (this.status === 200) {
  9100. resolve(this.response);
  9101. } else {
  9102. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  9103. }
  9104. }
  9105. };
  9106. });
  9107. }
  9108. getJSON('/posts.json').then(function(json) {
  9109. // on fulfillment
  9110. }, function(reason) {
  9111. // on rejection
  9112. });
  9113. ```
  9114. Unlike callbacks, promises are great composable primitives.
  9115. ```js
  9116. Promise.all([
  9117. getJSON('/posts'),
  9118. getJSON('/comments')
  9119. ]).then(function(values){
  9120. values[0] // => postsJSON
  9121. values[1] // => commentsJSON
  9122. return values;
  9123. });
  9124. ```
  9125. @class Promise
  9126. @param {function} resolver
  9127. Useful for tooling.
  9128. @constructor
  9129. */
  9130. function lib$es6$promise$promise$$Promise(resolver) {
  9131. this._id = lib$es6$promise$promise$$counter++;
  9132. this._state = undefined;
  9133. this._result = undefined;
  9134. this._subscribers = [];
  9135. if (lib$es6$promise$$internal$$noop !== resolver) {
  9136. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  9137. lib$es6$promise$promise$$needsResolver();
  9138. }
  9139. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  9140. lib$es6$promise$promise$$needsNew();
  9141. }
  9142. lib$es6$promise$$internal$$initializePromise(this, resolver);
  9143. }
  9144. }
  9145. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  9146. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  9147. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  9148. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  9149. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  9150. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  9151. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  9152. lib$es6$promise$promise$$Promise.prototype = {
  9153. constructor: lib$es6$promise$promise$$Promise,
  9154. /**
  9155. The primary way of interacting with a promise is through its `then` method,
  9156. which registers callbacks to receive either a promise's eventual value or the
  9157. reason why the promise cannot be fulfilled.
  9158. ```js
  9159. findUser().then(function(user){
  9160. // user is available
  9161. }, function(reason){
  9162. // user is unavailable, and you are given the reason why
  9163. });
  9164. ```
  9165. Chaining
  9166. --------
  9167. The return value of `then` is itself a promise. This second, 'downstream'
  9168. promise is resolved with the return value of the first promise's fulfillment
  9169. or rejection handler, or rejected if the handler throws an exception.
  9170. ```js
  9171. findUser().then(function (user) {
  9172. return user.name;
  9173. }, function (reason) {
  9174. return 'default name';
  9175. }).then(function (userName) {
  9176. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  9177. // will be `'default name'`
  9178. });
  9179. findUser().then(function (user) {
  9180. throw new Error('Found user, but still unhappy');
  9181. }, function (reason) {
  9182. throw new Error('`findUser` rejected and we're unhappy');
  9183. }).then(function (value) {
  9184. // never reached
  9185. }, function (reason) {
  9186. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  9187. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  9188. });
  9189. ```
  9190. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  9191. ```js
  9192. findUser().then(function (user) {
  9193. throw new PedagogicalException('Upstream error');
  9194. }).then(function (value) {
  9195. // never reached
  9196. }).then(function (value) {
  9197. // never reached
  9198. }, function (reason) {
  9199. // The `PedgagocialException` is propagated all the way down to here
  9200. });
  9201. ```
  9202. Assimilation
  9203. ------------
  9204. Sometimes the value you want to propagate to a downstream promise can only be
  9205. retrieved asynchronously. This can be achieved by returning a promise in the
  9206. fulfillment or rejection handler. The downstream promise will then be pending
  9207. until the returned promise is settled. This is called *assimilation*.
  9208. ```js
  9209. findUser().then(function (user) {
  9210. return findCommentsByAuthor(user);
  9211. }).then(function (comments) {
  9212. // The user's comments are now available
  9213. });
  9214. ```
  9215. If the assimliated promise rejects, then the downstream promise will also reject.
  9216. ```js
  9217. findUser().then(function (user) {
  9218. return findCommentsByAuthor(user);
  9219. }).then(function (comments) {
  9220. // If `findCommentsByAuthor` fulfills, we'll have the value here
  9221. }, function (reason) {
  9222. // If `findCommentsByAuthor` rejects, we'll have the reason here
  9223. });
  9224. ```
  9225. Simple Example
  9226. --------------
  9227. Synchronous Example
  9228. ```javascript
  9229. var result;
  9230. try {
  9231. result = findResult();
  9232. // success
  9233. } catch(reason) {
  9234. // failure
  9235. }
  9236. ```
  9237. Errback Example
  9238. ```js
  9239. findResult(function(result, err){
  9240. if (err) {
  9241. // failure
  9242. } else {
  9243. // success
  9244. }
  9245. });
  9246. ```
  9247. Promise Example;
  9248. ```javascript
  9249. findResult().then(function(result){
  9250. // success
  9251. }, function(reason){
  9252. // failure
  9253. });
  9254. ```
  9255. Advanced Example
  9256. --------------
  9257. Synchronous Example
  9258. ```javascript
  9259. var author, books;
  9260. try {
  9261. author = findAuthor();
  9262. books = findBooksByAuthor(author);
  9263. // success
  9264. } catch(reason) {
  9265. // failure
  9266. }
  9267. ```
  9268. Errback Example
  9269. ```js
  9270. function foundBooks(books) {
  9271. }
  9272. function failure(reason) {
  9273. }
  9274. findAuthor(function(author, err){
  9275. if (err) {
  9276. failure(err);
  9277. // failure
  9278. } else {
  9279. try {
  9280. findBoooksByAuthor(author, function(books, err) {
  9281. if (err) {
  9282. failure(err);
  9283. } else {
  9284. try {
  9285. foundBooks(books);
  9286. } catch(reason) {
  9287. failure(reason);
  9288. }
  9289. }
  9290. });
  9291. } catch(error) {
  9292. failure(err);
  9293. }
  9294. // success
  9295. }
  9296. });
  9297. ```
  9298. Promise Example;
  9299. ```javascript
  9300. findAuthor().
  9301. then(findBooksByAuthor).
  9302. then(function(books){
  9303. // found books
  9304. }).catch(function(reason){
  9305. // something went wrong
  9306. });
  9307. ```
  9308. @method then
  9309. @param {Function} onFulfilled
  9310. @param {Function} onRejected
  9311. Useful for tooling.
  9312. @return {Promise}
  9313. */
  9314. then: function(onFulfillment, onRejection) {
  9315. var parent = this;
  9316. var state = parent._state;
  9317. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  9318. return this;
  9319. }
  9320. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  9321. var result = parent._result;
  9322. if (state) {
  9323. var callback = arguments[state - 1];
  9324. lib$es6$promise$asap$$asap(function(){
  9325. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  9326. });
  9327. } else {
  9328. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  9329. }
  9330. return child;
  9331. },
  9332. /**
  9333. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  9334. as the catch block of a try/catch statement.
  9335. ```js
  9336. function findAuthor(){
  9337. throw new Error('couldn't find that author');
  9338. }
  9339. // synchronous
  9340. try {
  9341. findAuthor();
  9342. } catch(reason) {
  9343. // something went wrong
  9344. }
  9345. // async with promises
  9346. findAuthor().catch(function(reason){
  9347. // something went wrong
  9348. });
  9349. ```
  9350. @method catch
  9351. @param {Function} onRejection
  9352. Useful for tooling.
  9353. @return {Promise}
  9354. */
  9355. 'catch': function(onRejection) {
  9356. return this.then(null, onRejection);
  9357. }
  9358. };
  9359. function lib$es6$promise$polyfill$$polyfill() {
  9360. var local;
  9361. if (typeof global !== 'undefined') {
  9362. local = global;
  9363. } else if (typeof self !== 'undefined') {
  9364. local = self;
  9365. } else {
  9366. try {
  9367. local = Function('return this')();
  9368. } catch (e) {
  9369. throw new Error('polyfill failed because global object is unavailable in this environment');
  9370. }
  9371. }
  9372. var P = local.Promise;
  9373. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  9374. return;
  9375. }
  9376. local.Promise = lib$es6$promise$promise$$default;
  9377. }
  9378. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  9379. var lib$es6$promise$umd$$ES6Promise = {
  9380. 'Promise': lib$es6$promise$promise$$default,
  9381. 'polyfill': lib$es6$promise$polyfill$$default
  9382. };
  9383. /* global define:true module:true window: true */
  9384. if (typeof define === 'function' && define['amd']) {
  9385. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  9386. } else if (typeof module !== 'undefined' && module['exports']) {
  9387. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  9388. } else if (typeof this !== 'undefined') {
  9389. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  9390. }
  9391. lib$es6$promise$polyfill$$default();
  9392. }).call(this);
  9393. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9394. },{"_process":75}],32:[function(require,module,exports){
  9395. // Top level file is just a mixin of submodules & constants
  9396. 'use strict';
  9397. var assign = require('./lib/utils/common').assign;
  9398. var deflate = require('./lib/deflate');
  9399. var inflate = require('./lib/inflate');
  9400. var constants = require('./lib/zlib/constants');
  9401. var pako = {};
  9402. assign(pako, deflate, inflate, constants);
  9403. module.exports = pako;
  9404. },{"./lib/deflate":33,"./lib/inflate":34,"./lib/utils/common":35,"./lib/zlib/constants":38}],33:[function(require,module,exports){
  9405. 'use strict';
  9406. var zlib_deflate = require('./zlib/deflate.js');
  9407. var utils = require('./utils/common');
  9408. var strings = require('./utils/strings');
  9409. var msg = require('./zlib/messages');
  9410. var zstream = require('./zlib/zstream');
  9411. var toString = Object.prototype.toString;
  9412. /* Public constants ==========================================================*/
  9413. /* ===========================================================================*/
  9414. var Z_NO_FLUSH = 0;
  9415. var Z_FINISH = 4;
  9416. var Z_OK = 0;
  9417. var Z_STREAM_END = 1;
  9418. var Z_SYNC_FLUSH = 2;
  9419. var Z_DEFAULT_COMPRESSION = -1;
  9420. var Z_DEFAULT_STRATEGY = 0;
  9421. var Z_DEFLATED = 8;
  9422. /* ===========================================================================*/
  9423. /**
  9424. * class Deflate
  9425. *
  9426. * Generic JS-style wrapper for zlib calls. If you don't need
  9427. * streaming behaviour - use more simple functions: [[deflate]],
  9428. * [[deflateRaw]] and [[gzip]].
  9429. **/
  9430. /* internal
  9431. * Deflate.chunks -> Array
  9432. *
  9433. * Chunks of output data, if [[Deflate#onData]] not overriden.
  9434. **/
  9435. /**
  9436. * Deflate.result -> Uint8Array|Array
  9437. *
  9438. * Compressed result, generated by default [[Deflate#onData]]
  9439. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  9440. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  9441. * push a chunk with explicit flush (call [[Deflate#push]] with
  9442. * `Z_SYNC_FLUSH` param).
  9443. **/
  9444. /**
  9445. * Deflate.err -> Number
  9446. *
  9447. * Error code after deflate finished. 0 (Z_OK) on success.
  9448. * You will not need it in real life, because deflate errors
  9449. * are possible only on wrong options or bad `onData` / `onEnd`
  9450. * custom handlers.
  9451. **/
  9452. /**
  9453. * Deflate.msg -> String
  9454. *
  9455. * Error message, if [[Deflate.err]] != 0
  9456. **/
  9457. /**
  9458. * new Deflate(options)
  9459. * - options (Object): zlib deflate options.
  9460. *
  9461. * Creates new deflator instance with specified params. Throws exception
  9462. * on bad params. Supported options:
  9463. *
  9464. * - `level`
  9465. * - `windowBits`
  9466. * - `memLevel`
  9467. * - `strategy`
  9468. *
  9469. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  9470. * for more information on these.
  9471. *
  9472. * Additional options, for internal needs:
  9473. *
  9474. * - `chunkSize` - size of generated data chunks (16K by default)
  9475. * - `raw` (Boolean) - do raw deflate
  9476. * - `gzip` (Boolean) - create gzip wrapper
  9477. * - `to` (String) - if equal to 'string', then result will be "binary string"
  9478. * (each char code [0..255])
  9479. * - `header` (Object) - custom header for gzip
  9480. * - `text` (Boolean) - true if compressed data believed to be text
  9481. * - `time` (Number) - modification time, unix timestamp
  9482. * - `os` (Number) - operation system code
  9483. * - `extra` (Array) - array of bytes with extra data (max 65536)
  9484. * - `name` (String) - file name (binary string)
  9485. * - `comment` (String) - comment (binary string)
  9486. * - `hcrc` (Boolean) - true if header crc should be added
  9487. *
  9488. * ##### Example:
  9489. *
  9490. * ```javascript
  9491. * var pako = require('pako')
  9492. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  9493. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  9494. *
  9495. * var deflate = new pako.Deflate({ level: 3});
  9496. *
  9497. * deflate.push(chunk1, false);
  9498. * deflate.push(chunk2, true); // true -> last chunk
  9499. *
  9500. * if (deflate.err) { throw new Error(deflate.err); }
  9501. *
  9502. * console.log(deflate.result);
  9503. * ```
  9504. **/
  9505. var Deflate = function(options) {
  9506. this.options = utils.assign({
  9507. level: Z_DEFAULT_COMPRESSION,
  9508. method: Z_DEFLATED,
  9509. chunkSize: 16384,
  9510. windowBits: 15,
  9511. memLevel: 8,
  9512. strategy: Z_DEFAULT_STRATEGY,
  9513. to: ''
  9514. }, options || {});
  9515. var opt = this.options;
  9516. if (opt.raw && (opt.windowBits > 0)) {
  9517. opt.windowBits = -opt.windowBits;
  9518. }
  9519. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  9520. opt.windowBits += 16;
  9521. }
  9522. this.err = 0; // error code, if happens (0 = Z_OK)
  9523. this.msg = ''; // error message
  9524. this.ended = false; // used to avoid multiple onEnd() calls
  9525. this.chunks = []; // chunks of compressed data
  9526. this.strm = new zstream();
  9527. this.strm.avail_out = 0;
  9528. var status = zlib_deflate.deflateInit2(
  9529. this.strm,
  9530. opt.level,
  9531. opt.method,
  9532. opt.windowBits,
  9533. opt.memLevel,
  9534. opt.strategy
  9535. );
  9536. if (status !== Z_OK) {
  9537. throw new Error(msg[status]);
  9538. }
  9539. if (opt.header) {
  9540. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  9541. }
  9542. };
  9543. /**
  9544. * Deflate#push(data[, mode]) -> Boolean
  9545. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  9546. * converted to utf8 byte sequence.
  9547. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  9548. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  9549. *
  9550. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  9551. * new compressed chunks. Returns `true` on success. The last data block must have
  9552. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  9553. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  9554. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  9555. *
  9556. * On fail call [[Deflate#onEnd]] with error code and return false.
  9557. *
  9558. * We strongly recommend to use `Uint8Array` on input for best speed (output
  9559. * array format is detected automatically). Also, don't skip last param and always
  9560. * use the same type in your code (boolean or number). That will improve JS speed.
  9561. *
  9562. * For regular `Array`-s make sure all elements are [0..255].
  9563. *
  9564. * ##### Example
  9565. *
  9566. * ```javascript
  9567. * push(chunk, false); // push one of data chunks
  9568. * ...
  9569. * push(chunk, true); // push last chunk
  9570. * ```
  9571. **/
  9572. Deflate.prototype.push = function(data, mode) {
  9573. var strm = this.strm;
  9574. var chunkSize = this.options.chunkSize;
  9575. var status, _mode;
  9576. if (this.ended) { return false; }
  9577. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  9578. // Convert data if needed
  9579. if (typeof data === 'string') {
  9580. // If we need to compress text, change encoding to utf8.
  9581. strm.input = strings.string2buf(data);
  9582. } else if (toString.call(data) === '[object ArrayBuffer]') {
  9583. strm.input = new Uint8Array(data);
  9584. } else {
  9585. strm.input = data;
  9586. }
  9587. strm.next_in = 0;
  9588. strm.avail_in = strm.input.length;
  9589. do {
  9590. if (strm.avail_out === 0) {
  9591. strm.output = new utils.Buf8(chunkSize);
  9592. strm.next_out = 0;
  9593. strm.avail_out = chunkSize;
  9594. }
  9595. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  9596. if (status !== Z_STREAM_END && status !== Z_OK) {
  9597. this.onEnd(status);
  9598. this.ended = true;
  9599. return false;
  9600. }
  9601. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  9602. if (this.options.to === 'string') {
  9603. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  9604. } else {
  9605. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  9606. }
  9607. }
  9608. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  9609. // Finalize on the last chunk.
  9610. if (_mode === Z_FINISH) {
  9611. status = zlib_deflate.deflateEnd(this.strm);
  9612. this.onEnd(status);
  9613. this.ended = true;
  9614. return status === Z_OK;
  9615. }
  9616. // callback interim results if Z_SYNC_FLUSH.
  9617. if (_mode === Z_SYNC_FLUSH) {
  9618. this.onEnd(Z_OK);
  9619. strm.avail_out = 0;
  9620. return true;
  9621. }
  9622. return true;
  9623. };
  9624. /**
  9625. * Deflate#onData(chunk) -> Void
  9626. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  9627. * on js engine support. When string output requested, each chunk
  9628. * will be string.
  9629. *
  9630. * By default, stores data blocks in `chunks[]` property and glue
  9631. * those in `onEnd`. Override this handler, if you need another behaviour.
  9632. **/
  9633. Deflate.prototype.onData = function(chunk) {
  9634. this.chunks.push(chunk);
  9635. };
  9636. /**
  9637. * Deflate#onEnd(status) -> Void
  9638. * - status (Number): deflate status. 0 (Z_OK) on success,
  9639. * other if not.
  9640. *
  9641. * Called once after you tell deflate that the input stream is
  9642. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  9643. * or if an error happened. By default - join collected chunks,
  9644. * free memory and fill `results` / `err` properties.
  9645. **/
  9646. Deflate.prototype.onEnd = function(status) {
  9647. // On success - join
  9648. if (status === Z_OK) {
  9649. if (this.options.to === 'string') {
  9650. this.result = this.chunks.join('');
  9651. } else {
  9652. this.result = utils.flattenChunks(this.chunks);
  9653. }
  9654. }
  9655. this.chunks = [];
  9656. this.err = status;
  9657. this.msg = this.strm.msg;
  9658. };
  9659. /**
  9660. * deflate(data[, options]) -> Uint8Array|Array|String
  9661. * - data (Uint8Array|Array|String): input data to compress.
  9662. * - options (Object): zlib deflate options.
  9663. *
  9664. * Compress `data` with deflate alrorythm and `options`.
  9665. *
  9666. * Supported options are:
  9667. *
  9668. * - level
  9669. * - windowBits
  9670. * - memLevel
  9671. * - strategy
  9672. *
  9673. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  9674. * for more information on these.
  9675. *
  9676. * Sugar (options):
  9677. *
  9678. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  9679. * negative windowBits implicitly.
  9680. * - `to` (String) - if equal to 'string', then result will be "binary string"
  9681. * (each char code [0..255])
  9682. *
  9683. * ##### Example:
  9684. *
  9685. * ```javascript
  9686. * var pako = require('pako')
  9687. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  9688. *
  9689. * console.log(pako.deflate(data));
  9690. * ```
  9691. **/
  9692. function deflate(input, options) {
  9693. var deflator = new Deflate(options);
  9694. deflator.push(input, true);
  9695. // That will never happens, if you don't cheat with options :)
  9696. if (deflator.err) { throw deflator.msg; }
  9697. return deflator.result;
  9698. }
  9699. /**
  9700. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  9701. * - data (Uint8Array|Array|String): input data to compress.
  9702. * - options (Object): zlib deflate options.
  9703. *
  9704. * The same as [[deflate]], but creates raw data, without wrapper
  9705. * (header and adler32 crc).
  9706. **/
  9707. function deflateRaw(input, options) {
  9708. options = options || {};
  9709. options.raw = true;
  9710. return deflate(input, options);
  9711. }
  9712. /**
  9713. * gzip(data[, options]) -> Uint8Array|Array|String
  9714. * - data (Uint8Array|Array|String): input data to compress.
  9715. * - options (Object): zlib deflate options.
  9716. *
  9717. * The same as [[deflate]], but create gzip wrapper instead of
  9718. * deflate one.
  9719. **/
  9720. function gzip(input, options) {
  9721. options = options || {};
  9722. options.gzip = true;
  9723. return deflate(input, options);
  9724. }
  9725. exports.Deflate = Deflate;
  9726. exports.deflate = deflate;
  9727. exports.deflateRaw = deflateRaw;
  9728. exports.gzip = gzip;
  9729. },{"./utils/common":35,"./utils/strings":36,"./zlib/deflate.js":40,"./zlib/messages":45,"./zlib/zstream":47}],34:[function(require,module,exports){
  9730. 'use strict';
  9731. var zlib_inflate = require('./zlib/inflate.js');
  9732. var utils = require('./utils/common');
  9733. var strings = require('./utils/strings');
  9734. var c = require('./zlib/constants');
  9735. var msg = require('./zlib/messages');
  9736. var zstream = require('./zlib/zstream');
  9737. var gzheader = require('./zlib/gzheader');
  9738. var toString = Object.prototype.toString;
  9739. /**
  9740. * class Inflate
  9741. *
  9742. * Generic JS-style wrapper for zlib calls. If you don't need
  9743. * streaming behaviour - use more simple functions: [[inflate]]
  9744. * and [[inflateRaw]].
  9745. **/
  9746. /* internal
  9747. * inflate.chunks -> Array
  9748. *
  9749. * Chunks of output data, if [[Inflate#onData]] not overriden.
  9750. **/
  9751. /**
  9752. * Inflate.result -> Uint8Array|Array|String
  9753. *
  9754. * Uncompressed result, generated by default [[Inflate#onData]]
  9755. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  9756. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  9757. * push a chunk with explicit flush (call [[Inflate#push]] with
  9758. * `Z_SYNC_FLUSH` param).
  9759. **/
  9760. /**
  9761. * Inflate.err -> Number
  9762. *
  9763. * Error code after inflate finished. 0 (Z_OK) on success.
  9764. * Should be checked if broken data possible.
  9765. **/
  9766. /**
  9767. * Inflate.msg -> String
  9768. *
  9769. * Error message, if [[Inflate.err]] != 0
  9770. **/
  9771. /**
  9772. * new Inflate(options)
  9773. * - options (Object): zlib inflate options.
  9774. *
  9775. * Creates new inflator instance with specified params. Throws exception
  9776. * on bad params. Supported options:
  9777. *
  9778. * - `windowBits`
  9779. *
  9780. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  9781. * for more information on these.
  9782. *
  9783. * Additional options, for internal needs:
  9784. *
  9785. * - `chunkSize` - size of generated data chunks (16K by default)
  9786. * - `raw` (Boolean) - do raw inflate
  9787. * - `to` (String) - if equal to 'string', then result will be converted
  9788. * from utf8 to utf16 (javascript) string. When string output requested,
  9789. * chunk length can differ from `chunkSize`, depending on content.
  9790. *
  9791. * By default, when no options set, autodetect deflate/gzip data format via
  9792. * wrapper header.
  9793. *
  9794. * ##### Example:
  9795. *
  9796. * ```javascript
  9797. * var pako = require('pako')
  9798. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  9799. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  9800. *
  9801. * var inflate = new pako.Inflate({ level: 3});
  9802. *
  9803. * inflate.push(chunk1, false);
  9804. * inflate.push(chunk2, true); // true -> last chunk
  9805. *
  9806. * if (inflate.err) { throw new Error(inflate.err); }
  9807. *
  9808. * console.log(inflate.result);
  9809. * ```
  9810. **/
  9811. var Inflate = function(options) {
  9812. this.options = utils.assign({
  9813. chunkSize: 16384,
  9814. windowBits: 0,
  9815. to: ''
  9816. }, options || {});
  9817. var opt = this.options;
  9818. // Force window size for `raw` data, if not set directly,
  9819. // because we have no header for autodetect.
  9820. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  9821. opt.windowBits = -opt.windowBits;
  9822. if (opt.windowBits === 0) { opt.windowBits = -15; }
  9823. }
  9824. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  9825. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  9826. !(options && options.windowBits)) {
  9827. opt.windowBits += 32;
  9828. }
  9829. // Gzip header has no info about windows size, we can do autodetect only
  9830. // for deflate. So, if window size not set, force it to max when gzip possible
  9831. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  9832. // bit 3 (16) -> gzipped data
  9833. // bit 4 (32) -> autodetect gzip/deflate
  9834. if ((opt.windowBits & 15) === 0) {
  9835. opt.windowBits |= 15;
  9836. }
  9837. }
  9838. this.err = 0; // error code, if happens (0 = Z_OK)
  9839. this.msg = ''; // error message
  9840. this.ended = false; // used to avoid multiple onEnd() calls
  9841. this.chunks = []; // chunks of compressed data
  9842. this.strm = new zstream();
  9843. this.strm.avail_out = 0;
  9844. var status = zlib_inflate.inflateInit2(
  9845. this.strm,
  9846. opt.windowBits
  9847. );
  9848. if (status !== c.Z_OK) {
  9849. throw new Error(msg[status]);
  9850. }
  9851. this.header = new gzheader();
  9852. zlib_inflate.inflateGetHeader(this.strm, this.header);
  9853. };
  9854. /**
  9855. * Inflate#push(data[, mode]) -> Boolean
  9856. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  9857. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  9858. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  9859. *
  9860. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  9861. * new output chunks. Returns `true` on success. The last data block must have
  9862. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  9863. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  9864. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  9865. *
  9866. * On fail call [[Inflate#onEnd]] with error code and return false.
  9867. *
  9868. * We strongly recommend to use `Uint8Array` on input for best speed (output
  9869. * format is detected automatically). Also, don't skip last param and always
  9870. * use the same type in your code (boolean or number). That will improve JS speed.
  9871. *
  9872. * For regular `Array`-s make sure all elements are [0..255].
  9873. *
  9874. * ##### Example
  9875. *
  9876. * ```javascript
  9877. * push(chunk, false); // push one of data chunks
  9878. * ...
  9879. * push(chunk, true); // push last chunk
  9880. * ```
  9881. **/
  9882. Inflate.prototype.push = function(data, mode) {
  9883. var strm = this.strm;
  9884. var chunkSize = this.options.chunkSize;
  9885. var status, _mode;
  9886. var next_out_utf8, tail, utf8str;
  9887. if (this.ended) { return false; }
  9888. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  9889. // Convert data if needed
  9890. if (typeof data === 'string') {
  9891. // Only binary strings can be decompressed on practice
  9892. strm.input = strings.binstring2buf(data);
  9893. } else if (toString.call(data) === '[object ArrayBuffer]') {
  9894. strm.input = new Uint8Array(data);
  9895. } else {
  9896. strm.input = data;
  9897. }
  9898. strm.next_in = 0;
  9899. strm.avail_in = strm.input.length;
  9900. do {
  9901. if (strm.avail_out === 0) {
  9902. strm.output = new utils.Buf8(chunkSize);
  9903. strm.next_out = 0;
  9904. strm.avail_out = chunkSize;
  9905. }
  9906. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  9907. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  9908. this.onEnd(status);
  9909. this.ended = true;
  9910. return false;
  9911. }
  9912. if (strm.next_out) {
  9913. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  9914. if (this.options.to === 'string') {
  9915. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  9916. tail = strm.next_out - next_out_utf8;
  9917. utf8str = strings.buf2string(strm.output, next_out_utf8);
  9918. // move tail
  9919. strm.next_out = tail;
  9920. strm.avail_out = chunkSize - tail;
  9921. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  9922. this.onData(utf8str);
  9923. } else {
  9924. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  9925. }
  9926. }
  9927. }
  9928. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  9929. if (status === c.Z_STREAM_END) {
  9930. _mode = c.Z_FINISH;
  9931. }
  9932. // Finalize on the last chunk.
  9933. if (_mode === c.Z_FINISH) {
  9934. status = zlib_inflate.inflateEnd(this.strm);
  9935. this.onEnd(status);
  9936. this.ended = true;
  9937. return status === c.Z_OK;
  9938. }
  9939. // callback interim results if Z_SYNC_FLUSH.
  9940. if (_mode === c.Z_SYNC_FLUSH) {
  9941. this.onEnd(c.Z_OK);
  9942. strm.avail_out = 0;
  9943. return true;
  9944. }
  9945. return true;
  9946. };
  9947. /**
  9948. * Inflate#onData(chunk) -> Void
  9949. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  9950. * on js engine support. When string output requested, each chunk
  9951. * will be string.
  9952. *
  9953. * By default, stores data blocks in `chunks[]` property and glue
  9954. * those in `onEnd`. Override this handler, if you need another behaviour.
  9955. **/
  9956. Inflate.prototype.onData = function(chunk) {
  9957. this.chunks.push(chunk);
  9958. };
  9959. /**
  9960. * Inflate#onEnd(status) -> Void
  9961. * - status (Number): inflate status. 0 (Z_OK) on success,
  9962. * other if not.
  9963. *
  9964. * Called either after you tell inflate that the input stream is
  9965. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  9966. * or if an error happened. By default - join collected chunks,
  9967. * free memory and fill `results` / `err` properties.
  9968. **/
  9969. Inflate.prototype.onEnd = function(status) {
  9970. // On success - join
  9971. if (status === c.Z_OK) {
  9972. if (this.options.to === 'string') {
  9973. // Glue & convert here, until we teach pako to send
  9974. // utf8 alligned strings to onData
  9975. this.result = this.chunks.join('');
  9976. } else {
  9977. this.result = utils.flattenChunks(this.chunks);
  9978. }
  9979. }
  9980. this.chunks = [];
  9981. this.err = status;
  9982. this.msg = this.strm.msg;
  9983. };
  9984. /**
  9985. * inflate(data[, options]) -> Uint8Array|Array|String
  9986. * - data (Uint8Array|Array|String): input data to decompress.
  9987. * - options (Object): zlib inflate options.
  9988. *
  9989. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  9990. * format via wrapper header by default. That's why we don't provide
  9991. * separate `ungzip` method.
  9992. *
  9993. * Supported options are:
  9994. *
  9995. * - windowBits
  9996. *
  9997. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  9998. * for more information.
  9999. *
  10000. * Sugar (options):
  10001. *
  10002. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  10003. * negative windowBits implicitly.
  10004. * - `to` (String) - if equal to 'string', then result will be converted
  10005. * from utf8 to utf16 (javascript) string. When string output requested,
  10006. * chunk length can differ from `chunkSize`, depending on content.
  10007. *
  10008. *
  10009. * ##### Example:
  10010. *
  10011. * ```javascript
  10012. * var pako = require('pako')
  10013. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  10014. * , output;
  10015. *
  10016. * try {
  10017. * output = pako.inflate(input);
  10018. * } catch (err)
  10019. * console.log(err);
  10020. * }
  10021. * ```
  10022. **/
  10023. function inflate(input, options) {
  10024. var inflator = new Inflate(options);
  10025. inflator.push(input, true);
  10026. // That will never happens, if you don't cheat with options :)
  10027. if (inflator.err) { throw inflator.msg; }
  10028. return inflator.result;
  10029. }
  10030. /**
  10031. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  10032. * - data (Uint8Array|Array|String): input data to decompress.
  10033. * - options (Object): zlib inflate options.
  10034. *
  10035. * The same as [[inflate]], but creates raw data, without wrapper
  10036. * (header and adler32 crc).
  10037. **/
  10038. function inflateRaw(input, options) {
  10039. options = options || {};
  10040. options.raw = true;
  10041. return inflate(input, options);
  10042. }
  10043. /**
  10044. * ungzip(data[, options]) -> Uint8Array|Array|String
  10045. * - data (Uint8Array|Array|String): input data to decompress.
  10046. * - options (Object): zlib inflate options.
  10047. *
  10048. * Just shortcut to [[inflate]], because it autodetects format
  10049. * by header.content. Done for convenience.
  10050. **/
  10051. exports.Inflate = Inflate;
  10052. exports.inflate = inflate;
  10053. exports.inflateRaw = inflateRaw;
  10054. exports.ungzip = inflate;
  10055. },{"./utils/common":35,"./utils/strings":36,"./zlib/constants":38,"./zlib/gzheader":41,"./zlib/inflate.js":43,"./zlib/messages":45,"./zlib/zstream":47}],35:[function(require,module,exports){
  10056. 'use strict';
  10057. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  10058. (typeof Uint16Array !== 'undefined') &&
  10059. (typeof Int32Array !== 'undefined');
  10060. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  10061. var sources = Array.prototype.slice.call(arguments, 1);
  10062. while (sources.length) {
  10063. var source = sources.shift();
  10064. if (!source) { continue; }
  10065. if (typeof source !== 'object') {
  10066. throw new TypeError(source + 'must be non-object');
  10067. }
  10068. for (var p in source) {
  10069. if (source.hasOwnProperty(p)) {
  10070. obj[p] = source[p];
  10071. }
  10072. }
  10073. }
  10074. return obj;
  10075. };
  10076. // reduce buffer size, avoiding mem copy
  10077. exports.shrinkBuf = function (buf, size) {
  10078. if (buf.length === size) { return buf; }
  10079. if (buf.subarray) { return buf.subarray(0, size); }
  10080. buf.length = size;
  10081. return buf;
  10082. };
  10083. var fnTyped = {
  10084. arraySet: function (dest, src, src_offs, len, dest_offs) {
  10085. if (src.subarray && dest.subarray) {
  10086. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  10087. return;
  10088. }
  10089. // Fallback to ordinary array
  10090. for (var i=0; i<len; i++) {
  10091. dest[dest_offs + i] = src[src_offs + i];
  10092. }
  10093. },
  10094. // Join array of chunks to single array.
  10095. flattenChunks: function(chunks) {
  10096. var i, l, len, pos, chunk, result;
  10097. // calculate data length
  10098. len = 0;
  10099. for (i=0, l=chunks.length; i<l; i++) {
  10100. len += chunks[i].length;
  10101. }
  10102. // join chunks
  10103. result = new Uint8Array(len);
  10104. pos = 0;
  10105. for (i=0, l=chunks.length; i<l; i++) {
  10106. chunk = chunks[i];
  10107. result.set(chunk, pos);
  10108. pos += chunk.length;
  10109. }
  10110. return result;
  10111. }
  10112. };
  10113. var fnUntyped = {
  10114. arraySet: function (dest, src, src_offs, len, dest_offs) {
  10115. for (var i=0; i<len; i++) {
  10116. dest[dest_offs + i] = src[src_offs + i];
  10117. }
  10118. },
  10119. // Join array of chunks to single array.
  10120. flattenChunks: function(chunks) {
  10121. return [].concat.apply([], chunks);
  10122. }
  10123. };
  10124. // Enable/Disable typed arrays use, for testing
  10125. //
  10126. exports.setTyped = function (on) {
  10127. if (on) {
  10128. exports.Buf8 = Uint8Array;
  10129. exports.Buf16 = Uint16Array;
  10130. exports.Buf32 = Int32Array;
  10131. exports.assign(exports, fnTyped);
  10132. } else {
  10133. exports.Buf8 = Array;
  10134. exports.Buf16 = Array;
  10135. exports.Buf32 = Array;
  10136. exports.assign(exports, fnUntyped);
  10137. }
  10138. };
  10139. exports.setTyped(TYPED_OK);
  10140. },{}],36:[function(require,module,exports){
  10141. // String encode/decode helpers
  10142. 'use strict';
  10143. var utils = require('./common');
  10144. // Quick check if we can use fast array to bin string conversion
  10145. //
  10146. // - apply(Array) can fail on Android 2.2
  10147. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  10148. //
  10149. var STR_APPLY_OK = true;
  10150. var STR_APPLY_UIA_OK = true;
  10151. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  10152. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  10153. // Table with utf8 lengths (calculated by first byte of sequence)
  10154. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  10155. // because max possible codepoint is 0x10ffff
  10156. var _utf8len = new utils.Buf8(256);
  10157. for (var q=0; q<256; q++) {
  10158. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  10159. }
  10160. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  10161. // convert string to array (typed, when possible)
  10162. exports.string2buf = function (str) {
  10163. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  10164. // count binary size
  10165. for (m_pos = 0; m_pos < str_len; m_pos++) {
  10166. c = str.charCodeAt(m_pos);
  10167. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  10168. c2 = str.charCodeAt(m_pos+1);
  10169. if ((c2 & 0xfc00) === 0xdc00) {
  10170. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  10171. m_pos++;
  10172. }
  10173. }
  10174. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  10175. }
  10176. // allocate buffer
  10177. buf = new utils.Buf8(buf_len);
  10178. // convert
  10179. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  10180. c = str.charCodeAt(m_pos);
  10181. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  10182. c2 = str.charCodeAt(m_pos+1);
  10183. if ((c2 & 0xfc00) === 0xdc00) {
  10184. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  10185. m_pos++;
  10186. }
  10187. }
  10188. if (c < 0x80) {
  10189. /* one byte */
  10190. buf[i++] = c;
  10191. } else if (c < 0x800) {
  10192. /* two bytes */
  10193. buf[i++] = 0xC0 | (c >>> 6);
  10194. buf[i++] = 0x80 | (c & 0x3f);
  10195. } else if (c < 0x10000) {
  10196. /* three bytes */
  10197. buf[i++] = 0xE0 | (c >>> 12);
  10198. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  10199. buf[i++] = 0x80 | (c & 0x3f);
  10200. } else {
  10201. /* four bytes */
  10202. buf[i++] = 0xf0 | (c >>> 18);
  10203. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  10204. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  10205. buf[i++] = 0x80 | (c & 0x3f);
  10206. }
  10207. }
  10208. return buf;
  10209. };
  10210. // Helper (used in 2 places)
  10211. function buf2binstring(buf, len) {
  10212. // use fallback for big arrays to avoid stack overflow
  10213. if (len < 65537) {
  10214. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  10215. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  10216. }
  10217. }
  10218. var result = '';
  10219. for (var i=0; i < len; i++) {
  10220. result += String.fromCharCode(buf[i]);
  10221. }
  10222. return result;
  10223. }
  10224. // Convert byte array to binary string
  10225. exports.buf2binstring = function(buf) {
  10226. return buf2binstring(buf, buf.length);
  10227. };
  10228. // Convert binary string (typed, when possible)
  10229. exports.binstring2buf = function(str) {
  10230. var buf = new utils.Buf8(str.length);
  10231. for (var i=0, len=buf.length; i < len; i++) {
  10232. buf[i] = str.charCodeAt(i);
  10233. }
  10234. return buf;
  10235. };
  10236. // convert array to string
  10237. exports.buf2string = function (buf, max) {
  10238. var i, out, c, c_len;
  10239. var len = max || buf.length;
  10240. // Reserve max possible length (2 words per char)
  10241. // NB: by unknown reasons, Array is significantly faster for
  10242. // String.fromCharCode.apply than Uint16Array.
  10243. var utf16buf = new Array(len*2);
  10244. for (out=0, i=0; i<len;) {
  10245. c = buf[i++];
  10246. // quick process ascii
  10247. if (c < 0x80) { utf16buf[out++] = c; continue; }
  10248. c_len = _utf8len[c];
  10249. // skip 5 & 6 byte codes
  10250. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  10251. // apply mask on first byte
  10252. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  10253. // join the rest
  10254. while (c_len > 1 && i < len) {
  10255. c = (c << 6) | (buf[i++] & 0x3f);
  10256. c_len--;
  10257. }
  10258. // terminated by end of string?
  10259. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  10260. if (c < 0x10000) {
  10261. utf16buf[out++] = c;
  10262. } else {
  10263. c -= 0x10000;
  10264. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  10265. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  10266. }
  10267. }
  10268. return buf2binstring(utf16buf, out);
  10269. };
  10270. // Calculate max possible position in utf8 buffer,
  10271. // that will not break sequence. If that's not possible
  10272. // - (very small limits) return max size as is.
  10273. //
  10274. // buf[] - utf8 bytes array
  10275. // max - length limit (mandatory);
  10276. exports.utf8border = function(buf, max) {
  10277. var pos;
  10278. max = max || buf.length;
  10279. if (max > buf.length) { max = buf.length; }
  10280. // go back from last position, until start of sequence found
  10281. pos = max-1;
  10282. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  10283. // Fuckup - very small and broken sequence,
  10284. // return max, because we should return something anyway.
  10285. if (pos < 0) { return max; }
  10286. // If we came to start of buffer - that means vuffer is too small,
  10287. // return max too.
  10288. if (pos === 0) { return max; }
  10289. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  10290. };
  10291. },{"./common":35}],37:[function(require,module,exports){
  10292. 'use strict';
  10293. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  10294. // It doesn't worth to make additional optimizationa as in original.
  10295. // Small size is preferable.
  10296. function adler32(adler, buf, len, pos) {
  10297. var s1 = (adler & 0xffff) |0,
  10298. s2 = ((adler >>> 16) & 0xffff) |0,
  10299. n = 0;
  10300. while (len !== 0) {
  10301. // Set limit ~ twice less than 5552, to keep
  10302. // s2 in 31-bits, because we force signed ints.
  10303. // in other case %= will fail.
  10304. n = len > 2000 ? 2000 : len;
  10305. len -= n;
  10306. do {
  10307. s1 = (s1 + buf[pos++]) |0;
  10308. s2 = (s2 + s1) |0;
  10309. } while (--n);
  10310. s1 %= 65521;
  10311. s2 %= 65521;
  10312. }
  10313. return (s1 | (s2 << 16)) |0;
  10314. }
  10315. module.exports = adler32;
  10316. },{}],38:[function(require,module,exports){
  10317. module.exports = {
  10318. /* Allowed flush values; see deflate() and inflate() below for details */
  10319. Z_NO_FLUSH: 0,
  10320. Z_PARTIAL_FLUSH: 1,
  10321. Z_SYNC_FLUSH: 2,
  10322. Z_FULL_FLUSH: 3,
  10323. Z_FINISH: 4,
  10324. Z_BLOCK: 5,
  10325. Z_TREES: 6,
  10326. /* Return codes for the compression/decompression functions. Negative values
  10327. * are errors, positive values are used for special but normal events.
  10328. */
  10329. Z_OK: 0,
  10330. Z_STREAM_END: 1,
  10331. Z_NEED_DICT: 2,
  10332. Z_ERRNO: -1,
  10333. Z_STREAM_ERROR: -2,
  10334. Z_DATA_ERROR: -3,
  10335. //Z_MEM_ERROR: -4,
  10336. Z_BUF_ERROR: -5,
  10337. //Z_VERSION_ERROR: -6,
  10338. /* compression levels */
  10339. Z_NO_COMPRESSION: 0,
  10340. Z_BEST_SPEED: 1,
  10341. Z_BEST_COMPRESSION: 9,
  10342. Z_DEFAULT_COMPRESSION: -1,
  10343. Z_FILTERED: 1,
  10344. Z_HUFFMAN_ONLY: 2,
  10345. Z_RLE: 3,
  10346. Z_FIXED: 4,
  10347. Z_DEFAULT_STRATEGY: 0,
  10348. /* Possible values of the data_type field (though see inflate()) */
  10349. Z_BINARY: 0,
  10350. Z_TEXT: 1,
  10351. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  10352. Z_UNKNOWN: 2,
  10353. /* The deflate compression method */
  10354. Z_DEFLATED: 8
  10355. //Z_NULL: null // Use -1 or null inline, depending on var type
  10356. };
  10357. },{}],39:[function(require,module,exports){
  10358. 'use strict';
  10359. // Note: we can't get significant speed boost here.
  10360. // So write code to minimize size - no pregenerated tables
  10361. // and array tools dependencies.
  10362. // Use ordinary array, since untyped makes no boost here
  10363. function makeTable() {
  10364. var c, table = [];
  10365. for (var n =0; n < 256; n++) {
  10366. c = n;
  10367. for (var k =0; k < 8; k++) {
  10368. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  10369. }
  10370. table[n] = c;
  10371. }
  10372. return table;
  10373. }
  10374. // Create table on load. Just 255 signed longs. Not a problem.
  10375. var crcTable = makeTable();
  10376. function crc32(crc, buf, len, pos) {
  10377. var t = crcTable,
  10378. end = pos + len;
  10379. crc = crc ^ (-1);
  10380. for (var i = pos; i < end; i++) {
  10381. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  10382. }
  10383. return (crc ^ (-1)); // >>> 0;
  10384. }
  10385. module.exports = crc32;
  10386. },{}],40:[function(require,module,exports){
  10387. 'use strict';
  10388. var utils = require('../utils/common');
  10389. var trees = require('./trees');
  10390. var adler32 = require('./adler32');
  10391. var crc32 = require('./crc32');
  10392. var msg = require('./messages');
  10393. /* Public constants ==========================================================*/
  10394. /* ===========================================================================*/
  10395. /* Allowed flush values; see deflate() and inflate() below for details */
  10396. var Z_NO_FLUSH = 0;
  10397. var Z_PARTIAL_FLUSH = 1;
  10398. //var Z_SYNC_FLUSH = 2;
  10399. var Z_FULL_FLUSH = 3;
  10400. var Z_FINISH = 4;
  10401. var Z_BLOCK = 5;
  10402. //var Z_TREES = 6;
  10403. /* Return codes for the compression/decompression functions. Negative values
  10404. * are errors, positive values are used for special but normal events.
  10405. */
  10406. var Z_OK = 0;
  10407. var Z_STREAM_END = 1;
  10408. //var Z_NEED_DICT = 2;
  10409. //var Z_ERRNO = -1;
  10410. var Z_STREAM_ERROR = -2;
  10411. var Z_DATA_ERROR = -3;
  10412. //var Z_MEM_ERROR = -4;
  10413. var Z_BUF_ERROR = -5;
  10414. //var Z_VERSION_ERROR = -6;
  10415. /* compression levels */
  10416. //var Z_NO_COMPRESSION = 0;
  10417. //var Z_BEST_SPEED = 1;
  10418. //var Z_BEST_COMPRESSION = 9;
  10419. var Z_DEFAULT_COMPRESSION = -1;
  10420. var Z_FILTERED = 1;
  10421. var Z_HUFFMAN_ONLY = 2;
  10422. var Z_RLE = 3;
  10423. var Z_FIXED = 4;
  10424. var Z_DEFAULT_STRATEGY = 0;
  10425. /* Possible values of the data_type field (though see inflate()) */
  10426. //var Z_BINARY = 0;
  10427. //var Z_TEXT = 1;
  10428. //var Z_ASCII = 1; // = Z_TEXT
  10429. var Z_UNKNOWN = 2;
  10430. /* The deflate compression method */
  10431. var Z_DEFLATED = 8;
  10432. /*============================================================================*/
  10433. var MAX_MEM_LEVEL = 9;
  10434. /* Maximum value for memLevel in deflateInit2 */
  10435. var MAX_WBITS = 15;
  10436. /* 32K LZ77 window */
  10437. var DEF_MEM_LEVEL = 8;
  10438. var LENGTH_CODES = 29;
  10439. /* number of length codes, not counting the special END_BLOCK code */
  10440. var LITERALS = 256;
  10441. /* number of literal bytes 0..255 */
  10442. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  10443. /* number of Literal or Length codes, including the END_BLOCK code */
  10444. var D_CODES = 30;
  10445. /* number of distance codes */
  10446. var BL_CODES = 19;
  10447. /* number of codes used to transfer the bit lengths */
  10448. var HEAP_SIZE = 2*L_CODES + 1;
  10449. /* maximum heap size */
  10450. var MAX_BITS = 15;
  10451. /* All codes must not exceed MAX_BITS bits */
  10452. var MIN_MATCH = 3;
  10453. var MAX_MATCH = 258;
  10454. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  10455. var PRESET_DICT = 0x20;
  10456. var INIT_STATE = 42;
  10457. var EXTRA_STATE = 69;
  10458. var NAME_STATE = 73;
  10459. var COMMENT_STATE = 91;
  10460. var HCRC_STATE = 103;
  10461. var BUSY_STATE = 113;
  10462. var FINISH_STATE = 666;
  10463. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  10464. var BS_BLOCK_DONE = 2; /* block flush performed */
  10465. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  10466. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  10467. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  10468. function err(strm, errorCode) {
  10469. strm.msg = msg[errorCode];
  10470. return errorCode;
  10471. }
  10472. function rank(f) {
  10473. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  10474. }
  10475. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  10476. /* =========================================================================
  10477. * Flush as much pending output as possible. All deflate() output goes
  10478. * through this function so some applications may wish to modify it
  10479. * to avoid allocating a large strm->output buffer and copying into it.
  10480. * (See also read_buf()).
  10481. */
  10482. function flush_pending(strm) {
  10483. var s = strm.state;
  10484. //_tr_flush_bits(s);
  10485. var len = s.pending;
  10486. if (len > strm.avail_out) {
  10487. len = strm.avail_out;
  10488. }
  10489. if (len === 0) { return; }
  10490. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  10491. strm.next_out += len;
  10492. s.pending_out += len;
  10493. strm.total_out += len;
  10494. strm.avail_out -= len;
  10495. s.pending -= len;
  10496. if (s.pending === 0) {
  10497. s.pending_out = 0;
  10498. }
  10499. }
  10500. function flush_block_only (s, last) {
  10501. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  10502. s.block_start = s.strstart;
  10503. flush_pending(s.strm);
  10504. }
  10505. function put_byte(s, b) {
  10506. s.pending_buf[s.pending++] = b;
  10507. }
  10508. /* =========================================================================
  10509. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  10510. * IN assertion: the stream state is correct and there is enough room in
  10511. * pending_buf.
  10512. */
  10513. function putShortMSB(s, b) {
  10514. // put_byte(s, (Byte)(b >> 8));
  10515. // put_byte(s, (Byte)(b & 0xff));
  10516. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  10517. s.pending_buf[s.pending++] = b & 0xff;
  10518. }
  10519. /* ===========================================================================
  10520. * Read a new buffer from the current input stream, update the adler32
  10521. * and total number of bytes read. All deflate() input goes through
  10522. * this function so some applications may wish to modify it to avoid
  10523. * allocating a large strm->input buffer and copying from it.
  10524. * (See also flush_pending()).
  10525. */
  10526. function read_buf(strm, buf, start, size) {
  10527. var len = strm.avail_in;
  10528. if (len > size) { len = size; }
  10529. if (len === 0) { return 0; }
  10530. strm.avail_in -= len;
  10531. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  10532. if (strm.state.wrap === 1) {
  10533. strm.adler = adler32(strm.adler, buf, len, start);
  10534. }
  10535. else if (strm.state.wrap === 2) {
  10536. strm.adler = crc32(strm.adler, buf, len, start);
  10537. }
  10538. strm.next_in += len;
  10539. strm.total_in += len;
  10540. return len;
  10541. }
  10542. /* ===========================================================================
  10543. * Set match_start to the longest match starting at the given string and
  10544. * return its length. Matches shorter or equal to prev_length are discarded,
  10545. * in which case the result is equal to prev_length and match_start is
  10546. * garbage.
  10547. * IN assertions: cur_match is the head of the hash chain for the current
  10548. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  10549. * OUT assertion: the match length is not greater than s->lookahead.
  10550. */
  10551. function longest_match(s, cur_match) {
  10552. var chain_length = s.max_chain_length; /* max hash chain length */
  10553. var scan = s.strstart; /* current string */
  10554. var match; /* matched string */
  10555. var len; /* length of current match */
  10556. var best_len = s.prev_length; /* best match length so far */
  10557. var nice_match = s.nice_match; /* stop if match long enough */
  10558. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  10559. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  10560. var _win = s.window; // shortcut
  10561. var wmask = s.w_mask;
  10562. var prev = s.prev;
  10563. /* Stop when cur_match becomes <= limit. To simplify the code,
  10564. * we prevent matches with the string of window index 0.
  10565. */
  10566. var strend = s.strstart + MAX_MATCH;
  10567. var scan_end1 = _win[scan + best_len - 1];
  10568. var scan_end = _win[scan + best_len];
  10569. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  10570. * It is easy to get rid of this optimization if necessary.
  10571. */
  10572. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  10573. /* Do not waste too much time if we already have a good match: */
  10574. if (s.prev_length >= s.good_match) {
  10575. chain_length >>= 2;
  10576. }
  10577. /* Do not look for matches beyond the end of the input. This is necessary
  10578. * to make deflate deterministic.
  10579. */
  10580. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  10581. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  10582. do {
  10583. // Assert(cur_match < s->strstart, "no future");
  10584. match = cur_match;
  10585. /* Skip to next match if the match length cannot increase
  10586. * or if the match length is less than 2. Note that the checks below
  10587. * for insufficient lookahead only occur occasionally for performance
  10588. * reasons. Therefore uninitialized memory will be accessed, and
  10589. * conditional jumps will be made that depend on those values.
  10590. * However the length of the match is limited to the lookahead, so
  10591. * the output of deflate is not affected by the uninitialized values.
  10592. */
  10593. if (_win[match + best_len] !== scan_end ||
  10594. _win[match + best_len - 1] !== scan_end1 ||
  10595. _win[match] !== _win[scan] ||
  10596. _win[++match] !== _win[scan + 1]) {
  10597. continue;
  10598. }
  10599. /* The check at best_len-1 can be removed because it will be made
  10600. * again later. (This heuristic is not always a win.)
  10601. * It is not necessary to compare scan[2] and match[2] since they
  10602. * are always equal when the other bytes match, given that
  10603. * the hash keys are equal and that HASH_BITS >= 8.
  10604. */
  10605. scan += 2;
  10606. match++;
  10607. // Assert(*scan == *match, "match[2]?");
  10608. /* We check for insufficient lookahead only every 8th comparison;
  10609. * the 256th check will be made at strstart+258.
  10610. */
  10611. do {
  10612. /*jshint noempty:false*/
  10613. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  10614. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  10615. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  10616. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  10617. scan < strend);
  10618. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  10619. len = MAX_MATCH - (strend - scan);
  10620. scan = strend - MAX_MATCH;
  10621. if (len > best_len) {
  10622. s.match_start = cur_match;
  10623. best_len = len;
  10624. if (len >= nice_match) {
  10625. break;
  10626. }
  10627. scan_end1 = _win[scan + best_len - 1];
  10628. scan_end = _win[scan + best_len];
  10629. }
  10630. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  10631. if (best_len <= s.lookahead) {
  10632. return best_len;
  10633. }
  10634. return s.lookahead;
  10635. }
  10636. /* ===========================================================================
  10637. * Fill the window when the lookahead becomes insufficient.
  10638. * Updates strstart and lookahead.
  10639. *
  10640. * IN assertion: lookahead < MIN_LOOKAHEAD
  10641. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  10642. * At least one byte has been read, or avail_in == 0; reads are
  10643. * performed for at least two bytes (required for the zip translate_eol
  10644. * option -- not supported here).
  10645. */
  10646. function fill_window(s) {
  10647. var _w_size = s.w_size;
  10648. var p, n, m, more, str;
  10649. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  10650. do {
  10651. more = s.window_size - s.lookahead - s.strstart;
  10652. // JS ints have 32 bit, block below not needed
  10653. /* Deal with !@#$% 64K limit: */
  10654. //if (sizeof(int) <= 2) {
  10655. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  10656. // more = wsize;
  10657. //
  10658. // } else if (more == (unsigned)(-1)) {
  10659. // /* Very unlikely, but possible on 16 bit machine if
  10660. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  10661. // */
  10662. // more--;
  10663. // }
  10664. //}
  10665. /* If the window is almost full and there is insufficient lookahead,
  10666. * move the upper half to the lower one to make room in the upper half.
  10667. */
  10668. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  10669. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  10670. s.match_start -= _w_size;
  10671. s.strstart -= _w_size;
  10672. /* we now have strstart >= MAX_DIST */
  10673. s.block_start -= _w_size;
  10674. /* Slide the hash table (could be avoided with 32 bit values
  10675. at the expense of memory usage). We slide even when level == 0
  10676. to keep the hash table consistent if we switch back to level > 0
  10677. later. (Using level 0 permanently is not an optimal usage of
  10678. zlib, so we don't care about this pathological case.)
  10679. */
  10680. n = s.hash_size;
  10681. p = n;
  10682. do {
  10683. m = s.head[--p];
  10684. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  10685. } while (--n);
  10686. n = _w_size;
  10687. p = n;
  10688. do {
  10689. m = s.prev[--p];
  10690. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  10691. /* If n is not on any hash chain, prev[n] is garbage but
  10692. * its value will never be used.
  10693. */
  10694. } while (--n);
  10695. more += _w_size;
  10696. }
  10697. if (s.strm.avail_in === 0) {
  10698. break;
  10699. }
  10700. /* If there was no sliding:
  10701. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  10702. * more == window_size - lookahead - strstart
  10703. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  10704. * => more >= window_size - 2*WSIZE + 2
  10705. * In the BIG_MEM or MMAP case (not yet supported),
  10706. * window_size == input_size + MIN_LOOKAHEAD &&
  10707. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  10708. * Otherwise, window_size == 2*WSIZE so more >= 2.
  10709. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  10710. */
  10711. //Assert(more >= 2, "more < 2");
  10712. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  10713. s.lookahead += n;
  10714. /* Initialize the hash value now that we have some input: */
  10715. if (s.lookahead + s.insert >= MIN_MATCH) {
  10716. str = s.strstart - s.insert;
  10717. s.ins_h = s.window[str];
  10718. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  10719. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  10720. //#if MIN_MATCH != 3
  10721. // Call update_hash() MIN_MATCH-3 more times
  10722. //#endif
  10723. while (s.insert) {
  10724. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  10725. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  10726. s.prev[str & s.w_mask] = s.head[s.ins_h];
  10727. s.head[s.ins_h] = str;
  10728. str++;
  10729. s.insert--;
  10730. if (s.lookahead + s.insert < MIN_MATCH) {
  10731. break;
  10732. }
  10733. }
  10734. }
  10735. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  10736. * but this is not important since only literal bytes will be emitted.
  10737. */
  10738. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  10739. /* If the WIN_INIT bytes after the end of the current data have never been
  10740. * written, then zero those bytes in order to avoid memory check reports of
  10741. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  10742. * the longest match routines. Update the high water mark for the next
  10743. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  10744. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  10745. */
  10746. // if (s.high_water < s.window_size) {
  10747. // var curr = s.strstart + s.lookahead;
  10748. // var init = 0;
  10749. //
  10750. // if (s.high_water < curr) {
  10751. // /* Previous high water mark below current data -- zero WIN_INIT
  10752. // * bytes or up to end of window, whichever is less.
  10753. // */
  10754. // init = s.window_size - curr;
  10755. // if (init > WIN_INIT)
  10756. // init = WIN_INIT;
  10757. // zmemzero(s->window + curr, (unsigned)init);
  10758. // s->high_water = curr + init;
  10759. // }
  10760. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  10761. // /* High water mark at or above current data, but below current data
  10762. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  10763. // * to end of window, whichever is less.
  10764. // */
  10765. // init = (ulg)curr + WIN_INIT - s->high_water;
  10766. // if (init > s->window_size - s->high_water)
  10767. // init = s->window_size - s->high_water;
  10768. // zmemzero(s->window + s->high_water, (unsigned)init);
  10769. // s->high_water += init;
  10770. // }
  10771. // }
  10772. //
  10773. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  10774. // "not enough room for search");
  10775. }
  10776. /* ===========================================================================
  10777. * Copy without compression as much as possible from the input stream, return
  10778. * the current block state.
  10779. * This function does not insert new strings in the dictionary since
  10780. * uncompressible data is probably not useful. This function is used
  10781. * only for the level=0 compression option.
  10782. * NOTE: this function should be optimized to avoid extra copying from
  10783. * window to pending_buf.
  10784. */
  10785. function deflate_stored(s, flush) {
  10786. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  10787. * to pending_buf_size, and each stored block has a 5 byte header:
  10788. */
  10789. var max_block_size = 0xffff;
  10790. if (max_block_size > s.pending_buf_size - 5) {
  10791. max_block_size = s.pending_buf_size - 5;
  10792. }
  10793. /* Copy as much as possible from input to output: */
  10794. for (;;) {
  10795. /* Fill the window as much as possible: */
  10796. if (s.lookahead <= 1) {
  10797. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  10798. // s->block_start >= (long)s->w_size, "slide too late");
  10799. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  10800. // s.block_start >= s.w_size)) {
  10801. // throw new Error("slide too late");
  10802. // }
  10803. fill_window(s);
  10804. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  10805. return BS_NEED_MORE;
  10806. }
  10807. if (s.lookahead === 0) {
  10808. break;
  10809. }
  10810. /* flush the current block */
  10811. }
  10812. //Assert(s->block_start >= 0L, "block gone");
  10813. // if (s.block_start < 0) throw new Error("block gone");
  10814. s.strstart += s.lookahead;
  10815. s.lookahead = 0;
  10816. /* Emit a stored block if pending_buf will be full: */
  10817. var max_start = s.block_start + max_block_size;
  10818. if (s.strstart === 0 || s.strstart >= max_start) {
  10819. /* strstart == 0 is possible when wraparound on 16-bit machine */
  10820. s.lookahead = s.strstart - max_start;
  10821. s.strstart = max_start;
  10822. /*** FLUSH_BLOCK(s, 0); ***/
  10823. flush_block_only(s, false);
  10824. if (s.strm.avail_out === 0) {
  10825. return BS_NEED_MORE;
  10826. }
  10827. /***/
  10828. }
  10829. /* Flush if we may have to slide, otherwise block_start may become
  10830. * negative and the data will be gone:
  10831. */
  10832. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  10833. /*** FLUSH_BLOCK(s, 0); ***/
  10834. flush_block_only(s, false);
  10835. if (s.strm.avail_out === 0) {
  10836. return BS_NEED_MORE;
  10837. }
  10838. /***/
  10839. }
  10840. }
  10841. s.insert = 0;
  10842. if (flush === Z_FINISH) {
  10843. /*** FLUSH_BLOCK(s, 1); ***/
  10844. flush_block_only(s, true);
  10845. if (s.strm.avail_out === 0) {
  10846. return BS_FINISH_STARTED;
  10847. }
  10848. /***/
  10849. return BS_FINISH_DONE;
  10850. }
  10851. if (s.strstart > s.block_start) {
  10852. /*** FLUSH_BLOCK(s, 0); ***/
  10853. flush_block_only(s, false);
  10854. if (s.strm.avail_out === 0) {
  10855. return BS_NEED_MORE;
  10856. }
  10857. /***/
  10858. }
  10859. return BS_NEED_MORE;
  10860. }
  10861. /* ===========================================================================
  10862. * Compress as much as possible from the input stream, return the current
  10863. * block state.
  10864. * This function does not perform lazy evaluation of matches and inserts
  10865. * new strings in the dictionary only for unmatched strings or for short
  10866. * matches. It is used only for the fast compression options.
  10867. */
  10868. function deflate_fast(s, flush) {
  10869. var hash_head; /* head of the hash chain */
  10870. var bflush; /* set if current block must be flushed */
  10871. for (;;) {
  10872. /* Make sure that we always have enough lookahead, except
  10873. * at the end of the input file. We need MAX_MATCH bytes
  10874. * for the next match, plus MIN_MATCH bytes to insert the
  10875. * string following the next match.
  10876. */
  10877. if (s.lookahead < MIN_LOOKAHEAD) {
  10878. fill_window(s);
  10879. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  10880. return BS_NEED_MORE;
  10881. }
  10882. if (s.lookahead === 0) {
  10883. break; /* flush the current block */
  10884. }
  10885. }
  10886. /* Insert the string window[strstart .. strstart+2] in the
  10887. * dictionary, and set hash_head to the head of the hash chain:
  10888. */
  10889. hash_head = 0/*NIL*/;
  10890. if (s.lookahead >= MIN_MATCH) {
  10891. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  10892. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  10893. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  10894. s.head[s.ins_h] = s.strstart;
  10895. /***/
  10896. }
  10897. /* Find the longest match, discarding those <= prev_length.
  10898. * At this point we have always match_length < MIN_MATCH
  10899. */
  10900. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  10901. /* To simplify the code, we prevent matches with the string
  10902. * of window index 0 (in particular we have to avoid a match
  10903. * of the string with itself at the start of the input file).
  10904. */
  10905. s.match_length = longest_match(s, hash_head);
  10906. /* longest_match() sets match_start */
  10907. }
  10908. if (s.match_length >= MIN_MATCH) {
  10909. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  10910. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  10911. s.match_length - MIN_MATCH, bflush); ***/
  10912. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  10913. s.lookahead -= s.match_length;
  10914. /* Insert new strings in the hash table only if the match length
  10915. * is not too large. This saves time but degrades compression.
  10916. */
  10917. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  10918. s.match_length--; /* string at strstart already in table */
  10919. do {
  10920. s.strstart++;
  10921. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  10922. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  10923. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  10924. s.head[s.ins_h] = s.strstart;
  10925. /***/
  10926. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  10927. * always MIN_MATCH bytes ahead.
  10928. */
  10929. } while (--s.match_length !== 0);
  10930. s.strstart++;
  10931. } else
  10932. {
  10933. s.strstart += s.match_length;
  10934. s.match_length = 0;
  10935. s.ins_h = s.window[s.strstart];
  10936. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  10937. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  10938. //#if MIN_MATCH != 3
  10939. // Call UPDATE_HASH() MIN_MATCH-3 more times
  10940. //#endif
  10941. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  10942. * matter since it will be recomputed at next deflate call.
  10943. */
  10944. }
  10945. } else {
  10946. /* No match, output a literal byte */
  10947. //Tracevv((stderr,"%c", s.window[s.strstart]));
  10948. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  10949. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  10950. s.lookahead--;
  10951. s.strstart++;
  10952. }
  10953. if (bflush) {
  10954. /*** FLUSH_BLOCK(s, 0); ***/
  10955. flush_block_only(s, false);
  10956. if (s.strm.avail_out === 0) {
  10957. return BS_NEED_MORE;
  10958. }
  10959. /***/
  10960. }
  10961. }
  10962. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  10963. if (flush === Z_FINISH) {
  10964. /*** FLUSH_BLOCK(s, 1); ***/
  10965. flush_block_only(s, true);
  10966. if (s.strm.avail_out === 0) {
  10967. return BS_FINISH_STARTED;
  10968. }
  10969. /***/
  10970. return BS_FINISH_DONE;
  10971. }
  10972. if (s.last_lit) {
  10973. /*** FLUSH_BLOCK(s, 0); ***/
  10974. flush_block_only(s, false);
  10975. if (s.strm.avail_out === 0) {
  10976. return BS_NEED_MORE;
  10977. }
  10978. /***/
  10979. }
  10980. return BS_BLOCK_DONE;
  10981. }
  10982. /* ===========================================================================
  10983. * Same as above, but achieves better compression. We use a lazy
  10984. * evaluation for matches: a match is finally adopted only if there is
  10985. * no better match at the next window position.
  10986. */
  10987. function deflate_slow(s, flush) {
  10988. var hash_head; /* head of hash chain */
  10989. var bflush; /* set if current block must be flushed */
  10990. var max_insert;
  10991. /* Process the input block. */
  10992. for (;;) {
  10993. /* Make sure that we always have enough lookahead, except
  10994. * at the end of the input file. We need MAX_MATCH bytes
  10995. * for the next match, plus MIN_MATCH bytes to insert the
  10996. * string following the next match.
  10997. */
  10998. if (s.lookahead < MIN_LOOKAHEAD) {
  10999. fill_window(s);
  11000. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  11001. return BS_NEED_MORE;
  11002. }
  11003. if (s.lookahead === 0) { break; } /* flush the current block */
  11004. }
  11005. /* Insert the string window[strstart .. strstart+2] in the
  11006. * dictionary, and set hash_head to the head of the hash chain:
  11007. */
  11008. hash_head = 0/*NIL*/;
  11009. if (s.lookahead >= MIN_MATCH) {
  11010. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11011. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11012. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11013. s.head[s.ins_h] = s.strstart;
  11014. /***/
  11015. }
  11016. /* Find the longest match, discarding those <= prev_length.
  11017. */
  11018. s.prev_length = s.match_length;
  11019. s.prev_match = s.match_start;
  11020. s.match_length = MIN_MATCH-1;
  11021. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  11022. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  11023. /* To simplify the code, we prevent matches with the string
  11024. * of window index 0 (in particular we have to avoid a match
  11025. * of the string with itself at the start of the input file).
  11026. */
  11027. s.match_length = longest_match(s, hash_head);
  11028. /* longest_match() sets match_start */
  11029. if (s.match_length <= 5 &&
  11030. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  11031. /* If prev_match is also MIN_MATCH, match_start is garbage
  11032. * but we will ignore the current match anyway.
  11033. */
  11034. s.match_length = MIN_MATCH-1;
  11035. }
  11036. }
  11037. /* If there was a match at the previous step and the current
  11038. * match is not better, output the previous match:
  11039. */
  11040. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  11041. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  11042. /* Do not insert strings in hash table beyond this. */
  11043. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  11044. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  11045. s.prev_length - MIN_MATCH, bflush);***/
  11046. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  11047. /* Insert in hash table all strings up to the end of the match.
  11048. * strstart-1 and strstart are already inserted. If there is not
  11049. * enough lookahead, the last two strings are not inserted in
  11050. * the hash table.
  11051. */
  11052. s.lookahead -= s.prev_length-1;
  11053. s.prev_length -= 2;
  11054. do {
  11055. if (++s.strstart <= max_insert) {
  11056. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  11057. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  11058. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  11059. s.head[s.ins_h] = s.strstart;
  11060. /***/
  11061. }
  11062. } while (--s.prev_length !== 0);
  11063. s.match_available = 0;
  11064. s.match_length = MIN_MATCH-1;
  11065. s.strstart++;
  11066. if (bflush) {
  11067. /*** FLUSH_BLOCK(s, 0); ***/
  11068. flush_block_only(s, false);
  11069. if (s.strm.avail_out === 0) {
  11070. return BS_NEED_MORE;
  11071. }
  11072. /***/
  11073. }
  11074. } else if (s.match_available) {
  11075. /* If there was no match at the previous position, output a
  11076. * single literal. If there was a match but the current match
  11077. * is longer, truncate the previous match to a single literal.
  11078. */
  11079. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  11080. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  11081. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  11082. if (bflush) {
  11083. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  11084. flush_block_only(s, false);
  11085. /***/
  11086. }
  11087. s.strstart++;
  11088. s.lookahead--;
  11089. if (s.strm.avail_out === 0) {
  11090. return BS_NEED_MORE;
  11091. }
  11092. } else {
  11093. /* There is no previous match to compare with, wait for
  11094. * the next step to decide.
  11095. */
  11096. s.match_available = 1;
  11097. s.strstart++;
  11098. s.lookahead--;
  11099. }
  11100. }
  11101. //Assert (flush != Z_NO_FLUSH, "no flush?");
  11102. if (s.match_available) {
  11103. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  11104. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  11105. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  11106. s.match_available = 0;
  11107. }
  11108. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  11109. if (flush === Z_FINISH) {
  11110. /*** FLUSH_BLOCK(s, 1); ***/
  11111. flush_block_only(s, true);
  11112. if (s.strm.avail_out === 0) {
  11113. return BS_FINISH_STARTED;
  11114. }
  11115. /***/
  11116. return BS_FINISH_DONE;
  11117. }
  11118. if (s.last_lit) {
  11119. /*** FLUSH_BLOCK(s, 0); ***/
  11120. flush_block_only(s, false);
  11121. if (s.strm.avail_out === 0) {
  11122. return BS_NEED_MORE;
  11123. }
  11124. /***/
  11125. }
  11126. return BS_BLOCK_DONE;
  11127. }
  11128. /* ===========================================================================
  11129. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  11130. * one. Do not maintain a hash table. (It will be regenerated if this run of
  11131. * deflate switches away from Z_RLE.)
  11132. */
  11133. function deflate_rle(s, flush) {
  11134. var bflush; /* set if current block must be flushed */
  11135. var prev; /* byte at distance one to match */
  11136. var scan, strend; /* scan goes up to strend for length of run */
  11137. var _win = s.window;
  11138. for (;;) {
  11139. /* Make sure that we always have enough lookahead, except
  11140. * at the end of the input file. We need MAX_MATCH bytes
  11141. * for the longest run, plus one for the unrolled loop.
  11142. */
  11143. if (s.lookahead <= MAX_MATCH) {
  11144. fill_window(s);
  11145. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  11146. return BS_NEED_MORE;
  11147. }
  11148. if (s.lookahead === 0) { break; } /* flush the current block */
  11149. }
  11150. /* See how many times the previous byte repeats */
  11151. s.match_length = 0;
  11152. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  11153. scan = s.strstart - 1;
  11154. prev = _win[scan];
  11155. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  11156. strend = s.strstart + MAX_MATCH;
  11157. do {
  11158. /*jshint noempty:false*/
  11159. } while (prev === _win[++scan] && prev === _win[++scan] &&
  11160. prev === _win[++scan] && prev === _win[++scan] &&
  11161. prev === _win[++scan] && prev === _win[++scan] &&
  11162. prev === _win[++scan] && prev === _win[++scan] &&
  11163. scan < strend);
  11164. s.match_length = MAX_MATCH - (strend - scan);
  11165. if (s.match_length > s.lookahead) {
  11166. s.match_length = s.lookahead;
  11167. }
  11168. }
  11169. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  11170. }
  11171. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  11172. if (s.match_length >= MIN_MATCH) {
  11173. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  11174. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  11175. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  11176. s.lookahead -= s.match_length;
  11177. s.strstart += s.match_length;
  11178. s.match_length = 0;
  11179. } else {
  11180. /* No match, output a literal byte */
  11181. //Tracevv((stderr,"%c", s->window[s->strstart]));
  11182. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11183. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11184. s.lookahead--;
  11185. s.strstart++;
  11186. }
  11187. if (bflush) {
  11188. /*** FLUSH_BLOCK(s, 0); ***/
  11189. flush_block_only(s, false);
  11190. if (s.strm.avail_out === 0) {
  11191. return BS_NEED_MORE;
  11192. }
  11193. /***/
  11194. }
  11195. }
  11196. s.insert = 0;
  11197. if (flush === Z_FINISH) {
  11198. /*** FLUSH_BLOCK(s, 1); ***/
  11199. flush_block_only(s, true);
  11200. if (s.strm.avail_out === 0) {
  11201. return BS_FINISH_STARTED;
  11202. }
  11203. /***/
  11204. return BS_FINISH_DONE;
  11205. }
  11206. if (s.last_lit) {
  11207. /*** FLUSH_BLOCK(s, 0); ***/
  11208. flush_block_only(s, false);
  11209. if (s.strm.avail_out === 0) {
  11210. return BS_NEED_MORE;
  11211. }
  11212. /***/
  11213. }
  11214. return BS_BLOCK_DONE;
  11215. }
  11216. /* ===========================================================================
  11217. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  11218. * (It will be regenerated if this run of deflate switches away from Huffman.)
  11219. */
  11220. function deflate_huff(s, flush) {
  11221. var bflush; /* set if current block must be flushed */
  11222. for (;;) {
  11223. /* Make sure that we have a literal to write. */
  11224. if (s.lookahead === 0) {
  11225. fill_window(s);
  11226. if (s.lookahead === 0) {
  11227. if (flush === Z_NO_FLUSH) {
  11228. return BS_NEED_MORE;
  11229. }
  11230. break; /* flush the current block */
  11231. }
  11232. }
  11233. /* Output a literal byte */
  11234. s.match_length = 0;
  11235. //Tracevv((stderr,"%c", s->window[s->strstart]));
  11236. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  11237. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  11238. s.lookahead--;
  11239. s.strstart++;
  11240. if (bflush) {
  11241. /*** FLUSH_BLOCK(s, 0); ***/
  11242. flush_block_only(s, false);
  11243. if (s.strm.avail_out === 0) {
  11244. return BS_NEED_MORE;
  11245. }
  11246. /***/
  11247. }
  11248. }
  11249. s.insert = 0;
  11250. if (flush === Z_FINISH) {
  11251. /*** FLUSH_BLOCK(s, 1); ***/
  11252. flush_block_only(s, true);
  11253. if (s.strm.avail_out === 0) {
  11254. return BS_FINISH_STARTED;
  11255. }
  11256. /***/
  11257. return BS_FINISH_DONE;
  11258. }
  11259. if (s.last_lit) {
  11260. /*** FLUSH_BLOCK(s, 0); ***/
  11261. flush_block_only(s, false);
  11262. if (s.strm.avail_out === 0) {
  11263. return BS_NEED_MORE;
  11264. }
  11265. /***/
  11266. }
  11267. return BS_BLOCK_DONE;
  11268. }
  11269. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  11270. * the desired pack level (0..9). The values given below have been tuned to
  11271. * exclude worst case performance for pathological files. Better values may be
  11272. * found for specific files.
  11273. */
  11274. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  11275. this.good_length = good_length;
  11276. this.max_lazy = max_lazy;
  11277. this.nice_length = nice_length;
  11278. this.max_chain = max_chain;
  11279. this.func = func;
  11280. };
  11281. var configuration_table;
  11282. configuration_table = [
  11283. /* good lazy nice chain */
  11284. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  11285. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  11286. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  11287. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  11288. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  11289. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  11290. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  11291. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  11292. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  11293. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  11294. ];
  11295. /* ===========================================================================
  11296. * Initialize the "longest match" routines for a new zlib stream
  11297. */
  11298. function lm_init(s) {
  11299. s.window_size = 2 * s.w_size;
  11300. /*** CLEAR_HASH(s); ***/
  11301. zero(s.head); // Fill with NIL (= 0);
  11302. /* Set the default configuration parameters:
  11303. */
  11304. s.max_lazy_match = configuration_table[s.level].max_lazy;
  11305. s.good_match = configuration_table[s.level].good_length;
  11306. s.nice_match = configuration_table[s.level].nice_length;
  11307. s.max_chain_length = configuration_table[s.level].max_chain;
  11308. s.strstart = 0;
  11309. s.block_start = 0;
  11310. s.lookahead = 0;
  11311. s.insert = 0;
  11312. s.match_length = s.prev_length = MIN_MATCH - 1;
  11313. s.match_available = 0;
  11314. s.ins_h = 0;
  11315. }
  11316. function DeflateState() {
  11317. this.strm = null; /* pointer back to this zlib stream */
  11318. this.status = 0; /* as the name implies */
  11319. this.pending_buf = null; /* output still pending */
  11320. this.pending_buf_size = 0; /* size of pending_buf */
  11321. this.pending_out = 0; /* next pending byte to output to the stream */
  11322. this.pending = 0; /* nb of bytes in the pending buffer */
  11323. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  11324. this.gzhead = null; /* gzip header information to write */
  11325. this.gzindex = 0; /* where in extra, name, or comment */
  11326. this.method = Z_DEFLATED; /* can only be DEFLATED */
  11327. this.last_flush = -1; /* value of flush param for previous deflate call */
  11328. this.w_size = 0; /* LZ77 window size (32K by default) */
  11329. this.w_bits = 0; /* log2(w_size) (8..16) */
  11330. this.w_mask = 0; /* w_size - 1 */
  11331. this.window = null;
  11332. /* Sliding window. Input bytes are read into the second half of the window,
  11333. * and move to the first half later to keep a dictionary of at least wSize
  11334. * bytes. With this organization, matches are limited to a distance of
  11335. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  11336. * performed with a length multiple of the block size.
  11337. */
  11338. this.window_size = 0;
  11339. /* Actual size of window: 2*wSize, except when the user input buffer
  11340. * is directly used as sliding window.
  11341. */
  11342. this.prev = null;
  11343. /* Link to older string with same hash index. To limit the size of this
  11344. * array to 64K, this link is maintained only for the last 32K strings.
  11345. * An index in this array is thus a window index modulo 32K.
  11346. */
  11347. this.head = null; /* Heads of the hash chains or NIL. */
  11348. this.ins_h = 0; /* hash index of string to be inserted */
  11349. this.hash_size = 0; /* number of elements in hash table */
  11350. this.hash_bits = 0; /* log2(hash_size) */
  11351. this.hash_mask = 0; /* hash_size-1 */
  11352. this.hash_shift = 0;
  11353. /* Number of bits by which ins_h must be shifted at each input
  11354. * step. It must be such that after MIN_MATCH steps, the oldest
  11355. * byte no longer takes part in the hash key, that is:
  11356. * hash_shift * MIN_MATCH >= hash_bits
  11357. */
  11358. this.block_start = 0;
  11359. /* Window position at the beginning of the current output block. Gets
  11360. * negative when the window is moved backwards.
  11361. */
  11362. this.match_length = 0; /* length of best match */
  11363. this.prev_match = 0; /* previous match */
  11364. this.match_available = 0; /* set if previous match exists */
  11365. this.strstart = 0; /* start of string to insert */
  11366. this.match_start = 0; /* start of matching string */
  11367. this.lookahead = 0; /* number of valid bytes ahead in window */
  11368. this.prev_length = 0;
  11369. /* Length of the best match at previous step. Matches not greater than this
  11370. * are discarded. This is used in the lazy match evaluation.
  11371. */
  11372. this.max_chain_length = 0;
  11373. /* To speed up deflation, hash chains are never searched beyond this
  11374. * length. A higher limit improves compression ratio but degrades the
  11375. * speed.
  11376. */
  11377. this.max_lazy_match = 0;
  11378. /* Attempt to find a better match only when the current match is strictly
  11379. * smaller than this value. This mechanism is used only for compression
  11380. * levels >= 4.
  11381. */
  11382. // That's alias to max_lazy_match, don't use directly
  11383. //this.max_insert_length = 0;
  11384. /* Insert new strings in the hash table only if the match length is not
  11385. * greater than this length. This saves time but degrades compression.
  11386. * max_insert_length is used only for compression levels <= 3.
  11387. */
  11388. this.level = 0; /* compression level (1..9) */
  11389. this.strategy = 0; /* favor or force Huffman coding*/
  11390. this.good_match = 0;
  11391. /* Use a faster search when the previous match is longer than this */
  11392. this.nice_match = 0; /* Stop searching when current match exceeds this */
  11393. /* used by trees.c: */
  11394. /* Didn't use ct_data typedef below to suppress compiler warning */
  11395. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  11396. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  11397. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  11398. // Use flat array of DOUBLE size, with interleaved fata,
  11399. // because JS does not support effective
  11400. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  11401. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  11402. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  11403. zero(this.dyn_ltree);
  11404. zero(this.dyn_dtree);
  11405. zero(this.bl_tree);
  11406. this.l_desc = null; /* desc. for literal tree */
  11407. this.d_desc = null; /* desc. for distance tree */
  11408. this.bl_desc = null; /* desc. for bit length tree */
  11409. //ush bl_count[MAX_BITS+1];
  11410. this.bl_count = new utils.Buf16(MAX_BITS+1);
  11411. /* number of codes at each bit length for an optimal tree */
  11412. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  11413. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  11414. zero(this.heap);
  11415. this.heap_len = 0; /* number of elements in the heap */
  11416. this.heap_max = 0; /* element of largest frequency */
  11417. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  11418. * The same heap array is used to build all trees.
  11419. */
  11420. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  11421. zero(this.depth);
  11422. /* Depth of each subtree used as tie breaker for trees of equal frequency
  11423. */
  11424. this.l_buf = 0; /* buffer index for literals or lengths */
  11425. this.lit_bufsize = 0;
  11426. /* Size of match buffer for literals/lengths. There are 4 reasons for
  11427. * limiting lit_bufsize to 64K:
  11428. * - frequencies can be kept in 16 bit counters
  11429. * - if compression is not successful for the first block, all input
  11430. * data is still in the window so we can still emit a stored block even
  11431. * when input comes from standard input. (This can also be done for
  11432. * all blocks if lit_bufsize is not greater than 32K.)
  11433. * - if compression is not successful for a file smaller than 64K, we can
  11434. * even emit a stored file instead of a stored block (saving 5 bytes).
  11435. * This is applicable only for zip (not gzip or zlib).
  11436. * - creating new Huffman trees less frequently may not provide fast
  11437. * adaptation to changes in the input data statistics. (Take for
  11438. * example a binary file with poorly compressible code followed by
  11439. * a highly compressible string table.) Smaller buffer sizes give
  11440. * fast adaptation but have of course the overhead of transmitting
  11441. * trees more frequently.
  11442. * - I can't count above 4
  11443. */
  11444. this.last_lit = 0; /* running index in l_buf */
  11445. this.d_buf = 0;
  11446. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  11447. * the same number of elements. To use different lengths, an extra flag
  11448. * array would be necessary.
  11449. */
  11450. this.opt_len = 0; /* bit length of current block with optimal trees */
  11451. this.static_len = 0; /* bit length of current block with static trees */
  11452. this.matches = 0; /* number of string matches in current block */
  11453. this.insert = 0; /* bytes at end of window left to insert */
  11454. this.bi_buf = 0;
  11455. /* Output buffer. bits are inserted starting at the bottom (least
  11456. * significant bits).
  11457. */
  11458. this.bi_valid = 0;
  11459. /* Number of valid bits in bi_buf. All bits above the last valid bit
  11460. * are always zero.
  11461. */
  11462. // Used for window memory init. We safely ignore it for JS. That makes
  11463. // sense only for pointers and memory check tools.
  11464. //this.high_water = 0;
  11465. /* High water mark offset in window for initialized bytes -- bytes above
  11466. * this are set to zero in order to avoid memory check warnings when
  11467. * longest match routines access bytes past the input. This is then
  11468. * updated to the new high water mark.
  11469. */
  11470. }
  11471. function deflateResetKeep(strm) {
  11472. var s;
  11473. if (!strm || !strm.state) {
  11474. return err(strm, Z_STREAM_ERROR);
  11475. }
  11476. strm.total_in = strm.total_out = 0;
  11477. strm.data_type = Z_UNKNOWN;
  11478. s = strm.state;
  11479. s.pending = 0;
  11480. s.pending_out = 0;
  11481. if (s.wrap < 0) {
  11482. s.wrap = -s.wrap;
  11483. /* was made negative by deflate(..., Z_FINISH); */
  11484. }
  11485. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  11486. strm.adler = (s.wrap === 2) ?
  11487. 0 // crc32(0, Z_NULL, 0)
  11488. :
  11489. 1; // adler32(0, Z_NULL, 0)
  11490. s.last_flush = Z_NO_FLUSH;
  11491. trees._tr_init(s);
  11492. return Z_OK;
  11493. }
  11494. function deflateReset(strm) {
  11495. var ret = deflateResetKeep(strm);
  11496. if (ret === Z_OK) {
  11497. lm_init(strm.state);
  11498. }
  11499. return ret;
  11500. }
  11501. function deflateSetHeader(strm, head) {
  11502. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  11503. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  11504. strm.state.gzhead = head;
  11505. return Z_OK;
  11506. }
  11507. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  11508. if (!strm) { // === Z_NULL
  11509. return Z_STREAM_ERROR;
  11510. }
  11511. var wrap = 1;
  11512. if (level === Z_DEFAULT_COMPRESSION) {
  11513. level = 6;
  11514. }
  11515. if (windowBits < 0) { /* suppress zlib wrapper */
  11516. wrap = 0;
  11517. windowBits = -windowBits;
  11518. }
  11519. else if (windowBits > 15) {
  11520. wrap = 2; /* write gzip wrapper instead */
  11521. windowBits -= 16;
  11522. }
  11523. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  11524. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  11525. strategy < 0 || strategy > Z_FIXED) {
  11526. return err(strm, Z_STREAM_ERROR);
  11527. }
  11528. if (windowBits === 8) {
  11529. windowBits = 9;
  11530. }
  11531. /* until 256-byte window bug fixed */
  11532. var s = new DeflateState();
  11533. strm.state = s;
  11534. s.strm = strm;
  11535. s.wrap = wrap;
  11536. s.gzhead = null;
  11537. s.w_bits = windowBits;
  11538. s.w_size = 1 << s.w_bits;
  11539. s.w_mask = s.w_size - 1;
  11540. s.hash_bits = memLevel + 7;
  11541. s.hash_size = 1 << s.hash_bits;
  11542. s.hash_mask = s.hash_size - 1;
  11543. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  11544. s.window = new utils.Buf8(s.w_size * 2);
  11545. s.head = new utils.Buf16(s.hash_size);
  11546. s.prev = new utils.Buf16(s.w_size);
  11547. // Don't need mem init magic for JS.
  11548. //s.high_water = 0; /* nothing written to s->window yet */
  11549. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  11550. s.pending_buf_size = s.lit_bufsize * 4;
  11551. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  11552. s.d_buf = s.lit_bufsize >> 1;
  11553. s.l_buf = (1 + 2) * s.lit_bufsize;
  11554. s.level = level;
  11555. s.strategy = strategy;
  11556. s.method = method;
  11557. return deflateReset(strm);
  11558. }
  11559. function deflateInit(strm, level) {
  11560. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  11561. }
  11562. function deflate(strm, flush) {
  11563. var old_flush, s;
  11564. var beg, val; // for gzip header write only
  11565. if (!strm || !strm.state ||
  11566. flush > Z_BLOCK || flush < 0) {
  11567. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  11568. }
  11569. s = strm.state;
  11570. if (!strm.output ||
  11571. (!strm.input && strm.avail_in !== 0) ||
  11572. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  11573. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  11574. }
  11575. s.strm = strm; /* just in case */
  11576. old_flush = s.last_flush;
  11577. s.last_flush = flush;
  11578. /* Write the header */
  11579. if (s.status === INIT_STATE) {
  11580. if (s.wrap === 2) { // GZIP header
  11581. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  11582. put_byte(s, 31);
  11583. put_byte(s, 139);
  11584. put_byte(s, 8);
  11585. if (!s.gzhead) { // s->gzhead == Z_NULL
  11586. put_byte(s, 0);
  11587. put_byte(s, 0);
  11588. put_byte(s, 0);
  11589. put_byte(s, 0);
  11590. put_byte(s, 0);
  11591. put_byte(s, s.level === 9 ? 2 :
  11592. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  11593. 4 : 0));
  11594. put_byte(s, OS_CODE);
  11595. s.status = BUSY_STATE;
  11596. }
  11597. else {
  11598. put_byte(s, (s.gzhead.text ? 1 : 0) +
  11599. (s.gzhead.hcrc ? 2 : 0) +
  11600. (!s.gzhead.extra ? 0 : 4) +
  11601. (!s.gzhead.name ? 0 : 8) +
  11602. (!s.gzhead.comment ? 0 : 16)
  11603. );
  11604. put_byte(s, s.gzhead.time & 0xff);
  11605. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  11606. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  11607. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  11608. put_byte(s, s.level === 9 ? 2 :
  11609. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  11610. 4 : 0));
  11611. put_byte(s, s.gzhead.os & 0xff);
  11612. if (s.gzhead.extra && s.gzhead.extra.length) {
  11613. put_byte(s, s.gzhead.extra.length & 0xff);
  11614. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  11615. }
  11616. if (s.gzhead.hcrc) {
  11617. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  11618. }
  11619. s.gzindex = 0;
  11620. s.status = EXTRA_STATE;
  11621. }
  11622. }
  11623. else // DEFLATE header
  11624. {
  11625. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  11626. var level_flags = -1;
  11627. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  11628. level_flags = 0;
  11629. } else if (s.level < 6) {
  11630. level_flags = 1;
  11631. } else if (s.level === 6) {
  11632. level_flags = 2;
  11633. } else {
  11634. level_flags = 3;
  11635. }
  11636. header |= (level_flags << 6);
  11637. if (s.strstart !== 0) { header |= PRESET_DICT; }
  11638. header += 31 - (header % 31);
  11639. s.status = BUSY_STATE;
  11640. putShortMSB(s, header);
  11641. /* Save the adler32 of the preset dictionary: */
  11642. if (s.strstart !== 0) {
  11643. putShortMSB(s, strm.adler >>> 16);
  11644. putShortMSB(s, strm.adler & 0xffff);
  11645. }
  11646. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  11647. }
  11648. }
  11649. //#ifdef GZIP
  11650. if (s.status === EXTRA_STATE) {
  11651. if (s.gzhead.extra/* != Z_NULL*/) {
  11652. beg = s.pending; /* start of bytes to update crc */
  11653. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  11654. if (s.pending === s.pending_buf_size) {
  11655. if (s.gzhead.hcrc && s.pending > beg) {
  11656. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  11657. }
  11658. flush_pending(strm);
  11659. beg = s.pending;
  11660. if (s.pending === s.pending_buf_size) {
  11661. break;
  11662. }
  11663. }
  11664. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  11665. s.gzindex++;
  11666. }
  11667. if (s.gzhead.hcrc && s.pending > beg) {
  11668. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  11669. }
  11670. if (s.gzindex === s.gzhead.extra.length) {
  11671. s.gzindex = 0;
  11672. s.status = NAME_STATE;
  11673. }
  11674. }
  11675. else {
  11676. s.status = NAME_STATE;
  11677. }
  11678. }
  11679. if (s.status === NAME_STATE) {
  11680. if (s.gzhead.name/* != Z_NULL*/) {
  11681. beg = s.pending; /* start of bytes to update crc */
  11682. //int val;
  11683. do {
  11684. if (s.pending === s.pending_buf_size) {
  11685. if (s.gzhead.hcrc && s.pending > beg) {
  11686. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  11687. }
  11688. flush_pending(strm);
  11689. beg = s.pending;
  11690. if (s.pending === s.pending_buf_size) {
  11691. val = 1;
  11692. break;
  11693. }
  11694. }
  11695. // JS specific: little magic to add zero terminator to end of string
  11696. if (s.gzindex < s.gzhead.name.length) {
  11697. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  11698. } else {
  11699. val = 0;
  11700. }
  11701. put_byte(s, val);
  11702. } while (val !== 0);
  11703. if (s.gzhead.hcrc && s.pending > beg) {
  11704. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  11705. }
  11706. if (val === 0) {
  11707. s.gzindex = 0;
  11708. s.status = COMMENT_STATE;
  11709. }
  11710. }
  11711. else {
  11712. s.status = COMMENT_STATE;
  11713. }
  11714. }
  11715. if (s.status === COMMENT_STATE) {
  11716. if (s.gzhead.comment/* != Z_NULL*/) {
  11717. beg = s.pending; /* start of bytes to update crc */
  11718. //int val;
  11719. do {
  11720. if (s.pending === s.pending_buf_size) {
  11721. if (s.gzhead.hcrc && s.pending > beg) {
  11722. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  11723. }
  11724. flush_pending(strm);
  11725. beg = s.pending;
  11726. if (s.pending === s.pending_buf_size) {
  11727. val = 1;
  11728. break;
  11729. }
  11730. }
  11731. // JS specific: little magic to add zero terminator to end of string
  11732. if (s.gzindex < s.gzhead.comment.length) {
  11733. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  11734. } else {
  11735. val = 0;
  11736. }
  11737. put_byte(s, val);
  11738. } while (val !== 0);
  11739. if (s.gzhead.hcrc && s.pending > beg) {
  11740. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  11741. }
  11742. if (val === 0) {
  11743. s.status = HCRC_STATE;
  11744. }
  11745. }
  11746. else {
  11747. s.status = HCRC_STATE;
  11748. }
  11749. }
  11750. if (s.status === HCRC_STATE) {
  11751. if (s.gzhead.hcrc) {
  11752. if (s.pending + 2 > s.pending_buf_size) {
  11753. flush_pending(strm);
  11754. }
  11755. if (s.pending + 2 <= s.pending_buf_size) {
  11756. put_byte(s, strm.adler & 0xff);
  11757. put_byte(s, (strm.adler >> 8) & 0xff);
  11758. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  11759. s.status = BUSY_STATE;
  11760. }
  11761. }
  11762. else {
  11763. s.status = BUSY_STATE;
  11764. }
  11765. }
  11766. //#endif
  11767. /* Flush as much pending output as possible */
  11768. if (s.pending !== 0) {
  11769. flush_pending(strm);
  11770. if (strm.avail_out === 0) {
  11771. /* Since avail_out is 0, deflate will be called again with
  11772. * more output space, but possibly with both pending and
  11773. * avail_in equal to zero. There won't be anything to do,
  11774. * but this is not an error situation so make sure we
  11775. * return OK instead of BUF_ERROR at next call of deflate:
  11776. */
  11777. s.last_flush = -1;
  11778. return Z_OK;
  11779. }
  11780. /* Make sure there is something to do and avoid duplicate consecutive
  11781. * flushes. For repeated and useless calls with Z_FINISH, we keep
  11782. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  11783. */
  11784. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  11785. flush !== Z_FINISH) {
  11786. return err(strm, Z_BUF_ERROR);
  11787. }
  11788. /* User must not provide more input after the first FINISH: */
  11789. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  11790. return err(strm, Z_BUF_ERROR);
  11791. }
  11792. /* Start a new block or continue the current one.
  11793. */
  11794. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  11795. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  11796. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  11797. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  11798. configuration_table[s.level].func(s, flush));
  11799. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  11800. s.status = FINISH_STATE;
  11801. }
  11802. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  11803. if (strm.avail_out === 0) {
  11804. s.last_flush = -1;
  11805. /* avoid BUF_ERROR next call, see above */
  11806. }
  11807. return Z_OK;
  11808. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  11809. * of deflate should use the same flush parameter to make sure
  11810. * that the flush is complete. So we don't have to output an
  11811. * empty block here, this will be done at next call. This also
  11812. * ensures that for a very small output buffer, we emit at most
  11813. * one empty block.
  11814. */
  11815. }
  11816. if (bstate === BS_BLOCK_DONE) {
  11817. if (flush === Z_PARTIAL_FLUSH) {
  11818. trees._tr_align(s);
  11819. }
  11820. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  11821. trees._tr_stored_block(s, 0, 0, false);
  11822. /* For a full flush, this empty block will be recognized
  11823. * as a special marker by inflate_sync().
  11824. */
  11825. if (flush === Z_FULL_FLUSH) {
  11826. /*** CLEAR_HASH(s); ***/ /* forget history */
  11827. zero(s.head); // Fill with NIL (= 0);
  11828. if (s.lookahead === 0) {
  11829. s.strstart = 0;
  11830. s.block_start = 0;
  11831. s.insert = 0;
  11832. }
  11833. }
  11834. }
  11835. flush_pending(strm);
  11836. if (strm.avail_out === 0) {
  11837. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  11838. return Z_OK;
  11839. }
  11840. }
  11841. }
  11842. //Assert(strm->avail_out > 0, "bug2");
  11843. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  11844. if (flush !== Z_FINISH) { return Z_OK; }
  11845. if (s.wrap <= 0) { return Z_STREAM_END; }
  11846. /* Write the trailer */
  11847. if (s.wrap === 2) {
  11848. put_byte(s, strm.adler & 0xff);
  11849. put_byte(s, (strm.adler >> 8) & 0xff);
  11850. put_byte(s, (strm.adler >> 16) & 0xff);
  11851. put_byte(s, (strm.adler >> 24) & 0xff);
  11852. put_byte(s, strm.total_in & 0xff);
  11853. put_byte(s, (strm.total_in >> 8) & 0xff);
  11854. put_byte(s, (strm.total_in >> 16) & 0xff);
  11855. put_byte(s, (strm.total_in >> 24) & 0xff);
  11856. }
  11857. else
  11858. {
  11859. putShortMSB(s, strm.adler >>> 16);
  11860. putShortMSB(s, strm.adler & 0xffff);
  11861. }
  11862. flush_pending(strm);
  11863. /* If avail_out is zero, the application will call deflate again
  11864. * to flush the rest.
  11865. */
  11866. if (s.wrap > 0) { s.wrap = -s.wrap; }
  11867. /* write the trailer only once! */
  11868. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  11869. }
  11870. function deflateEnd(strm) {
  11871. var status;
  11872. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  11873. return Z_STREAM_ERROR;
  11874. }
  11875. status = strm.state.status;
  11876. if (status !== INIT_STATE &&
  11877. status !== EXTRA_STATE &&
  11878. status !== NAME_STATE &&
  11879. status !== COMMENT_STATE &&
  11880. status !== HCRC_STATE &&
  11881. status !== BUSY_STATE &&
  11882. status !== FINISH_STATE
  11883. ) {
  11884. return err(strm, Z_STREAM_ERROR);
  11885. }
  11886. strm.state = null;
  11887. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  11888. }
  11889. /* =========================================================================
  11890. * Copy the source state to the destination state
  11891. */
  11892. //function deflateCopy(dest, source) {
  11893. //
  11894. //}
  11895. exports.deflateInit = deflateInit;
  11896. exports.deflateInit2 = deflateInit2;
  11897. exports.deflateReset = deflateReset;
  11898. exports.deflateResetKeep = deflateResetKeep;
  11899. exports.deflateSetHeader = deflateSetHeader;
  11900. exports.deflate = deflate;
  11901. exports.deflateEnd = deflateEnd;
  11902. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  11903. /* Not implemented
  11904. exports.deflateBound = deflateBound;
  11905. exports.deflateCopy = deflateCopy;
  11906. exports.deflateSetDictionary = deflateSetDictionary;
  11907. exports.deflateParams = deflateParams;
  11908. exports.deflatePending = deflatePending;
  11909. exports.deflatePrime = deflatePrime;
  11910. exports.deflateTune = deflateTune;
  11911. */
  11912. },{"../utils/common":35,"./adler32":37,"./crc32":39,"./messages":45,"./trees":46}],41:[function(require,module,exports){
  11913. 'use strict';
  11914. function GZheader() {
  11915. /* true if compressed data believed to be text */
  11916. this.text = 0;
  11917. /* modification time */
  11918. this.time = 0;
  11919. /* extra flags (not used when writing a gzip file) */
  11920. this.xflags = 0;
  11921. /* operating system */
  11922. this.os = 0;
  11923. /* pointer to extra field or Z_NULL if none */
  11924. this.extra = null;
  11925. /* extra field length (valid if extra != Z_NULL) */
  11926. this.extra_len = 0; // Actually, we don't need it in JS,
  11927. // but leave for few code modifications
  11928. //
  11929. // Setup limits is not necessary because in js we should not preallocate memory
  11930. // for inflate use constant limit in 65536 bytes
  11931. //
  11932. /* space at extra (only when reading header) */
  11933. // this.extra_max = 0;
  11934. /* pointer to zero-terminated file name or Z_NULL */
  11935. this.name = '';
  11936. /* space at name (only when reading header) */
  11937. // this.name_max = 0;
  11938. /* pointer to zero-terminated comment or Z_NULL */
  11939. this.comment = '';
  11940. /* space at comment (only when reading header) */
  11941. // this.comm_max = 0;
  11942. /* true if there was or will be a header crc */
  11943. this.hcrc = 0;
  11944. /* true when done reading gzip header (not used when writing a gzip file) */
  11945. this.done = false;
  11946. }
  11947. module.exports = GZheader;
  11948. },{}],42:[function(require,module,exports){
  11949. 'use strict';
  11950. // See state defs from inflate.js
  11951. var BAD = 30; /* got a data error -- remain here until reset */
  11952. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  11953. /*
  11954. Decode literal, length, and distance codes and write out the resulting
  11955. literal and match bytes until either not enough input or output is
  11956. available, an end-of-block is encountered, or a data error is encountered.
  11957. When large enough input and output buffers are supplied to inflate(), for
  11958. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  11959. inflate execution time is spent in this routine.
  11960. Entry assumptions:
  11961. state.mode === LEN
  11962. strm.avail_in >= 6
  11963. strm.avail_out >= 258
  11964. start >= strm.avail_out
  11965. state.bits < 8
  11966. On return, state.mode is one of:
  11967. LEN -- ran out of enough output space or enough available input
  11968. TYPE -- reached end of block code, inflate() to interpret next block
  11969. BAD -- error in block data
  11970. Notes:
  11971. - The maximum input bits used by a length/distance pair is 15 bits for the
  11972. length code, 5 bits for the length extra, 15 bits for the distance code,
  11973. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  11974. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  11975. checking for available input while decoding.
  11976. - The maximum bytes that a single length/distance pair can output is 258
  11977. bytes, which is the maximum length that can be coded. inflate_fast()
  11978. requires strm.avail_out >= 258 for each loop to avoid checking for
  11979. output space.
  11980. */
  11981. module.exports = function inflate_fast(strm, start) {
  11982. var state;
  11983. var _in; /* local strm.input */
  11984. var last; /* have enough input while in < last */
  11985. var _out; /* local strm.output */
  11986. var beg; /* inflate()'s initial strm.output */
  11987. var end; /* while out < end, enough space available */
  11988. //#ifdef INFLATE_STRICT
  11989. var dmax; /* maximum distance from zlib header */
  11990. //#endif
  11991. var wsize; /* window size or zero if not using window */
  11992. var whave; /* valid bytes in the window */
  11993. var wnext; /* window write index */
  11994. var window; /* allocated sliding window, if wsize != 0 */
  11995. var hold; /* local strm.hold */
  11996. var bits; /* local strm.bits */
  11997. var lcode; /* local strm.lencode */
  11998. var dcode; /* local strm.distcode */
  11999. var lmask; /* mask for first level of length codes */
  12000. var dmask; /* mask for first level of distance codes */
  12001. var here; /* retrieved table entry */
  12002. var op; /* code bits, operation, extra bits, or */
  12003. /* window position, window bytes to copy */
  12004. var len; /* match length, unused bytes */
  12005. var dist; /* match distance */
  12006. var from; /* where to copy match from */
  12007. var from_source;
  12008. var input, output; // JS specific, because we have no pointers
  12009. /* copy state to local variables */
  12010. state = strm.state;
  12011. //here = state.here;
  12012. _in = strm.next_in;
  12013. input = strm.input;
  12014. last = _in + (strm.avail_in - 5);
  12015. _out = strm.next_out;
  12016. output = strm.output;
  12017. beg = _out - (start - strm.avail_out);
  12018. end = _out + (strm.avail_out - 257);
  12019. //#ifdef INFLATE_STRICT
  12020. dmax = state.dmax;
  12021. //#endif
  12022. wsize = state.wsize;
  12023. whave = state.whave;
  12024. wnext = state.wnext;
  12025. window = state.window;
  12026. hold = state.hold;
  12027. bits = state.bits;
  12028. lcode = state.lencode;
  12029. dcode = state.distcode;
  12030. lmask = (1 << state.lenbits) - 1;
  12031. dmask = (1 << state.distbits) - 1;
  12032. /* decode literals and length/distances until end-of-block or not enough
  12033. input data or output space */
  12034. top:
  12035. do {
  12036. if (bits < 15) {
  12037. hold += input[_in++] << bits;
  12038. bits += 8;
  12039. hold += input[_in++] << bits;
  12040. bits += 8;
  12041. }
  12042. here = lcode[hold & lmask];
  12043. dolen:
  12044. for (;;) { // Goto emulation
  12045. op = here >>> 24/*here.bits*/;
  12046. hold >>>= op;
  12047. bits -= op;
  12048. op = (here >>> 16) & 0xff/*here.op*/;
  12049. if (op === 0) { /* literal */
  12050. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  12051. // "inflate: literal '%c'\n" :
  12052. // "inflate: literal 0x%02x\n", here.val));
  12053. output[_out++] = here & 0xffff/*here.val*/;
  12054. }
  12055. else if (op & 16) { /* length base */
  12056. len = here & 0xffff/*here.val*/;
  12057. op &= 15; /* number of extra bits */
  12058. if (op) {
  12059. if (bits < op) {
  12060. hold += input[_in++] << bits;
  12061. bits += 8;
  12062. }
  12063. len += hold & ((1 << op) - 1);
  12064. hold >>>= op;
  12065. bits -= op;
  12066. }
  12067. //Tracevv((stderr, "inflate: length %u\n", len));
  12068. if (bits < 15) {
  12069. hold += input[_in++] << bits;
  12070. bits += 8;
  12071. hold += input[_in++] << bits;
  12072. bits += 8;
  12073. }
  12074. here = dcode[hold & dmask];
  12075. dodist:
  12076. for (;;) { // goto emulation
  12077. op = here >>> 24/*here.bits*/;
  12078. hold >>>= op;
  12079. bits -= op;
  12080. op = (here >>> 16) & 0xff/*here.op*/;
  12081. if (op & 16) { /* distance base */
  12082. dist = here & 0xffff/*here.val*/;
  12083. op &= 15; /* number of extra bits */
  12084. if (bits < op) {
  12085. hold += input[_in++] << bits;
  12086. bits += 8;
  12087. if (bits < op) {
  12088. hold += input[_in++] << bits;
  12089. bits += 8;
  12090. }
  12091. }
  12092. dist += hold & ((1 << op) - 1);
  12093. //#ifdef INFLATE_STRICT
  12094. if (dist > dmax) {
  12095. strm.msg = 'invalid distance too far back';
  12096. state.mode = BAD;
  12097. break top;
  12098. }
  12099. //#endif
  12100. hold >>>= op;
  12101. bits -= op;
  12102. //Tracevv((stderr, "inflate: distance %u\n", dist));
  12103. op = _out - beg; /* max distance in output */
  12104. if (dist > op) { /* see if copy from window */
  12105. op = dist - op; /* distance back in window */
  12106. if (op > whave) {
  12107. if (state.sane) {
  12108. strm.msg = 'invalid distance too far back';
  12109. state.mode = BAD;
  12110. break top;
  12111. }
  12112. // (!) This block is disabled in zlib defailts,
  12113. // don't enable it for binary compatibility
  12114. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  12115. // if (len <= op - whave) {
  12116. // do {
  12117. // output[_out++] = 0;
  12118. // } while (--len);
  12119. // continue top;
  12120. // }
  12121. // len -= op - whave;
  12122. // do {
  12123. // output[_out++] = 0;
  12124. // } while (--op > whave);
  12125. // if (op === 0) {
  12126. // from = _out - dist;
  12127. // do {
  12128. // output[_out++] = output[from++];
  12129. // } while (--len);
  12130. // continue top;
  12131. // }
  12132. //#endif
  12133. }
  12134. from = 0; // window index
  12135. from_source = window;
  12136. if (wnext === 0) { /* very common case */
  12137. from += wsize - op;
  12138. if (op < len) { /* some from window */
  12139. len -= op;
  12140. do {
  12141. output[_out++] = window[from++];
  12142. } while (--op);
  12143. from = _out - dist; /* rest from output */
  12144. from_source = output;
  12145. }
  12146. }
  12147. else if (wnext < op) { /* wrap around window */
  12148. from += wsize + wnext - op;
  12149. op -= wnext;
  12150. if (op < len) { /* some from end of window */
  12151. len -= op;
  12152. do {
  12153. output[_out++] = window[from++];
  12154. } while (--op);
  12155. from = 0;
  12156. if (wnext < len) { /* some from start of window */
  12157. op = wnext;
  12158. len -= op;
  12159. do {
  12160. output[_out++] = window[from++];
  12161. } while (--op);
  12162. from = _out - dist; /* rest from output */
  12163. from_source = output;
  12164. }
  12165. }
  12166. }
  12167. else { /* contiguous in window */
  12168. from += wnext - op;
  12169. if (op < len) { /* some from window */
  12170. len -= op;
  12171. do {
  12172. output[_out++] = window[from++];
  12173. } while (--op);
  12174. from = _out - dist; /* rest from output */
  12175. from_source = output;
  12176. }
  12177. }
  12178. while (len > 2) {
  12179. output[_out++] = from_source[from++];
  12180. output[_out++] = from_source[from++];
  12181. output[_out++] = from_source[from++];
  12182. len -= 3;
  12183. }
  12184. if (len) {
  12185. output[_out++] = from_source[from++];
  12186. if (len > 1) {
  12187. output[_out++] = from_source[from++];
  12188. }
  12189. }
  12190. }
  12191. else {
  12192. from = _out - dist; /* copy direct from output */
  12193. do { /* minimum length is three */
  12194. output[_out++] = output[from++];
  12195. output[_out++] = output[from++];
  12196. output[_out++] = output[from++];
  12197. len -= 3;
  12198. } while (len > 2);
  12199. if (len) {
  12200. output[_out++] = output[from++];
  12201. if (len > 1) {
  12202. output[_out++] = output[from++];
  12203. }
  12204. }
  12205. }
  12206. }
  12207. else if ((op & 64) === 0) { /* 2nd level distance code */
  12208. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  12209. continue dodist;
  12210. }
  12211. else {
  12212. strm.msg = 'invalid distance code';
  12213. state.mode = BAD;
  12214. break top;
  12215. }
  12216. break; // need to emulate goto via "continue"
  12217. }
  12218. }
  12219. else if ((op & 64) === 0) { /* 2nd level length code */
  12220. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  12221. continue dolen;
  12222. }
  12223. else if (op & 32) { /* end-of-block */
  12224. //Tracevv((stderr, "inflate: end of block\n"));
  12225. state.mode = TYPE;
  12226. break top;
  12227. }
  12228. else {
  12229. strm.msg = 'invalid literal/length code';
  12230. state.mode = BAD;
  12231. break top;
  12232. }
  12233. break; // need to emulate goto via "continue"
  12234. }
  12235. } while (_in < last && _out < end);
  12236. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  12237. len = bits >> 3;
  12238. _in -= len;
  12239. bits -= len << 3;
  12240. hold &= (1 << bits) - 1;
  12241. /* update state and return */
  12242. strm.next_in = _in;
  12243. strm.next_out = _out;
  12244. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  12245. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  12246. state.hold = hold;
  12247. state.bits = bits;
  12248. return;
  12249. };
  12250. },{}],43:[function(require,module,exports){
  12251. 'use strict';
  12252. var utils = require('../utils/common');
  12253. var adler32 = require('./adler32');
  12254. var crc32 = require('./crc32');
  12255. var inflate_fast = require('./inffast');
  12256. var inflate_table = require('./inftrees');
  12257. var CODES = 0;
  12258. var LENS = 1;
  12259. var DISTS = 2;
  12260. /* Public constants ==========================================================*/
  12261. /* ===========================================================================*/
  12262. /* Allowed flush values; see deflate() and inflate() below for details */
  12263. //var Z_NO_FLUSH = 0;
  12264. //var Z_PARTIAL_FLUSH = 1;
  12265. //var Z_SYNC_FLUSH = 2;
  12266. //var Z_FULL_FLUSH = 3;
  12267. var Z_FINISH = 4;
  12268. var Z_BLOCK = 5;
  12269. var Z_TREES = 6;
  12270. /* Return codes for the compression/decompression functions. Negative values
  12271. * are errors, positive values are used for special but normal events.
  12272. */
  12273. var Z_OK = 0;
  12274. var Z_STREAM_END = 1;
  12275. var Z_NEED_DICT = 2;
  12276. //var Z_ERRNO = -1;
  12277. var Z_STREAM_ERROR = -2;
  12278. var Z_DATA_ERROR = -3;
  12279. var Z_MEM_ERROR = -4;
  12280. var Z_BUF_ERROR = -5;
  12281. //var Z_VERSION_ERROR = -6;
  12282. /* The deflate compression method */
  12283. var Z_DEFLATED = 8;
  12284. /* STATES ====================================================================*/
  12285. /* ===========================================================================*/
  12286. var HEAD = 1; /* i: waiting for magic header */
  12287. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  12288. var TIME = 3; /* i: waiting for modification time (gzip) */
  12289. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  12290. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  12291. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  12292. var NAME = 7; /* i: waiting for end of file name (gzip) */
  12293. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  12294. var HCRC = 9; /* i: waiting for header crc (gzip) */
  12295. var DICTID = 10; /* i: waiting for dictionary check value */
  12296. var DICT = 11; /* waiting for inflateSetDictionary() call */
  12297. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  12298. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  12299. var STORED = 14; /* i: waiting for stored size (length and complement) */
  12300. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  12301. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  12302. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  12303. var LENLENS = 18; /* i: waiting for code length code lengths */
  12304. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  12305. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  12306. var LEN = 21; /* i: waiting for length/lit/eob code */
  12307. var LENEXT = 22; /* i: waiting for length extra bits */
  12308. var DIST = 23; /* i: waiting for distance code */
  12309. var DISTEXT = 24; /* i: waiting for distance extra bits */
  12310. var MATCH = 25; /* o: waiting for output space to copy string */
  12311. var LIT = 26; /* o: waiting for output space to write literal */
  12312. var CHECK = 27; /* i: waiting for 32-bit check value */
  12313. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  12314. var DONE = 29; /* finished check, done -- remain here until reset */
  12315. var BAD = 30; /* got a data error -- remain here until reset */
  12316. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  12317. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  12318. /* ===========================================================================*/
  12319. var ENOUGH_LENS = 852;
  12320. var ENOUGH_DISTS = 592;
  12321. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  12322. var MAX_WBITS = 15;
  12323. /* 32K LZ77 window */
  12324. var DEF_WBITS = MAX_WBITS;
  12325. function ZSWAP32(q) {
  12326. return (((q >>> 24) & 0xff) +
  12327. ((q >>> 8) & 0xff00) +
  12328. ((q & 0xff00) << 8) +
  12329. ((q & 0xff) << 24));
  12330. }
  12331. function InflateState() {
  12332. this.mode = 0; /* current inflate mode */
  12333. this.last = false; /* true if processing last block */
  12334. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  12335. this.havedict = false; /* true if dictionary provided */
  12336. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  12337. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  12338. this.check = 0; /* protected copy of check value */
  12339. this.total = 0; /* protected copy of output count */
  12340. // TODO: may be {}
  12341. this.head = null; /* where to save gzip header information */
  12342. /* sliding window */
  12343. this.wbits = 0; /* log base 2 of requested window size */
  12344. this.wsize = 0; /* window size or zero if not using window */
  12345. this.whave = 0; /* valid bytes in the window */
  12346. this.wnext = 0; /* window write index */
  12347. this.window = null; /* allocated sliding window, if needed */
  12348. /* bit accumulator */
  12349. this.hold = 0; /* input bit accumulator */
  12350. this.bits = 0; /* number of bits in "in" */
  12351. /* for string and stored block copying */
  12352. this.length = 0; /* literal or length of data to copy */
  12353. this.offset = 0; /* distance back to copy string from */
  12354. /* for table and code decoding */
  12355. this.extra = 0; /* extra bits needed */
  12356. /* fixed and dynamic code tables */
  12357. this.lencode = null; /* starting table for length/literal codes */
  12358. this.distcode = null; /* starting table for distance codes */
  12359. this.lenbits = 0; /* index bits for lencode */
  12360. this.distbits = 0; /* index bits for distcode */
  12361. /* dynamic table building */
  12362. this.ncode = 0; /* number of code length code lengths */
  12363. this.nlen = 0; /* number of length code lengths */
  12364. this.ndist = 0; /* number of distance code lengths */
  12365. this.have = 0; /* number of code lengths in lens[] */
  12366. this.next = null; /* next available space in codes[] */
  12367. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  12368. this.work = new utils.Buf16(288); /* work area for code table building */
  12369. /*
  12370. because we don't have pointers in js, we use lencode and distcode directly
  12371. as buffers so we don't need codes
  12372. */
  12373. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  12374. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  12375. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  12376. this.sane = 0; /* if false, allow invalid distance too far */
  12377. this.back = 0; /* bits back of last unprocessed length/lit */
  12378. this.was = 0; /* initial length of match */
  12379. }
  12380. function inflateResetKeep(strm) {
  12381. var state;
  12382. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12383. state = strm.state;
  12384. strm.total_in = strm.total_out = state.total = 0;
  12385. strm.msg = ''; /*Z_NULL*/
  12386. if (state.wrap) { /* to support ill-conceived Java test suite */
  12387. strm.adler = state.wrap & 1;
  12388. }
  12389. state.mode = HEAD;
  12390. state.last = 0;
  12391. state.havedict = 0;
  12392. state.dmax = 32768;
  12393. state.head = null/*Z_NULL*/;
  12394. state.hold = 0;
  12395. state.bits = 0;
  12396. //state.lencode = state.distcode = state.next = state.codes;
  12397. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  12398. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  12399. state.sane = 1;
  12400. state.back = -1;
  12401. //Tracev((stderr, "inflate: reset\n"));
  12402. return Z_OK;
  12403. }
  12404. function inflateReset(strm) {
  12405. var state;
  12406. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12407. state = strm.state;
  12408. state.wsize = 0;
  12409. state.whave = 0;
  12410. state.wnext = 0;
  12411. return inflateResetKeep(strm);
  12412. }
  12413. function inflateReset2(strm, windowBits) {
  12414. var wrap;
  12415. var state;
  12416. /* get the state */
  12417. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  12418. state = strm.state;
  12419. /* extract wrap request from windowBits parameter */
  12420. if (windowBits < 0) {
  12421. wrap = 0;
  12422. windowBits = -windowBits;
  12423. }
  12424. else {
  12425. wrap = (windowBits >> 4) + 1;
  12426. if (windowBits < 48) {
  12427. windowBits &= 15;
  12428. }
  12429. }
  12430. /* set number of window bits, free window if different */
  12431. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  12432. return Z_STREAM_ERROR;
  12433. }
  12434. if (state.window !== null && state.wbits !== windowBits) {
  12435. state.window = null;
  12436. }
  12437. /* update state and reset the rest of it */
  12438. state.wrap = wrap;
  12439. state.wbits = windowBits;
  12440. return inflateReset(strm);
  12441. }
  12442. function inflateInit2(strm, windowBits) {
  12443. var ret;
  12444. var state;
  12445. if (!strm) { return Z_STREAM_ERROR; }
  12446. //strm.msg = Z_NULL; /* in case we return an error */
  12447. state = new InflateState();
  12448. //if (state === Z_NULL) return Z_MEM_ERROR;
  12449. //Tracev((stderr, "inflate: allocated\n"));
  12450. strm.state = state;
  12451. state.window = null/*Z_NULL*/;
  12452. ret = inflateReset2(strm, windowBits);
  12453. if (ret !== Z_OK) {
  12454. strm.state = null/*Z_NULL*/;
  12455. }
  12456. return ret;
  12457. }
  12458. function inflateInit(strm) {
  12459. return inflateInit2(strm, DEF_WBITS);
  12460. }
  12461. /*
  12462. Return state with length and distance decoding tables and index sizes set to
  12463. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  12464. If BUILDFIXED is defined, then instead this routine builds the tables the
  12465. first time it's called, and returns those tables the first time and
  12466. thereafter. This reduces the size of the code by about 2K bytes, in
  12467. exchange for a little execution time. However, BUILDFIXED should not be
  12468. used for threaded applications, since the rewriting of the tables and virgin
  12469. may not be thread-safe.
  12470. */
  12471. var virgin = true;
  12472. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  12473. function fixedtables(state) {
  12474. /* build fixed huffman tables if first call (may not be thread safe) */
  12475. if (virgin) {
  12476. var sym;
  12477. lenfix = new utils.Buf32(512);
  12478. distfix = new utils.Buf32(32);
  12479. /* literal/length table */
  12480. sym = 0;
  12481. while (sym < 144) { state.lens[sym++] = 8; }
  12482. while (sym < 256) { state.lens[sym++] = 9; }
  12483. while (sym < 280) { state.lens[sym++] = 7; }
  12484. while (sym < 288) { state.lens[sym++] = 8; }
  12485. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  12486. /* distance table */
  12487. sym = 0;
  12488. while (sym < 32) { state.lens[sym++] = 5; }
  12489. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  12490. /* do this just once */
  12491. virgin = false;
  12492. }
  12493. state.lencode = lenfix;
  12494. state.lenbits = 9;
  12495. state.distcode = distfix;
  12496. state.distbits = 5;
  12497. }
  12498. /*
  12499. Update the window with the last wsize (normally 32K) bytes written before
  12500. returning. If window does not exist yet, create it. This is only called
  12501. when a window is already in use, or when output has been written during this
  12502. inflate call, but the end of the deflate stream has not been reached yet.
  12503. It is also called to create a window for dictionary data when a dictionary
  12504. is loaded.
  12505. Providing output buffers larger than 32K to inflate() should provide a speed
  12506. advantage, since only the last 32K of output is copied to the sliding window
  12507. upon return from inflate(), and since all distances after the first 32K of
  12508. output will fall in the output data, making match copies simpler and faster.
  12509. The advantage may be dependent on the size of the processor's data caches.
  12510. */
  12511. function updatewindow(strm, src, end, copy) {
  12512. var dist;
  12513. var state = strm.state;
  12514. /* if it hasn't been done already, allocate space for the window */
  12515. if (state.window === null) {
  12516. state.wsize = 1 << state.wbits;
  12517. state.wnext = 0;
  12518. state.whave = 0;
  12519. state.window = new utils.Buf8(state.wsize);
  12520. }
  12521. /* copy state->wsize or less output bytes into the circular window */
  12522. if (copy >= state.wsize) {
  12523. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  12524. state.wnext = 0;
  12525. state.whave = state.wsize;
  12526. }
  12527. else {
  12528. dist = state.wsize - state.wnext;
  12529. if (dist > copy) {
  12530. dist = copy;
  12531. }
  12532. //zmemcpy(state->window + state->wnext, end - copy, dist);
  12533. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  12534. copy -= dist;
  12535. if (copy) {
  12536. //zmemcpy(state->window, end - copy, copy);
  12537. utils.arraySet(state.window,src, end - copy, copy, 0);
  12538. state.wnext = copy;
  12539. state.whave = state.wsize;
  12540. }
  12541. else {
  12542. state.wnext += dist;
  12543. if (state.wnext === state.wsize) { state.wnext = 0; }
  12544. if (state.whave < state.wsize) { state.whave += dist; }
  12545. }
  12546. }
  12547. return 0;
  12548. }
  12549. function inflate(strm, flush) {
  12550. var state;
  12551. var input, output; // input/output buffers
  12552. var next; /* next input INDEX */
  12553. var put; /* next output INDEX */
  12554. var have, left; /* available input and output */
  12555. var hold; /* bit buffer */
  12556. var bits; /* bits in bit buffer */
  12557. var _in, _out; /* save starting available input and output */
  12558. var copy; /* number of stored or match bytes to copy */
  12559. var from; /* where to copy match bytes from */
  12560. var from_source;
  12561. var here = 0; /* current decoding table entry */
  12562. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  12563. //var last; /* parent table entry */
  12564. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  12565. var len; /* length to copy for repeats, bits to drop */
  12566. var ret; /* return code */
  12567. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  12568. var opts;
  12569. var n; // temporary var for NEED_BITS
  12570. var order = /* permutation of code lengths */
  12571. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  12572. if (!strm || !strm.state || !strm.output ||
  12573. (!strm.input && strm.avail_in !== 0)) {
  12574. return Z_STREAM_ERROR;
  12575. }
  12576. state = strm.state;
  12577. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  12578. //--- LOAD() ---
  12579. put = strm.next_out;
  12580. output = strm.output;
  12581. left = strm.avail_out;
  12582. next = strm.next_in;
  12583. input = strm.input;
  12584. have = strm.avail_in;
  12585. hold = state.hold;
  12586. bits = state.bits;
  12587. //---
  12588. _in = have;
  12589. _out = left;
  12590. ret = Z_OK;
  12591. inf_leave: // goto emulation
  12592. for (;;) {
  12593. switch (state.mode) {
  12594. case HEAD:
  12595. if (state.wrap === 0) {
  12596. state.mode = TYPEDO;
  12597. break;
  12598. }
  12599. //=== NEEDBITS(16);
  12600. while (bits < 16) {
  12601. if (have === 0) { break inf_leave; }
  12602. have--;
  12603. hold += input[next++] << bits;
  12604. bits += 8;
  12605. }
  12606. //===//
  12607. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  12608. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  12609. //=== CRC2(state.check, hold);
  12610. hbuf[0] = hold & 0xff;
  12611. hbuf[1] = (hold >>> 8) & 0xff;
  12612. state.check = crc32(state.check, hbuf, 2, 0);
  12613. //===//
  12614. //=== INITBITS();
  12615. hold = 0;
  12616. bits = 0;
  12617. //===//
  12618. state.mode = FLAGS;
  12619. break;
  12620. }
  12621. state.flags = 0; /* expect zlib header */
  12622. if (state.head) {
  12623. state.head.done = false;
  12624. }
  12625. if (!(state.wrap & 1) || /* check if zlib header allowed */
  12626. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  12627. strm.msg = 'incorrect header check';
  12628. state.mode = BAD;
  12629. break;
  12630. }
  12631. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  12632. strm.msg = 'unknown compression method';
  12633. state.mode = BAD;
  12634. break;
  12635. }
  12636. //--- DROPBITS(4) ---//
  12637. hold >>>= 4;
  12638. bits -= 4;
  12639. //---//
  12640. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  12641. if (state.wbits === 0) {
  12642. state.wbits = len;
  12643. }
  12644. else if (len > state.wbits) {
  12645. strm.msg = 'invalid window size';
  12646. state.mode = BAD;
  12647. break;
  12648. }
  12649. state.dmax = 1 << len;
  12650. //Tracev((stderr, "inflate: zlib header ok\n"));
  12651. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  12652. state.mode = hold & 0x200 ? DICTID : TYPE;
  12653. //=== INITBITS();
  12654. hold = 0;
  12655. bits = 0;
  12656. //===//
  12657. break;
  12658. case FLAGS:
  12659. //=== NEEDBITS(16); */
  12660. while (bits < 16) {
  12661. if (have === 0) { break inf_leave; }
  12662. have--;
  12663. hold += input[next++] << bits;
  12664. bits += 8;
  12665. }
  12666. //===//
  12667. state.flags = hold;
  12668. if ((state.flags & 0xff) !== Z_DEFLATED) {
  12669. strm.msg = 'unknown compression method';
  12670. state.mode = BAD;
  12671. break;
  12672. }
  12673. if (state.flags & 0xe000) {
  12674. strm.msg = 'unknown header flags set';
  12675. state.mode = BAD;
  12676. break;
  12677. }
  12678. if (state.head) {
  12679. state.head.text = ((hold >> 8) & 1);
  12680. }
  12681. if (state.flags & 0x0200) {
  12682. //=== CRC2(state.check, hold);
  12683. hbuf[0] = hold & 0xff;
  12684. hbuf[1] = (hold >>> 8) & 0xff;
  12685. state.check = crc32(state.check, hbuf, 2, 0);
  12686. //===//
  12687. }
  12688. //=== INITBITS();
  12689. hold = 0;
  12690. bits = 0;
  12691. //===//
  12692. state.mode = TIME;
  12693. /* falls through */
  12694. case TIME:
  12695. //=== NEEDBITS(32); */
  12696. while (bits < 32) {
  12697. if (have === 0) { break inf_leave; }
  12698. have--;
  12699. hold += input[next++] << bits;
  12700. bits += 8;
  12701. }
  12702. //===//
  12703. if (state.head) {
  12704. state.head.time = hold;
  12705. }
  12706. if (state.flags & 0x0200) {
  12707. //=== CRC4(state.check, hold)
  12708. hbuf[0] = hold & 0xff;
  12709. hbuf[1] = (hold >>> 8) & 0xff;
  12710. hbuf[2] = (hold >>> 16) & 0xff;
  12711. hbuf[3] = (hold >>> 24) & 0xff;
  12712. state.check = crc32(state.check, hbuf, 4, 0);
  12713. //===
  12714. }
  12715. //=== INITBITS();
  12716. hold = 0;
  12717. bits = 0;
  12718. //===//
  12719. state.mode = OS;
  12720. /* falls through */
  12721. case OS:
  12722. //=== NEEDBITS(16); */
  12723. while (bits < 16) {
  12724. if (have === 0) { break inf_leave; }
  12725. have--;
  12726. hold += input[next++] << bits;
  12727. bits += 8;
  12728. }
  12729. //===//
  12730. if (state.head) {
  12731. state.head.xflags = (hold & 0xff);
  12732. state.head.os = (hold >> 8);
  12733. }
  12734. if (state.flags & 0x0200) {
  12735. //=== CRC2(state.check, hold);
  12736. hbuf[0] = hold & 0xff;
  12737. hbuf[1] = (hold >>> 8) & 0xff;
  12738. state.check = crc32(state.check, hbuf, 2, 0);
  12739. //===//
  12740. }
  12741. //=== INITBITS();
  12742. hold = 0;
  12743. bits = 0;
  12744. //===//
  12745. state.mode = EXLEN;
  12746. /* falls through */
  12747. case EXLEN:
  12748. if (state.flags & 0x0400) {
  12749. //=== NEEDBITS(16); */
  12750. while (bits < 16) {
  12751. if (have === 0) { break inf_leave; }
  12752. have--;
  12753. hold += input[next++] << bits;
  12754. bits += 8;
  12755. }
  12756. //===//
  12757. state.length = hold;
  12758. if (state.head) {
  12759. state.head.extra_len = hold;
  12760. }
  12761. if (state.flags & 0x0200) {
  12762. //=== CRC2(state.check, hold);
  12763. hbuf[0] = hold & 0xff;
  12764. hbuf[1] = (hold >>> 8) & 0xff;
  12765. state.check = crc32(state.check, hbuf, 2, 0);
  12766. //===//
  12767. }
  12768. //=== INITBITS();
  12769. hold = 0;
  12770. bits = 0;
  12771. //===//
  12772. }
  12773. else if (state.head) {
  12774. state.head.extra = null/*Z_NULL*/;
  12775. }
  12776. state.mode = EXTRA;
  12777. /* falls through */
  12778. case EXTRA:
  12779. if (state.flags & 0x0400) {
  12780. copy = state.length;
  12781. if (copy > have) { copy = have; }
  12782. if (copy) {
  12783. if (state.head) {
  12784. len = state.head.extra_len - state.length;
  12785. if (!state.head.extra) {
  12786. // Use untyped array for more conveniend processing later
  12787. state.head.extra = new Array(state.head.extra_len);
  12788. }
  12789. utils.arraySet(
  12790. state.head.extra,
  12791. input,
  12792. next,
  12793. // extra field is limited to 65536 bytes
  12794. // - no need for additional size check
  12795. copy,
  12796. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  12797. len
  12798. );
  12799. //zmemcpy(state.head.extra + len, next,
  12800. // len + copy > state.head.extra_max ?
  12801. // state.head.extra_max - len : copy);
  12802. }
  12803. if (state.flags & 0x0200) {
  12804. state.check = crc32(state.check, input, copy, next);
  12805. }
  12806. have -= copy;
  12807. next += copy;
  12808. state.length -= copy;
  12809. }
  12810. if (state.length) { break inf_leave; }
  12811. }
  12812. state.length = 0;
  12813. state.mode = NAME;
  12814. /* falls through */
  12815. case NAME:
  12816. if (state.flags & 0x0800) {
  12817. if (have === 0) { break inf_leave; }
  12818. copy = 0;
  12819. do {
  12820. // TODO: 2 or 1 bytes?
  12821. len = input[next + copy++];
  12822. /* use constant limit because in js we should not preallocate memory */
  12823. if (state.head && len &&
  12824. (state.length < 65536 /*state.head.name_max*/)) {
  12825. state.head.name += String.fromCharCode(len);
  12826. }
  12827. } while (len && copy < have);
  12828. if (state.flags & 0x0200) {
  12829. state.check = crc32(state.check, input, copy, next);
  12830. }
  12831. have -= copy;
  12832. next += copy;
  12833. if (len) { break inf_leave; }
  12834. }
  12835. else if (state.head) {
  12836. state.head.name = null;
  12837. }
  12838. state.length = 0;
  12839. state.mode = COMMENT;
  12840. /* falls through */
  12841. case COMMENT:
  12842. if (state.flags & 0x1000) {
  12843. if (have === 0) { break inf_leave; }
  12844. copy = 0;
  12845. do {
  12846. len = input[next + copy++];
  12847. /* use constant limit because in js we should not preallocate memory */
  12848. if (state.head && len &&
  12849. (state.length < 65536 /*state.head.comm_max*/)) {
  12850. state.head.comment += String.fromCharCode(len);
  12851. }
  12852. } while (len && copy < have);
  12853. if (state.flags & 0x0200) {
  12854. state.check = crc32(state.check, input, copy, next);
  12855. }
  12856. have -= copy;
  12857. next += copy;
  12858. if (len) { break inf_leave; }
  12859. }
  12860. else if (state.head) {
  12861. state.head.comment = null;
  12862. }
  12863. state.mode = HCRC;
  12864. /* falls through */
  12865. case HCRC:
  12866. if (state.flags & 0x0200) {
  12867. //=== NEEDBITS(16); */
  12868. while (bits < 16) {
  12869. if (have === 0) { break inf_leave; }
  12870. have--;
  12871. hold += input[next++] << bits;
  12872. bits += 8;
  12873. }
  12874. //===//
  12875. if (hold !== (state.check & 0xffff)) {
  12876. strm.msg = 'header crc mismatch';
  12877. state.mode = BAD;
  12878. break;
  12879. }
  12880. //=== INITBITS();
  12881. hold = 0;
  12882. bits = 0;
  12883. //===//
  12884. }
  12885. if (state.head) {
  12886. state.head.hcrc = ((state.flags >> 9) & 1);
  12887. state.head.done = true;
  12888. }
  12889. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  12890. state.mode = TYPE;
  12891. break;
  12892. case DICTID:
  12893. //=== NEEDBITS(32); */
  12894. while (bits < 32) {
  12895. if (have === 0) { break inf_leave; }
  12896. have--;
  12897. hold += input[next++] << bits;
  12898. bits += 8;
  12899. }
  12900. //===//
  12901. strm.adler = state.check = ZSWAP32(hold);
  12902. //=== INITBITS();
  12903. hold = 0;
  12904. bits = 0;
  12905. //===//
  12906. state.mode = DICT;
  12907. /* falls through */
  12908. case DICT:
  12909. if (state.havedict === 0) {
  12910. //--- RESTORE() ---
  12911. strm.next_out = put;
  12912. strm.avail_out = left;
  12913. strm.next_in = next;
  12914. strm.avail_in = have;
  12915. state.hold = hold;
  12916. state.bits = bits;
  12917. //---
  12918. return Z_NEED_DICT;
  12919. }
  12920. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  12921. state.mode = TYPE;
  12922. /* falls through */
  12923. case TYPE:
  12924. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  12925. /* falls through */
  12926. case TYPEDO:
  12927. if (state.last) {
  12928. //--- BYTEBITS() ---//
  12929. hold >>>= bits & 7;
  12930. bits -= bits & 7;
  12931. //---//
  12932. state.mode = CHECK;
  12933. break;
  12934. }
  12935. //=== NEEDBITS(3); */
  12936. while (bits < 3) {
  12937. if (have === 0) { break inf_leave; }
  12938. have--;
  12939. hold += input[next++] << bits;
  12940. bits += 8;
  12941. }
  12942. //===//
  12943. state.last = (hold & 0x01)/*BITS(1)*/;
  12944. //--- DROPBITS(1) ---//
  12945. hold >>>= 1;
  12946. bits -= 1;
  12947. //---//
  12948. switch ((hold & 0x03)/*BITS(2)*/) {
  12949. case 0: /* stored block */
  12950. //Tracev((stderr, "inflate: stored block%s\n",
  12951. // state.last ? " (last)" : ""));
  12952. state.mode = STORED;
  12953. break;
  12954. case 1: /* fixed block */
  12955. fixedtables(state);
  12956. //Tracev((stderr, "inflate: fixed codes block%s\n",
  12957. // state.last ? " (last)" : ""));
  12958. state.mode = LEN_; /* decode codes */
  12959. if (flush === Z_TREES) {
  12960. //--- DROPBITS(2) ---//
  12961. hold >>>= 2;
  12962. bits -= 2;
  12963. //---//
  12964. break inf_leave;
  12965. }
  12966. break;
  12967. case 2: /* dynamic block */
  12968. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  12969. // state.last ? " (last)" : ""));
  12970. state.mode = TABLE;
  12971. break;
  12972. case 3:
  12973. strm.msg = 'invalid block type';
  12974. state.mode = BAD;
  12975. }
  12976. //--- DROPBITS(2) ---//
  12977. hold >>>= 2;
  12978. bits -= 2;
  12979. //---//
  12980. break;
  12981. case STORED:
  12982. //--- BYTEBITS() ---// /* go to byte boundary */
  12983. hold >>>= bits & 7;
  12984. bits -= bits & 7;
  12985. //---//
  12986. //=== NEEDBITS(32); */
  12987. while (bits < 32) {
  12988. if (have === 0) { break inf_leave; }
  12989. have--;
  12990. hold += input[next++] << bits;
  12991. bits += 8;
  12992. }
  12993. //===//
  12994. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  12995. strm.msg = 'invalid stored block lengths';
  12996. state.mode = BAD;
  12997. break;
  12998. }
  12999. state.length = hold & 0xffff;
  13000. //Tracev((stderr, "inflate: stored length %u\n",
  13001. // state.length));
  13002. //=== INITBITS();
  13003. hold = 0;
  13004. bits = 0;
  13005. //===//
  13006. state.mode = COPY_;
  13007. if (flush === Z_TREES) { break inf_leave; }
  13008. /* falls through */
  13009. case COPY_:
  13010. state.mode = COPY;
  13011. /* falls through */
  13012. case COPY:
  13013. copy = state.length;
  13014. if (copy) {
  13015. if (copy > have) { copy = have; }
  13016. if (copy > left) { copy = left; }
  13017. if (copy === 0) { break inf_leave; }
  13018. //--- zmemcpy(put, next, copy); ---
  13019. utils.arraySet(output, input, next, copy, put);
  13020. //---//
  13021. have -= copy;
  13022. next += copy;
  13023. left -= copy;
  13024. put += copy;
  13025. state.length -= copy;
  13026. break;
  13027. }
  13028. //Tracev((stderr, "inflate: stored end\n"));
  13029. state.mode = TYPE;
  13030. break;
  13031. case TABLE:
  13032. //=== NEEDBITS(14); */
  13033. while (bits < 14) {
  13034. if (have === 0) { break inf_leave; }
  13035. have--;
  13036. hold += input[next++] << bits;
  13037. bits += 8;
  13038. }
  13039. //===//
  13040. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  13041. //--- DROPBITS(5) ---//
  13042. hold >>>= 5;
  13043. bits -= 5;
  13044. //---//
  13045. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  13046. //--- DROPBITS(5) ---//
  13047. hold >>>= 5;
  13048. bits -= 5;
  13049. //---//
  13050. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  13051. //--- DROPBITS(4) ---//
  13052. hold >>>= 4;
  13053. bits -= 4;
  13054. //---//
  13055. //#ifndef PKZIP_BUG_WORKAROUND
  13056. if (state.nlen > 286 || state.ndist > 30) {
  13057. strm.msg = 'too many length or distance symbols';
  13058. state.mode = BAD;
  13059. break;
  13060. }
  13061. //#endif
  13062. //Tracev((stderr, "inflate: table sizes ok\n"));
  13063. state.have = 0;
  13064. state.mode = LENLENS;
  13065. /* falls through */
  13066. case LENLENS:
  13067. while (state.have < state.ncode) {
  13068. //=== NEEDBITS(3);
  13069. while (bits < 3) {
  13070. if (have === 0) { break inf_leave; }
  13071. have--;
  13072. hold += input[next++] << bits;
  13073. bits += 8;
  13074. }
  13075. //===//
  13076. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  13077. //--- DROPBITS(3) ---//
  13078. hold >>>= 3;
  13079. bits -= 3;
  13080. //---//
  13081. }
  13082. while (state.have < 19) {
  13083. state.lens[order[state.have++]] = 0;
  13084. }
  13085. // We have separate tables & no pointers. 2 commented lines below not needed.
  13086. //state.next = state.codes;
  13087. //state.lencode = state.next;
  13088. // Switch to use dynamic table
  13089. state.lencode = state.lendyn;
  13090. state.lenbits = 7;
  13091. opts = {bits: state.lenbits};
  13092. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  13093. state.lenbits = opts.bits;
  13094. if (ret) {
  13095. strm.msg = 'invalid code lengths set';
  13096. state.mode = BAD;
  13097. break;
  13098. }
  13099. //Tracev((stderr, "inflate: code lengths ok\n"));
  13100. state.have = 0;
  13101. state.mode = CODELENS;
  13102. /* falls through */
  13103. case CODELENS:
  13104. while (state.have < state.nlen + state.ndist) {
  13105. for (;;) {
  13106. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  13107. here_bits = here >>> 24;
  13108. here_op = (here >>> 16) & 0xff;
  13109. here_val = here & 0xffff;
  13110. if ((here_bits) <= bits) { break; }
  13111. //--- PULLBYTE() ---//
  13112. if (have === 0) { break inf_leave; }
  13113. have--;
  13114. hold += input[next++] << bits;
  13115. bits += 8;
  13116. //---//
  13117. }
  13118. if (here_val < 16) {
  13119. //--- DROPBITS(here.bits) ---//
  13120. hold >>>= here_bits;
  13121. bits -= here_bits;
  13122. //---//
  13123. state.lens[state.have++] = here_val;
  13124. }
  13125. else {
  13126. if (here_val === 16) {
  13127. //=== NEEDBITS(here.bits + 2);
  13128. n = here_bits + 2;
  13129. while (bits < n) {
  13130. if (have === 0) { break inf_leave; }
  13131. have--;
  13132. hold += input[next++] << bits;
  13133. bits += 8;
  13134. }
  13135. //===//
  13136. //--- DROPBITS(here.bits) ---//
  13137. hold >>>= here_bits;
  13138. bits -= here_bits;
  13139. //---//
  13140. if (state.have === 0) {
  13141. strm.msg = 'invalid bit length repeat';
  13142. state.mode = BAD;
  13143. break;
  13144. }
  13145. len = state.lens[state.have - 1];
  13146. copy = 3 + (hold & 0x03);//BITS(2);
  13147. //--- DROPBITS(2) ---//
  13148. hold >>>= 2;
  13149. bits -= 2;
  13150. //---//
  13151. }
  13152. else if (here_val === 17) {
  13153. //=== NEEDBITS(here.bits + 3);
  13154. n = here_bits + 3;
  13155. while (bits < n) {
  13156. if (have === 0) { break inf_leave; }
  13157. have--;
  13158. hold += input[next++] << bits;
  13159. bits += 8;
  13160. }
  13161. //===//
  13162. //--- DROPBITS(here.bits) ---//
  13163. hold >>>= here_bits;
  13164. bits -= here_bits;
  13165. //---//
  13166. len = 0;
  13167. copy = 3 + (hold & 0x07);//BITS(3);
  13168. //--- DROPBITS(3) ---//
  13169. hold >>>= 3;
  13170. bits -= 3;
  13171. //---//
  13172. }
  13173. else {
  13174. //=== NEEDBITS(here.bits + 7);
  13175. n = here_bits + 7;
  13176. while (bits < n) {
  13177. if (have === 0) { break inf_leave; }
  13178. have--;
  13179. hold += input[next++] << bits;
  13180. bits += 8;
  13181. }
  13182. //===//
  13183. //--- DROPBITS(here.bits) ---//
  13184. hold >>>= here_bits;
  13185. bits -= here_bits;
  13186. //---//
  13187. len = 0;
  13188. copy = 11 + (hold & 0x7f);//BITS(7);
  13189. //--- DROPBITS(7) ---//
  13190. hold >>>= 7;
  13191. bits -= 7;
  13192. //---//
  13193. }
  13194. if (state.have + copy > state.nlen + state.ndist) {
  13195. strm.msg = 'invalid bit length repeat';
  13196. state.mode = BAD;
  13197. break;
  13198. }
  13199. while (copy--) {
  13200. state.lens[state.have++] = len;
  13201. }
  13202. }
  13203. }
  13204. /* handle error breaks in while */
  13205. if (state.mode === BAD) { break; }
  13206. /* check for end-of-block code (better have one) */
  13207. if (state.lens[256] === 0) {
  13208. strm.msg = 'invalid code -- missing end-of-block';
  13209. state.mode = BAD;
  13210. break;
  13211. }
  13212. /* build code tables -- note: do not change the lenbits or distbits
  13213. values here (9 and 6) without reading the comments in inftrees.h
  13214. concerning the ENOUGH constants, which depend on those values */
  13215. state.lenbits = 9;
  13216. opts = {bits: state.lenbits};
  13217. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  13218. // We have separate tables & no pointers. 2 commented lines below not needed.
  13219. // state.next_index = opts.table_index;
  13220. state.lenbits = opts.bits;
  13221. // state.lencode = state.next;
  13222. if (ret) {
  13223. strm.msg = 'invalid literal/lengths set';
  13224. state.mode = BAD;
  13225. break;
  13226. }
  13227. state.distbits = 6;
  13228. //state.distcode.copy(state.codes);
  13229. // Switch to use dynamic table
  13230. state.distcode = state.distdyn;
  13231. opts = {bits: state.distbits};
  13232. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  13233. // We have separate tables & no pointers. 2 commented lines below not needed.
  13234. // state.next_index = opts.table_index;
  13235. state.distbits = opts.bits;
  13236. // state.distcode = state.next;
  13237. if (ret) {
  13238. strm.msg = 'invalid distances set';
  13239. state.mode = BAD;
  13240. break;
  13241. }
  13242. //Tracev((stderr, 'inflate: codes ok\n'));
  13243. state.mode = LEN_;
  13244. if (flush === Z_TREES) { break inf_leave; }
  13245. /* falls through */
  13246. case LEN_:
  13247. state.mode = LEN;
  13248. /* falls through */
  13249. case LEN:
  13250. if (have >= 6 && left >= 258) {
  13251. //--- RESTORE() ---
  13252. strm.next_out = put;
  13253. strm.avail_out = left;
  13254. strm.next_in = next;
  13255. strm.avail_in = have;
  13256. state.hold = hold;
  13257. state.bits = bits;
  13258. //---
  13259. inflate_fast(strm, _out);
  13260. //--- LOAD() ---
  13261. put = strm.next_out;
  13262. output = strm.output;
  13263. left = strm.avail_out;
  13264. next = strm.next_in;
  13265. input = strm.input;
  13266. have = strm.avail_in;
  13267. hold = state.hold;
  13268. bits = state.bits;
  13269. //---
  13270. if (state.mode === TYPE) {
  13271. state.back = -1;
  13272. }
  13273. break;
  13274. }
  13275. state.back = 0;
  13276. for (;;) {
  13277. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  13278. here_bits = here >>> 24;
  13279. here_op = (here >>> 16) & 0xff;
  13280. here_val = here & 0xffff;
  13281. if (here_bits <= bits) { break; }
  13282. //--- PULLBYTE() ---//
  13283. if (have === 0) { break inf_leave; }
  13284. have--;
  13285. hold += input[next++] << bits;
  13286. bits += 8;
  13287. //---//
  13288. }
  13289. if (here_op && (here_op & 0xf0) === 0) {
  13290. last_bits = here_bits;
  13291. last_op = here_op;
  13292. last_val = here_val;
  13293. for (;;) {
  13294. here = state.lencode[last_val +
  13295. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  13296. here_bits = here >>> 24;
  13297. here_op = (here >>> 16) & 0xff;
  13298. here_val = here & 0xffff;
  13299. if ((last_bits + here_bits) <= bits) { break; }
  13300. //--- PULLBYTE() ---//
  13301. if (have === 0) { break inf_leave; }
  13302. have--;
  13303. hold += input[next++] << bits;
  13304. bits += 8;
  13305. //---//
  13306. }
  13307. //--- DROPBITS(last.bits) ---//
  13308. hold >>>= last_bits;
  13309. bits -= last_bits;
  13310. //---//
  13311. state.back += last_bits;
  13312. }
  13313. //--- DROPBITS(here.bits) ---//
  13314. hold >>>= here_bits;
  13315. bits -= here_bits;
  13316. //---//
  13317. state.back += here_bits;
  13318. state.length = here_val;
  13319. if (here_op === 0) {
  13320. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  13321. // "inflate: literal '%c'\n" :
  13322. // "inflate: literal 0x%02x\n", here.val));
  13323. state.mode = LIT;
  13324. break;
  13325. }
  13326. if (here_op & 32) {
  13327. //Tracevv((stderr, "inflate: end of block\n"));
  13328. state.back = -1;
  13329. state.mode = TYPE;
  13330. break;
  13331. }
  13332. if (here_op & 64) {
  13333. strm.msg = 'invalid literal/length code';
  13334. state.mode = BAD;
  13335. break;
  13336. }
  13337. state.extra = here_op & 15;
  13338. state.mode = LENEXT;
  13339. /* falls through */
  13340. case LENEXT:
  13341. if (state.extra) {
  13342. //=== NEEDBITS(state.extra);
  13343. n = state.extra;
  13344. while (bits < n) {
  13345. if (have === 0) { break inf_leave; }
  13346. have--;
  13347. hold += input[next++] << bits;
  13348. bits += 8;
  13349. }
  13350. //===//
  13351. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  13352. //--- DROPBITS(state.extra) ---//
  13353. hold >>>= state.extra;
  13354. bits -= state.extra;
  13355. //---//
  13356. state.back += state.extra;
  13357. }
  13358. //Tracevv((stderr, "inflate: length %u\n", state.length));
  13359. state.was = state.length;
  13360. state.mode = DIST;
  13361. /* falls through */
  13362. case DIST:
  13363. for (;;) {
  13364. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  13365. here_bits = here >>> 24;
  13366. here_op = (here >>> 16) & 0xff;
  13367. here_val = here & 0xffff;
  13368. if ((here_bits) <= bits) { break; }
  13369. //--- PULLBYTE() ---//
  13370. if (have === 0) { break inf_leave; }
  13371. have--;
  13372. hold += input[next++] << bits;
  13373. bits += 8;
  13374. //---//
  13375. }
  13376. if ((here_op & 0xf0) === 0) {
  13377. last_bits = here_bits;
  13378. last_op = here_op;
  13379. last_val = here_val;
  13380. for (;;) {
  13381. here = state.distcode[last_val +
  13382. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  13383. here_bits = here >>> 24;
  13384. here_op = (here >>> 16) & 0xff;
  13385. here_val = here & 0xffff;
  13386. if ((last_bits + here_bits) <= bits) { break; }
  13387. //--- PULLBYTE() ---//
  13388. if (have === 0) { break inf_leave; }
  13389. have--;
  13390. hold += input[next++] << bits;
  13391. bits += 8;
  13392. //---//
  13393. }
  13394. //--- DROPBITS(last.bits) ---//
  13395. hold >>>= last_bits;
  13396. bits -= last_bits;
  13397. //---//
  13398. state.back += last_bits;
  13399. }
  13400. //--- DROPBITS(here.bits) ---//
  13401. hold >>>= here_bits;
  13402. bits -= here_bits;
  13403. //---//
  13404. state.back += here_bits;
  13405. if (here_op & 64) {
  13406. strm.msg = 'invalid distance code';
  13407. state.mode = BAD;
  13408. break;
  13409. }
  13410. state.offset = here_val;
  13411. state.extra = (here_op) & 15;
  13412. state.mode = DISTEXT;
  13413. /* falls through */
  13414. case DISTEXT:
  13415. if (state.extra) {
  13416. //=== NEEDBITS(state.extra);
  13417. n = state.extra;
  13418. while (bits < n) {
  13419. if (have === 0) { break inf_leave; }
  13420. have--;
  13421. hold += input[next++] << bits;
  13422. bits += 8;
  13423. }
  13424. //===//
  13425. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  13426. //--- DROPBITS(state.extra) ---//
  13427. hold >>>= state.extra;
  13428. bits -= state.extra;
  13429. //---//
  13430. state.back += state.extra;
  13431. }
  13432. //#ifdef INFLATE_STRICT
  13433. if (state.offset > state.dmax) {
  13434. strm.msg = 'invalid distance too far back';
  13435. state.mode = BAD;
  13436. break;
  13437. }
  13438. //#endif
  13439. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  13440. state.mode = MATCH;
  13441. /* falls through */
  13442. case MATCH:
  13443. if (left === 0) { break inf_leave; }
  13444. copy = _out - left;
  13445. if (state.offset > copy) { /* copy from window */
  13446. copy = state.offset - copy;
  13447. if (copy > state.whave) {
  13448. if (state.sane) {
  13449. strm.msg = 'invalid distance too far back';
  13450. state.mode = BAD;
  13451. break;
  13452. }
  13453. // (!) This block is disabled in zlib defailts,
  13454. // don't enable it for binary compatibility
  13455. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  13456. // Trace((stderr, "inflate.c too far\n"));
  13457. // copy -= state.whave;
  13458. // if (copy > state.length) { copy = state.length; }
  13459. // if (copy > left) { copy = left; }
  13460. // left -= copy;
  13461. // state.length -= copy;
  13462. // do {
  13463. // output[put++] = 0;
  13464. // } while (--copy);
  13465. // if (state.length === 0) { state.mode = LEN; }
  13466. // break;
  13467. //#endif
  13468. }
  13469. if (copy > state.wnext) {
  13470. copy -= state.wnext;
  13471. from = state.wsize - copy;
  13472. }
  13473. else {
  13474. from = state.wnext - copy;
  13475. }
  13476. if (copy > state.length) { copy = state.length; }
  13477. from_source = state.window;
  13478. }
  13479. else { /* copy from output */
  13480. from_source = output;
  13481. from = put - state.offset;
  13482. copy = state.length;
  13483. }
  13484. if (copy > left) { copy = left; }
  13485. left -= copy;
  13486. state.length -= copy;
  13487. do {
  13488. output[put++] = from_source[from++];
  13489. } while (--copy);
  13490. if (state.length === 0) { state.mode = LEN; }
  13491. break;
  13492. case LIT:
  13493. if (left === 0) { break inf_leave; }
  13494. output[put++] = state.length;
  13495. left--;
  13496. state.mode = LEN;
  13497. break;
  13498. case CHECK:
  13499. if (state.wrap) {
  13500. //=== NEEDBITS(32);
  13501. while (bits < 32) {
  13502. if (have === 0) { break inf_leave; }
  13503. have--;
  13504. // Use '|' insdead of '+' to make sure that result is signed
  13505. hold |= input[next++] << bits;
  13506. bits += 8;
  13507. }
  13508. //===//
  13509. _out -= left;
  13510. strm.total_out += _out;
  13511. state.total += _out;
  13512. if (_out) {
  13513. strm.adler = state.check =
  13514. /*UPDATE(state.check, put - _out, _out);*/
  13515. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  13516. }
  13517. _out = left;
  13518. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  13519. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  13520. strm.msg = 'incorrect data check';
  13521. state.mode = BAD;
  13522. break;
  13523. }
  13524. //=== INITBITS();
  13525. hold = 0;
  13526. bits = 0;
  13527. //===//
  13528. //Tracev((stderr, "inflate: check matches trailer\n"));
  13529. }
  13530. state.mode = LENGTH;
  13531. /* falls through */
  13532. case LENGTH:
  13533. if (state.wrap && state.flags) {
  13534. //=== NEEDBITS(32);
  13535. while (bits < 32) {
  13536. if (have === 0) { break inf_leave; }
  13537. have--;
  13538. hold += input[next++] << bits;
  13539. bits += 8;
  13540. }
  13541. //===//
  13542. if (hold !== (state.total & 0xffffffff)) {
  13543. strm.msg = 'incorrect length check';
  13544. state.mode = BAD;
  13545. break;
  13546. }
  13547. //=== INITBITS();
  13548. hold = 0;
  13549. bits = 0;
  13550. //===//
  13551. //Tracev((stderr, "inflate: length matches trailer\n"));
  13552. }
  13553. state.mode = DONE;
  13554. /* falls through */
  13555. case DONE:
  13556. ret = Z_STREAM_END;
  13557. break inf_leave;
  13558. case BAD:
  13559. ret = Z_DATA_ERROR;
  13560. break inf_leave;
  13561. case MEM:
  13562. return Z_MEM_ERROR;
  13563. case SYNC:
  13564. /* falls through */
  13565. default:
  13566. return Z_STREAM_ERROR;
  13567. }
  13568. }
  13569. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  13570. /*
  13571. Return from inflate(), updating the total counts and the check value.
  13572. If there was no progress during the inflate() call, return a buffer
  13573. error. Call updatewindow() to create and/or update the window state.
  13574. Note: a memory error from inflate() is non-recoverable.
  13575. */
  13576. //--- RESTORE() ---
  13577. strm.next_out = put;
  13578. strm.avail_out = left;
  13579. strm.next_in = next;
  13580. strm.avail_in = have;
  13581. state.hold = hold;
  13582. state.bits = bits;
  13583. //---
  13584. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  13585. (state.mode < CHECK || flush !== Z_FINISH))) {
  13586. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  13587. state.mode = MEM;
  13588. return Z_MEM_ERROR;
  13589. }
  13590. }
  13591. _in -= strm.avail_in;
  13592. _out -= strm.avail_out;
  13593. strm.total_in += _in;
  13594. strm.total_out += _out;
  13595. state.total += _out;
  13596. if (state.wrap && _out) {
  13597. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  13598. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  13599. }
  13600. strm.data_type = state.bits + (state.last ? 64 : 0) +
  13601. (state.mode === TYPE ? 128 : 0) +
  13602. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  13603. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  13604. ret = Z_BUF_ERROR;
  13605. }
  13606. return ret;
  13607. }
  13608. function inflateEnd(strm) {
  13609. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  13610. return Z_STREAM_ERROR;
  13611. }
  13612. var state = strm.state;
  13613. if (state.window) {
  13614. state.window = null;
  13615. }
  13616. strm.state = null;
  13617. return Z_OK;
  13618. }
  13619. function inflateGetHeader(strm, head) {
  13620. var state;
  13621. /* check state */
  13622. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  13623. state = strm.state;
  13624. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  13625. /* save header structure */
  13626. state.head = head;
  13627. head.done = false;
  13628. return Z_OK;
  13629. }
  13630. exports.inflateReset = inflateReset;
  13631. exports.inflateReset2 = inflateReset2;
  13632. exports.inflateResetKeep = inflateResetKeep;
  13633. exports.inflateInit = inflateInit;
  13634. exports.inflateInit2 = inflateInit2;
  13635. exports.inflate = inflate;
  13636. exports.inflateEnd = inflateEnd;
  13637. exports.inflateGetHeader = inflateGetHeader;
  13638. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  13639. /* Not implemented
  13640. exports.inflateCopy = inflateCopy;
  13641. exports.inflateGetDictionary = inflateGetDictionary;
  13642. exports.inflateMark = inflateMark;
  13643. exports.inflatePrime = inflatePrime;
  13644. exports.inflateSetDictionary = inflateSetDictionary;
  13645. exports.inflateSync = inflateSync;
  13646. exports.inflateSyncPoint = inflateSyncPoint;
  13647. exports.inflateUndermine = inflateUndermine;
  13648. */
  13649. },{"../utils/common":35,"./adler32":37,"./crc32":39,"./inffast":42,"./inftrees":44}],44:[function(require,module,exports){
  13650. 'use strict';
  13651. var utils = require('../utils/common');
  13652. var MAXBITS = 15;
  13653. var ENOUGH_LENS = 852;
  13654. var ENOUGH_DISTS = 592;
  13655. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  13656. var CODES = 0;
  13657. var LENS = 1;
  13658. var DISTS = 2;
  13659. var lbase = [ /* Length codes 257..285 base */
  13660. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  13661. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  13662. ];
  13663. var lext = [ /* Length codes 257..285 extra */
  13664. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  13665. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  13666. ];
  13667. var dbase = [ /* Distance codes 0..29 base */
  13668. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  13669. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  13670. 8193, 12289, 16385, 24577, 0, 0
  13671. ];
  13672. var dext = [ /* Distance codes 0..29 extra */
  13673. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  13674. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  13675. 28, 28, 29, 29, 64, 64
  13676. ];
  13677. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  13678. {
  13679. var bits = opts.bits;
  13680. //here = opts.here; /* table entry for duplication */
  13681. var len = 0; /* a code's length in bits */
  13682. var sym = 0; /* index of code symbols */
  13683. var min = 0, max = 0; /* minimum and maximum code lengths */
  13684. var root = 0; /* number of index bits for root table */
  13685. var curr = 0; /* number of index bits for current table */
  13686. var drop = 0; /* code bits to drop for sub-table */
  13687. var left = 0; /* number of prefix codes available */
  13688. var used = 0; /* code entries in table used */
  13689. var huff = 0; /* Huffman code */
  13690. var incr; /* for incrementing code, index */
  13691. var fill; /* index for replicating entries */
  13692. var low; /* low bits for current root entry */
  13693. var mask; /* mask for low root bits */
  13694. var next; /* next available space in table */
  13695. var base = null; /* base value table to use */
  13696. var base_index = 0;
  13697. // var shoextra; /* extra bits table to use */
  13698. var end; /* use base and extra for symbol > end */
  13699. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  13700. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  13701. var extra = null;
  13702. var extra_index = 0;
  13703. var here_bits, here_op, here_val;
  13704. /*
  13705. Process a set of code lengths to create a canonical Huffman code. The
  13706. code lengths are lens[0..codes-1]. Each length corresponds to the
  13707. symbols 0..codes-1. The Huffman code is generated by first sorting the
  13708. symbols by length from short to long, and retaining the symbol order
  13709. for codes with equal lengths. Then the code starts with all zero bits
  13710. for the first code of the shortest length, and the codes are integer
  13711. increments for the same length, and zeros are appended as the length
  13712. increases. For the deflate format, these bits are stored backwards
  13713. from their more natural integer increment ordering, and so when the
  13714. decoding tables are built in the large loop below, the integer codes
  13715. are incremented backwards.
  13716. This routine assumes, but does not check, that all of the entries in
  13717. lens[] are in the range 0..MAXBITS. The caller must assure this.
  13718. 1..MAXBITS is interpreted as that code length. zero means that that
  13719. symbol does not occur in this code.
  13720. The codes are sorted by computing a count of codes for each length,
  13721. creating from that a table of starting indices for each length in the
  13722. sorted table, and then entering the symbols in order in the sorted
  13723. table. The sorted table is work[], with that space being provided by
  13724. the caller.
  13725. The length counts are used for other purposes as well, i.e. finding
  13726. the minimum and maximum length codes, determining if there are any
  13727. codes at all, checking for a valid set of lengths, and looking ahead
  13728. at length counts to determine sub-table sizes when building the
  13729. decoding tables.
  13730. */
  13731. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  13732. for (len = 0; len <= MAXBITS; len++) {
  13733. count[len] = 0;
  13734. }
  13735. for (sym = 0; sym < codes; sym++) {
  13736. count[lens[lens_index + sym]]++;
  13737. }
  13738. /* bound code lengths, force root to be within code lengths */
  13739. root = bits;
  13740. for (max = MAXBITS; max >= 1; max--) {
  13741. if (count[max] !== 0) { break; }
  13742. }
  13743. if (root > max) {
  13744. root = max;
  13745. }
  13746. if (max === 0) { /* no symbols to code at all */
  13747. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  13748. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  13749. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  13750. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  13751. //table.op[opts.table_index] = 64;
  13752. //table.bits[opts.table_index] = 1;
  13753. //table.val[opts.table_index++] = 0;
  13754. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  13755. opts.bits = 1;
  13756. return 0; /* no symbols, but wait for decoding to report error */
  13757. }
  13758. for (min = 1; min < max; min++) {
  13759. if (count[min] !== 0) { break; }
  13760. }
  13761. if (root < min) {
  13762. root = min;
  13763. }
  13764. /* check for an over-subscribed or incomplete set of lengths */
  13765. left = 1;
  13766. for (len = 1; len <= MAXBITS; len++) {
  13767. left <<= 1;
  13768. left -= count[len];
  13769. if (left < 0) {
  13770. return -1;
  13771. } /* over-subscribed */
  13772. }
  13773. if (left > 0 && (type === CODES || max !== 1)) {
  13774. return -1; /* incomplete set */
  13775. }
  13776. /* generate offsets into symbol table for each length for sorting */
  13777. offs[1] = 0;
  13778. for (len = 1; len < MAXBITS; len++) {
  13779. offs[len + 1] = offs[len] + count[len];
  13780. }
  13781. /* sort symbols by length, by symbol order within each length */
  13782. for (sym = 0; sym < codes; sym++) {
  13783. if (lens[lens_index + sym] !== 0) {
  13784. work[offs[lens[lens_index + sym]]++] = sym;
  13785. }
  13786. }
  13787. /*
  13788. Create and fill in decoding tables. In this loop, the table being
  13789. filled is at next and has curr index bits. The code being used is huff
  13790. with length len. That code is converted to an index by dropping drop
  13791. bits off of the bottom. For codes where len is less than drop + curr,
  13792. those top drop + curr - len bits are incremented through all values to
  13793. fill the table with replicated entries.
  13794. root is the number of index bits for the root table. When len exceeds
  13795. root, sub-tables are created pointed to by the root entry with an index
  13796. of the low root bits of huff. This is saved in low to check for when a
  13797. new sub-table should be started. drop is zero when the root table is
  13798. being filled, and drop is root when sub-tables are being filled.
  13799. When a new sub-table is needed, it is necessary to look ahead in the
  13800. code lengths to determine what size sub-table is needed. The length
  13801. counts are used for this, and so count[] is decremented as codes are
  13802. entered in the tables.
  13803. used keeps track of how many table entries have been allocated from the
  13804. provided *table space. It is checked for LENS and DIST tables against
  13805. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  13806. the initial root table size constants. See the comments in inftrees.h
  13807. for more information.
  13808. sym increments through all symbols, and the loop terminates when
  13809. all codes of length max, i.e. all codes, have been processed. This
  13810. routine permits incomplete codes, so another loop after this one fills
  13811. in the rest of the decoding tables with invalid code markers.
  13812. */
  13813. /* set up for code type */
  13814. // poor man optimization - use if-else instead of switch,
  13815. // to avoid deopts in old v8
  13816. if (type === CODES) {
  13817. base = extra = work; /* dummy value--not used */
  13818. end = 19;
  13819. } else if (type === LENS) {
  13820. base = lbase;
  13821. base_index -= 257;
  13822. extra = lext;
  13823. extra_index -= 257;
  13824. end = 256;
  13825. } else { /* DISTS */
  13826. base = dbase;
  13827. extra = dext;
  13828. end = -1;
  13829. }
  13830. /* initialize opts for loop */
  13831. huff = 0; /* starting code */
  13832. sym = 0; /* starting code symbol */
  13833. len = min; /* starting code length */
  13834. next = table_index; /* current table to fill in */
  13835. curr = root; /* current table index bits */
  13836. drop = 0; /* current bits to drop from code for index */
  13837. low = -1; /* trigger new sub-table when len > root */
  13838. used = 1 << root; /* use root table entries */
  13839. mask = used - 1; /* mask for comparing low */
  13840. /* check available table space */
  13841. if ((type === LENS && used > ENOUGH_LENS) ||
  13842. (type === DISTS && used > ENOUGH_DISTS)) {
  13843. return 1;
  13844. }
  13845. var i=0;
  13846. /* process all codes and make table entries */
  13847. for (;;) {
  13848. i++;
  13849. /* create table entry */
  13850. here_bits = len - drop;
  13851. if (work[sym] < end) {
  13852. here_op = 0;
  13853. here_val = work[sym];
  13854. }
  13855. else if (work[sym] > end) {
  13856. here_op = extra[extra_index + work[sym]];
  13857. here_val = base[base_index + work[sym]];
  13858. }
  13859. else {
  13860. here_op = 32 + 64; /* end of block */
  13861. here_val = 0;
  13862. }
  13863. /* replicate for those indices with low len bits equal to huff */
  13864. incr = 1 << (len - drop);
  13865. fill = 1 << curr;
  13866. min = fill; /* save offset to next table */
  13867. do {
  13868. fill -= incr;
  13869. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  13870. } while (fill !== 0);
  13871. /* backwards increment the len-bit code huff */
  13872. incr = 1 << (len - 1);
  13873. while (huff & incr) {
  13874. incr >>= 1;
  13875. }
  13876. if (incr !== 0) {
  13877. huff &= incr - 1;
  13878. huff += incr;
  13879. } else {
  13880. huff = 0;
  13881. }
  13882. /* go to next symbol, update count, len */
  13883. sym++;
  13884. if (--count[len] === 0) {
  13885. if (len === max) { break; }
  13886. len = lens[lens_index + work[sym]];
  13887. }
  13888. /* create new sub-table if needed */
  13889. if (len > root && (huff & mask) !== low) {
  13890. /* if first time, transition to sub-tables */
  13891. if (drop === 0) {
  13892. drop = root;
  13893. }
  13894. /* increment past last table */
  13895. next += min; /* here min is 1 << curr */
  13896. /* determine length of next table */
  13897. curr = len - drop;
  13898. left = 1 << curr;
  13899. while (curr + drop < max) {
  13900. left -= count[curr + drop];
  13901. if (left <= 0) { break; }
  13902. curr++;
  13903. left <<= 1;
  13904. }
  13905. /* check for enough space */
  13906. used += 1 << curr;
  13907. if ((type === LENS && used > ENOUGH_LENS) ||
  13908. (type === DISTS && used > ENOUGH_DISTS)) {
  13909. return 1;
  13910. }
  13911. /* point entry in root table to sub-table */
  13912. low = huff & mask;
  13913. /*table.op[low] = curr;
  13914. table.bits[low] = root;
  13915. table.val[low] = next - opts.table_index;*/
  13916. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  13917. }
  13918. }
  13919. /* fill in remaining table entry if code is incomplete (guaranteed to have
  13920. at most one remaining entry, since if the code is incomplete, the
  13921. maximum code length that was allowed to get this far is one bit) */
  13922. if (huff !== 0) {
  13923. //table.op[next + huff] = 64; /* invalid code marker */
  13924. //table.bits[next + huff] = len - drop;
  13925. //table.val[next + huff] = 0;
  13926. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  13927. }
  13928. /* set return parameters */
  13929. //opts.table_index += used;
  13930. opts.bits = root;
  13931. return 0;
  13932. };
  13933. },{"../utils/common":35}],45:[function(require,module,exports){
  13934. 'use strict';
  13935. module.exports = {
  13936. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  13937. '1': 'stream end', /* Z_STREAM_END 1 */
  13938. '0': '', /* Z_OK 0 */
  13939. '-1': 'file error', /* Z_ERRNO (-1) */
  13940. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  13941. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  13942. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  13943. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  13944. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  13945. };
  13946. },{}],46:[function(require,module,exports){
  13947. 'use strict';
  13948. var utils = require('../utils/common');
  13949. /* Public constants ==========================================================*/
  13950. /* ===========================================================================*/
  13951. //var Z_FILTERED = 1;
  13952. //var Z_HUFFMAN_ONLY = 2;
  13953. //var Z_RLE = 3;
  13954. var Z_FIXED = 4;
  13955. //var Z_DEFAULT_STRATEGY = 0;
  13956. /* Possible values of the data_type field (though see inflate()) */
  13957. var Z_BINARY = 0;
  13958. var Z_TEXT = 1;
  13959. //var Z_ASCII = 1; // = Z_TEXT
  13960. var Z_UNKNOWN = 2;
  13961. /*============================================================================*/
  13962. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  13963. // From zutil.h
  13964. var STORED_BLOCK = 0;
  13965. var STATIC_TREES = 1;
  13966. var DYN_TREES = 2;
  13967. /* The three kinds of block type */
  13968. var MIN_MATCH = 3;
  13969. var MAX_MATCH = 258;
  13970. /* The minimum and maximum match lengths */
  13971. // From deflate.h
  13972. /* ===========================================================================
  13973. * Internal compression state.
  13974. */
  13975. var LENGTH_CODES = 29;
  13976. /* number of length codes, not counting the special END_BLOCK code */
  13977. var LITERALS = 256;
  13978. /* number of literal bytes 0..255 */
  13979. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  13980. /* number of Literal or Length codes, including the END_BLOCK code */
  13981. var D_CODES = 30;
  13982. /* number of distance codes */
  13983. var BL_CODES = 19;
  13984. /* number of codes used to transfer the bit lengths */
  13985. var HEAP_SIZE = 2*L_CODES + 1;
  13986. /* maximum heap size */
  13987. var MAX_BITS = 15;
  13988. /* All codes must not exceed MAX_BITS bits */
  13989. var Buf_size = 16;
  13990. /* size of bit buffer in bi_buf */
  13991. /* ===========================================================================
  13992. * Constants
  13993. */
  13994. var MAX_BL_BITS = 7;
  13995. /* Bit length codes must not exceed MAX_BL_BITS bits */
  13996. var END_BLOCK = 256;
  13997. /* end of block literal code */
  13998. var REP_3_6 = 16;
  13999. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  14000. var REPZ_3_10 = 17;
  14001. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  14002. var REPZ_11_138 = 18;
  14003. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  14004. var extra_lbits = /* extra bits for each length code */
  14005. [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];
  14006. var extra_dbits = /* extra bits for each distance code */
  14007. [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];
  14008. var extra_blbits = /* extra bits for each bit length code */
  14009. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  14010. var bl_order =
  14011. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  14012. /* The lengths of the bit length codes are sent in order of decreasing
  14013. * probability, to avoid transmitting the lengths for unused bit length codes.
  14014. */
  14015. /* ===========================================================================
  14016. * Local data. These are initialized only once.
  14017. */
  14018. // We pre-fill arrays with 0 to avoid uninitialized gaps
  14019. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  14020. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  14021. var static_ltree = new Array((L_CODES+2) * 2);
  14022. zero(static_ltree);
  14023. /* The static literal tree. Since the bit lengths are imposed, there is no
  14024. * need for the L_CODES extra codes used during heap construction. However
  14025. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  14026. * below).
  14027. */
  14028. var static_dtree = new Array(D_CODES * 2);
  14029. zero(static_dtree);
  14030. /* The static distance tree. (Actually a trivial tree since all codes use
  14031. * 5 bits.)
  14032. */
  14033. var _dist_code = new Array(DIST_CODE_LEN);
  14034. zero(_dist_code);
  14035. /* Distance codes. The first 256 values correspond to the distances
  14036. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  14037. * the 15 bit distances.
  14038. */
  14039. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  14040. zero(_length_code);
  14041. /* length code for each normalized match length (0 == MIN_MATCH) */
  14042. var base_length = new Array(LENGTH_CODES);
  14043. zero(base_length);
  14044. /* First normalized length for each code (0 = MIN_MATCH) */
  14045. var base_dist = new Array(D_CODES);
  14046. zero(base_dist);
  14047. /* First normalized distance for each code (0 = distance of 1) */
  14048. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  14049. this.static_tree = static_tree; /* static tree or NULL */
  14050. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  14051. this.extra_base = extra_base; /* base index for extra_bits */
  14052. this.elems = elems; /* max number of elements in the tree */
  14053. this.max_length = max_length; /* max bit length for the codes */
  14054. // show if `static_tree` has data or dummy - needed for monomorphic objects
  14055. this.has_stree = static_tree && static_tree.length;
  14056. };
  14057. var static_l_desc;
  14058. var static_d_desc;
  14059. var static_bl_desc;
  14060. var TreeDesc = function(dyn_tree, stat_desc) {
  14061. this.dyn_tree = dyn_tree; /* the dynamic tree */
  14062. this.max_code = 0; /* largest code with non zero frequency */
  14063. this.stat_desc = stat_desc; /* the corresponding static tree */
  14064. };
  14065. function d_code(dist) {
  14066. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  14067. }
  14068. /* ===========================================================================
  14069. * Output a short LSB first on the stream.
  14070. * IN assertion: there is enough room in pendingBuf.
  14071. */
  14072. function put_short (s, w) {
  14073. // put_byte(s, (uch)((w) & 0xff));
  14074. // put_byte(s, (uch)((ush)(w) >> 8));
  14075. s.pending_buf[s.pending++] = (w) & 0xff;
  14076. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  14077. }
  14078. /* ===========================================================================
  14079. * Send a value on a given number of bits.
  14080. * IN assertion: length <= 16 and value fits in length bits.
  14081. */
  14082. function send_bits(s, value, length) {
  14083. if (s.bi_valid > (Buf_size - length)) {
  14084. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  14085. put_short(s, s.bi_buf);
  14086. s.bi_buf = value >> (Buf_size - s.bi_valid);
  14087. s.bi_valid += length - Buf_size;
  14088. } else {
  14089. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  14090. s.bi_valid += length;
  14091. }
  14092. }
  14093. function send_code(s, c, tree) {
  14094. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  14095. }
  14096. /* ===========================================================================
  14097. * Reverse the first len bits of a code, using straightforward code (a faster
  14098. * method would use a table)
  14099. * IN assertion: 1 <= len <= 15
  14100. */
  14101. function bi_reverse(code, len) {
  14102. var res = 0;
  14103. do {
  14104. res |= code & 1;
  14105. code >>>= 1;
  14106. res <<= 1;
  14107. } while (--len > 0);
  14108. return res >>> 1;
  14109. }
  14110. /* ===========================================================================
  14111. * Flush the bit buffer, keeping at most 7 bits in it.
  14112. */
  14113. function bi_flush(s) {
  14114. if (s.bi_valid === 16) {
  14115. put_short(s, s.bi_buf);
  14116. s.bi_buf = 0;
  14117. s.bi_valid = 0;
  14118. } else if (s.bi_valid >= 8) {
  14119. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  14120. s.bi_buf >>= 8;
  14121. s.bi_valid -= 8;
  14122. }
  14123. }
  14124. /* ===========================================================================
  14125. * Compute the optimal bit lengths for a tree and update the total bit length
  14126. * for the current block.
  14127. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  14128. * above are the tree nodes sorted by increasing frequency.
  14129. * OUT assertions: the field len is set to the optimal bit length, the
  14130. * array bl_count contains the frequencies for each bit length.
  14131. * The length opt_len is updated; static_len is also updated if stree is
  14132. * not null.
  14133. */
  14134. function gen_bitlen(s, desc)
  14135. // deflate_state *s;
  14136. // tree_desc *desc; /* the tree descriptor */
  14137. {
  14138. var tree = desc.dyn_tree;
  14139. var max_code = desc.max_code;
  14140. var stree = desc.stat_desc.static_tree;
  14141. var has_stree = desc.stat_desc.has_stree;
  14142. var extra = desc.stat_desc.extra_bits;
  14143. var base = desc.stat_desc.extra_base;
  14144. var max_length = desc.stat_desc.max_length;
  14145. var h; /* heap index */
  14146. var n, m; /* iterate over the tree elements */
  14147. var bits; /* bit length */
  14148. var xbits; /* extra bits */
  14149. var f; /* frequency */
  14150. var overflow = 0; /* number of elements with bit length too large */
  14151. for (bits = 0; bits <= MAX_BITS; bits++) {
  14152. s.bl_count[bits] = 0;
  14153. }
  14154. /* In a first pass, compute the optimal bit lengths (which may
  14155. * overflow in the case of the bit length tree).
  14156. */
  14157. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  14158. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  14159. n = s.heap[h];
  14160. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  14161. if (bits > max_length) {
  14162. bits = max_length;
  14163. overflow++;
  14164. }
  14165. tree[n*2 + 1]/*.Len*/ = bits;
  14166. /* We overwrite tree[n].Dad which is no longer needed */
  14167. if (n > max_code) { continue; } /* not a leaf node */
  14168. s.bl_count[bits]++;
  14169. xbits = 0;
  14170. if (n >= base) {
  14171. xbits = extra[n-base];
  14172. }
  14173. f = tree[n * 2]/*.Freq*/;
  14174. s.opt_len += f * (bits + xbits);
  14175. if (has_stree) {
  14176. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  14177. }
  14178. }
  14179. if (overflow === 0) { return; }
  14180. // Trace((stderr,"\nbit length overflow\n"));
  14181. /* This happens for example on obj2 and pic of the Calgary corpus */
  14182. /* Find the first bit length which could increase: */
  14183. do {
  14184. bits = max_length-1;
  14185. while (s.bl_count[bits] === 0) { bits--; }
  14186. s.bl_count[bits]--; /* move one leaf down the tree */
  14187. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  14188. s.bl_count[max_length]--;
  14189. /* The brother of the overflow item also moves one step up,
  14190. * but this does not affect bl_count[max_length]
  14191. */
  14192. overflow -= 2;
  14193. } while (overflow > 0);
  14194. /* Now recompute all bit lengths, scanning in increasing frequency.
  14195. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  14196. * lengths instead of fixing only the wrong ones. This idea is taken
  14197. * from 'ar' written by Haruhiko Okumura.)
  14198. */
  14199. for (bits = max_length; bits !== 0; bits--) {
  14200. n = s.bl_count[bits];
  14201. while (n !== 0) {
  14202. m = s.heap[--h];
  14203. if (m > max_code) { continue; }
  14204. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  14205. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  14206. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  14207. tree[m*2 + 1]/*.Len*/ = bits;
  14208. }
  14209. n--;
  14210. }
  14211. }
  14212. }
  14213. /* ===========================================================================
  14214. * Generate the codes for a given tree and bit counts (which need not be
  14215. * optimal).
  14216. * IN assertion: the array bl_count contains the bit length statistics for
  14217. * the given tree and the field len is set for all tree elements.
  14218. * OUT assertion: the field code is set for all tree elements of non
  14219. * zero code length.
  14220. */
  14221. function gen_codes(tree, max_code, bl_count)
  14222. // ct_data *tree; /* the tree to decorate */
  14223. // int max_code; /* largest code with non zero frequency */
  14224. // ushf *bl_count; /* number of codes at each bit length */
  14225. {
  14226. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  14227. var code = 0; /* running code value */
  14228. var bits; /* bit index */
  14229. var n; /* code index */
  14230. /* The distribution counts are first used to generate the code values
  14231. * without bit reversal.
  14232. */
  14233. for (bits = 1; bits <= MAX_BITS; bits++) {
  14234. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  14235. }
  14236. /* Check that the bit counts in bl_count are consistent. The last code
  14237. * must be all ones.
  14238. */
  14239. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  14240. // "inconsistent bit counts");
  14241. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  14242. for (n = 0; n <= max_code; n++) {
  14243. var len = tree[n*2 + 1]/*.Len*/;
  14244. if (len === 0) { continue; }
  14245. /* Now reverse the bits */
  14246. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  14247. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  14248. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  14249. }
  14250. }
  14251. /* ===========================================================================
  14252. * Initialize the various 'constant' tables.
  14253. */
  14254. function tr_static_init() {
  14255. var n; /* iterates over tree elements */
  14256. var bits; /* bit counter */
  14257. var length; /* length value */
  14258. var code; /* code value */
  14259. var dist; /* distance index */
  14260. var bl_count = new Array(MAX_BITS+1);
  14261. /* number of codes at each bit length for an optimal tree */
  14262. // do check in _tr_init()
  14263. //if (static_init_done) return;
  14264. /* For some embedded targets, global variables are not initialized: */
  14265. /*#ifdef NO_INIT_GLOBAL_POINTERS
  14266. static_l_desc.static_tree = static_ltree;
  14267. static_l_desc.extra_bits = extra_lbits;
  14268. static_d_desc.static_tree = static_dtree;
  14269. static_d_desc.extra_bits = extra_dbits;
  14270. static_bl_desc.extra_bits = extra_blbits;
  14271. #endif*/
  14272. /* Initialize the mapping length (0..255) -> length code (0..28) */
  14273. length = 0;
  14274. for (code = 0; code < LENGTH_CODES-1; code++) {
  14275. base_length[code] = length;
  14276. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  14277. _length_code[length++] = code;
  14278. }
  14279. }
  14280. //Assert (length == 256, "tr_static_init: length != 256");
  14281. /* Note that the length 255 (match length 258) can be represented
  14282. * in two different ways: code 284 + 5 bits or code 285, so we
  14283. * overwrite length_code[255] to use the best encoding:
  14284. */
  14285. _length_code[length-1] = code;
  14286. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  14287. dist = 0;
  14288. for (code = 0 ; code < 16; code++) {
  14289. base_dist[code] = dist;
  14290. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  14291. _dist_code[dist++] = code;
  14292. }
  14293. }
  14294. //Assert (dist == 256, "tr_static_init: dist != 256");
  14295. dist >>= 7; /* from now on, all distances are divided by 128 */
  14296. for (; code < D_CODES; code++) {
  14297. base_dist[code] = dist << 7;
  14298. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  14299. _dist_code[256 + dist++] = code;
  14300. }
  14301. }
  14302. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  14303. /* Construct the codes of the static literal tree */
  14304. for (bits = 0; bits <= MAX_BITS; bits++) {
  14305. bl_count[bits] = 0;
  14306. }
  14307. n = 0;
  14308. while (n <= 143) {
  14309. static_ltree[n*2 + 1]/*.Len*/ = 8;
  14310. n++;
  14311. bl_count[8]++;
  14312. }
  14313. while (n <= 255) {
  14314. static_ltree[n*2 + 1]/*.Len*/ = 9;
  14315. n++;
  14316. bl_count[9]++;
  14317. }
  14318. while (n <= 279) {
  14319. static_ltree[n*2 + 1]/*.Len*/ = 7;
  14320. n++;
  14321. bl_count[7]++;
  14322. }
  14323. while (n <= 287) {
  14324. static_ltree[n*2 + 1]/*.Len*/ = 8;
  14325. n++;
  14326. bl_count[8]++;
  14327. }
  14328. /* Codes 286 and 287 do not exist, but we must include them in the
  14329. * tree construction to get a canonical Huffman tree (longest code
  14330. * all ones)
  14331. */
  14332. gen_codes(static_ltree, L_CODES+1, bl_count);
  14333. /* The static distance tree is trivial: */
  14334. for (n = 0; n < D_CODES; n++) {
  14335. static_dtree[n*2 + 1]/*.Len*/ = 5;
  14336. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  14337. }
  14338. // Now data ready and we can init static trees
  14339. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  14340. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  14341. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  14342. //static_init_done = true;
  14343. }
  14344. /* ===========================================================================
  14345. * Initialize a new block.
  14346. */
  14347. function init_block(s) {
  14348. var n; /* iterates over tree elements */
  14349. /* Initialize the trees. */
  14350. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  14351. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  14352. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  14353. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  14354. s.opt_len = s.static_len = 0;
  14355. s.last_lit = s.matches = 0;
  14356. }
  14357. /* ===========================================================================
  14358. * Flush the bit buffer and align the output on a byte boundary
  14359. */
  14360. function bi_windup(s)
  14361. {
  14362. if (s.bi_valid > 8) {
  14363. put_short(s, s.bi_buf);
  14364. } else if (s.bi_valid > 0) {
  14365. //put_byte(s, (Byte)s->bi_buf);
  14366. s.pending_buf[s.pending++] = s.bi_buf;
  14367. }
  14368. s.bi_buf = 0;
  14369. s.bi_valid = 0;
  14370. }
  14371. /* ===========================================================================
  14372. * Copy a stored block, storing first the length and its
  14373. * one's complement if requested.
  14374. */
  14375. function copy_block(s, buf, len, header)
  14376. //DeflateState *s;
  14377. //charf *buf; /* the input data */
  14378. //unsigned len; /* its length */
  14379. //int header; /* true if block header must be written */
  14380. {
  14381. bi_windup(s); /* align on byte boundary */
  14382. if (header) {
  14383. put_short(s, len);
  14384. put_short(s, ~len);
  14385. }
  14386. // while (len--) {
  14387. // put_byte(s, *buf++);
  14388. // }
  14389. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  14390. s.pending += len;
  14391. }
  14392. /* ===========================================================================
  14393. * Compares to subtrees, using the tree depth as tie breaker when
  14394. * the subtrees have equal frequency. This minimizes the worst case length.
  14395. */
  14396. function smaller(tree, n, m, depth) {
  14397. var _n2 = n*2;
  14398. var _m2 = m*2;
  14399. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  14400. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  14401. }
  14402. /* ===========================================================================
  14403. * Restore the heap property by moving down the tree starting at node k,
  14404. * exchanging a node with the smallest of its two sons if necessary, stopping
  14405. * when the heap property is re-established (each father smaller than its
  14406. * two sons).
  14407. */
  14408. function pqdownheap(s, tree, k)
  14409. // deflate_state *s;
  14410. // ct_data *tree; /* the tree to restore */
  14411. // int k; /* node to move down */
  14412. {
  14413. var v = s.heap[k];
  14414. var j = k << 1; /* left son of k */
  14415. while (j <= s.heap_len) {
  14416. /* Set j to the smallest of the two sons: */
  14417. if (j < s.heap_len &&
  14418. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  14419. j++;
  14420. }
  14421. /* Exit if v is smaller than both sons */
  14422. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  14423. /* Exchange v with the smallest son */
  14424. s.heap[k] = s.heap[j];
  14425. k = j;
  14426. /* And continue down the tree, setting j to the left son of k */
  14427. j <<= 1;
  14428. }
  14429. s.heap[k] = v;
  14430. }
  14431. // inlined manually
  14432. // var SMALLEST = 1;
  14433. /* ===========================================================================
  14434. * Send the block data compressed using the given Huffman trees
  14435. */
  14436. function compress_block(s, ltree, dtree)
  14437. // deflate_state *s;
  14438. // const ct_data *ltree; /* literal tree */
  14439. // const ct_data *dtree; /* distance tree */
  14440. {
  14441. var dist; /* distance of matched string */
  14442. var lc; /* match length or unmatched char (if dist == 0) */
  14443. var lx = 0; /* running index in l_buf */
  14444. var code; /* the code to send */
  14445. var extra; /* number of extra bits to send */
  14446. if (s.last_lit !== 0) {
  14447. do {
  14448. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  14449. lc = s.pending_buf[s.l_buf + lx];
  14450. lx++;
  14451. if (dist === 0) {
  14452. send_code(s, lc, ltree); /* send a literal byte */
  14453. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  14454. } else {
  14455. /* Here, lc is the match length - MIN_MATCH */
  14456. code = _length_code[lc];
  14457. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  14458. extra = extra_lbits[code];
  14459. if (extra !== 0) {
  14460. lc -= base_length[code];
  14461. send_bits(s, lc, extra); /* send the extra length bits */
  14462. }
  14463. dist--; /* dist is now the match distance - 1 */
  14464. code = d_code(dist);
  14465. //Assert (code < D_CODES, "bad d_code");
  14466. send_code(s, code, dtree); /* send the distance code */
  14467. extra = extra_dbits[code];
  14468. if (extra !== 0) {
  14469. dist -= base_dist[code];
  14470. send_bits(s, dist, extra); /* send the extra distance bits */
  14471. }
  14472. } /* literal or match pair ? */
  14473. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  14474. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  14475. // "pendingBuf overflow");
  14476. } while (lx < s.last_lit);
  14477. }
  14478. send_code(s, END_BLOCK, ltree);
  14479. }
  14480. /* ===========================================================================
  14481. * Construct one Huffman tree and assigns the code bit strings and lengths.
  14482. * Update the total bit length for the current block.
  14483. * IN assertion: the field freq is set for all tree elements.
  14484. * OUT assertions: the fields len and code are set to the optimal bit length
  14485. * and corresponding code. The length opt_len is updated; static_len is
  14486. * also updated if stree is not null. The field max_code is set.
  14487. */
  14488. function build_tree(s, desc)
  14489. // deflate_state *s;
  14490. // tree_desc *desc; /* the tree descriptor */
  14491. {
  14492. var tree = desc.dyn_tree;
  14493. var stree = desc.stat_desc.static_tree;
  14494. var has_stree = desc.stat_desc.has_stree;
  14495. var elems = desc.stat_desc.elems;
  14496. var n, m; /* iterate over heap elements */
  14497. var max_code = -1; /* largest code with non zero frequency */
  14498. var node; /* new node being created */
  14499. /* Construct the initial heap, with least frequent element in
  14500. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  14501. * heap[0] is not used.
  14502. */
  14503. s.heap_len = 0;
  14504. s.heap_max = HEAP_SIZE;
  14505. for (n = 0; n < elems; n++) {
  14506. if (tree[n * 2]/*.Freq*/ !== 0) {
  14507. s.heap[++s.heap_len] = max_code = n;
  14508. s.depth[n] = 0;
  14509. } else {
  14510. tree[n*2 + 1]/*.Len*/ = 0;
  14511. }
  14512. }
  14513. /* The pkzip format requires that at least one distance code exists,
  14514. * and that at least one bit should be sent even if there is only one
  14515. * possible code. So to avoid special checks later on we force at least
  14516. * two codes of non zero frequency.
  14517. */
  14518. while (s.heap_len < 2) {
  14519. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  14520. tree[node * 2]/*.Freq*/ = 1;
  14521. s.depth[node] = 0;
  14522. s.opt_len--;
  14523. if (has_stree) {
  14524. s.static_len -= stree[node*2 + 1]/*.Len*/;
  14525. }
  14526. /* node is 0 or 1 so it does not have extra bits */
  14527. }
  14528. desc.max_code = max_code;
  14529. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  14530. * establish sub-heaps of increasing lengths:
  14531. */
  14532. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  14533. /* Construct the Huffman tree by repeatedly combining the least two
  14534. * frequent nodes.
  14535. */
  14536. node = elems; /* next internal node of the tree */
  14537. do {
  14538. //pqremove(s, tree, n); /* n = node of least frequency */
  14539. /*** pqremove ***/
  14540. n = s.heap[1/*SMALLEST*/];
  14541. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  14542. pqdownheap(s, tree, 1/*SMALLEST*/);
  14543. /***/
  14544. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  14545. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  14546. s.heap[--s.heap_max] = m;
  14547. /* Create a new node father of n and m */
  14548. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  14549. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  14550. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  14551. /* and insert the new node in the heap */
  14552. s.heap[1/*SMALLEST*/] = node++;
  14553. pqdownheap(s, tree, 1/*SMALLEST*/);
  14554. } while (s.heap_len >= 2);
  14555. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  14556. /* At this point, the fields freq and dad are set. We can now
  14557. * generate the bit lengths.
  14558. */
  14559. gen_bitlen(s, desc);
  14560. /* The field len is now set, we can generate the bit codes */
  14561. gen_codes(tree, max_code, s.bl_count);
  14562. }
  14563. /* ===========================================================================
  14564. * Scan a literal or distance tree to determine the frequencies of the codes
  14565. * in the bit length tree.
  14566. */
  14567. function scan_tree(s, tree, max_code)
  14568. // deflate_state *s;
  14569. // ct_data *tree; /* the tree to be scanned */
  14570. // int max_code; /* and its largest code of non zero frequency */
  14571. {
  14572. var n; /* iterates over all tree elements */
  14573. var prevlen = -1; /* last emitted length */
  14574. var curlen; /* length of current code */
  14575. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  14576. var count = 0; /* repeat count of the current code */
  14577. var max_count = 7; /* max repeat count */
  14578. var min_count = 4; /* min repeat count */
  14579. if (nextlen === 0) {
  14580. max_count = 138;
  14581. min_count = 3;
  14582. }
  14583. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  14584. for (n = 0; n <= max_code; n++) {
  14585. curlen = nextlen;
  14586. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  14587. if (++count < max_count && curlen === nextlen) {
  14588. continue;
  14589. } else if (count < min_count) {
  14590. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  14591. } else if (curlen !== 0) {
  14592. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  14593. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  14594. } else if (count <= 10) {
  14595. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  14596. } else {
  14597. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  14598. }
  14599. count = 0;
  14600. prevlen = curlen;
  14601. if (nextlen === 0) {
  14602. max_count = 138;
  14603. min_count = 3;
  14604. } else if (curlen === nextlen) {
  14605. max_count = 6;
  14606. min_count = 3;
  14607. } else {
  14608. max_count = 7;
  14609. min_count = 4;
  14610. }
  14611. }
  14612. }
  14613. /* ===========================================================================
  14614. * Send a literal or distance tree in compressed form, using the codes in
  14615. * bl_tree.
  14616. */
  14617. function send_tree(s, tree, max_code)
  14618. // deflate_state *s;
  14619. // ct_data *tree; /* the tree to be scanned */
  14620. // int max_code; /* and its largest code of non zero frequency */
  14621. {
  14622. var n; /* iterates over all tree elements */
  14623. var prevlen = -1; /* last emitted length */
  14624. var curlen; /* length of current code */
  14625. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  14626. var count = 0; /* repeat count of the current code */
  14627. var max_count = 7; /* max repeat count */
  14628. var min_count = 4; /* min repeat count */
  14629. /* tree[max_code+1].Len = -1; */ /* guard already set */
  14630. if (nextlen === 0) {
  14631. max_count = 138;
  14632. min_count = 3;
  14633. }
  14634. for (n = 0; n <= max_code; n++) {
  14635. curlen = nextlen;
  14636. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  14637. if (++count < max_count && curlen === nextlen) {
  14638. continue;
  14639. } else if (count < min_count) {
  14640. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  14641. } else if (curlen !== 0) {
  14642. if (curlen !== prevlen) {
  14643. send_code(s, curlen, s.bl_tree);
  14644. count--;
  14645. }
  14646. //Assert(count >= 3 && count <= 6, " 3_6?");
  14647. send_code(s, REP_3_6, s.bl_tree);
  14648. send_bits(s, count-3, 2);
  14649. } else if (count <= 10) {
  14650. send_code(s, REPZ_3_10, s.bl_tree);
  14651. send_bits(s, count-3, 3);
  14652. } else {
  14653. send_code(s, REPZ_11_138, s.bl_tree);
  14654. send_bits(s, count-11, 7);
  14655. }
  14656. count = 0;
  14657. prevlen = curlen;
  14658. if (nextlen === 0) {
  14659. max_count = 138;
  14660. min_count = 3;
  14661. } else if (curlen === nextlen) {
  14662. max_count = 6;
  14663. min_count = 3;
  14664. } else {
  14665. max_count = 7;
  14666. min_count = 4;
  14667. }
  14668. }
  14669. }
  14670. /* ===========================================================================
  14671. * Construct the Huffman tree for the bit lengths and return the index in
  14672. * bl_order of the last bit length code to send.
  14673. */
  14674. function build_bl_tree(s) {
  14675. var max_blindex; /* index of last bit length code of non zero freq */
  14676. /* Determine the bit length frequencies for literal and distance trees */
  14677. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  14678. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  14679. /* Build the bit length tree: */
  14680. build_tree(s, s.bl_desc);
  14681. /* opt_len now includes the length of the tree representations, except
  14682. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  14683. */
  14684. /* Determine the number of bit length codes to send. The pkzip format
  14685. * requires that at least 4 bit length codes be sent. (appnote.txt says
  14686. * 3 but the actual value used is 4.)
  14687. */
  14688. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  14689. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  14690. break;
  14691. }
  14692. }
  14693. /* Update opt_len to include the bit length tree and counts */
  14694. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  14695. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  14696. // s->opt_len, s->static_len));
  14697. return max_blindex;
  14698. }
  14699. /* ===========================================================================
  14700. * Send the header for a block using dynamic Huffman trees: the counts, the
  14701. * lengths of the bit length codes, the literal tree and the distance tree.
  14702. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  14703. */
  14704. function send_all_trees(s, lcodes, dcodes, blcodes)
  14705. // deflate_state *s;
  14706. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  14707. {
  14708. var rank; /* index in bl_order */
  14709. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  14710. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  14711. // "too many codes");
  14712. //Tracev((stderr, "\nbl counts: "));
  14713. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  14714. send_bits(s, dcodes-1, 5);
  14715. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  14716. for (rank = 0; rank < blcodes; rank++) {
  14717. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  14718. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  14719. }
  14720. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  14721. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  14722. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  14723. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  14724. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  14725. }
  14726. /* ===========================================================================
  14727. * Check if the data type is TEXT or BINARY, using the following algorithm:
  14728. * - TEXT if the two conditions below are satisfied:
  14729. * a) There are no non-portable control characters belonging to the
  14730. * "black list" (0..6, 14..25, 28..31).
  14731. * b) There is at least one printable character belonging to the
  14732. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  14733. * - BINARY otherwise.
  14734. * - The following partially-portable control characters form a
  14735. * "gray list" that is ignored in this detection algorithm:
  14736. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  14737. * IN assertion: the fields Freq of dyn_ltree are set.
  14738. */
  14739. function detect_data_type(s) {
  14740. /* black_mask is the bit mask of black-listed bytes
  14741. * set bits 0..6, 14..25, and 28..31
  14742. * 0xf3ffc07f = binary 11110011111111111100000001111111
  14743. */
  14744. var black_mask = 0xf3ffc07f;
  14745. var n;
  14746. /* Check for non-textual ("black-listed") bytes. */
  14747. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  14748. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  14749. return Z_BINARY;
  14750. }
  14751. }
  14752. /* Check for textual ("white-listed") bytes. */
  14753. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  14754. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  14755. return Z_TEXT;
  14756. }
  14757. for (n = 32; n < LITERALS; n++) {
  14758. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  14759. return Z_TEXT;
  14760. }
  14761. }
  14762. /* There are no "black-listed" or "white-listed" bytes:
  14763. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  14764. */
  14765. return Z_BINARY;
  14766. }
  14767. var static_init_done = false;
  14768. /* ===========================================================================
  14769. * Initialize the tree data structures for a new zlib stream.
  14770. */
  14771. function _tr_init(s)
  14772. {
  14773. if (!static_init_done) {
  14774. tr_static_init();
  14775. static_init_done = true;
  14776. }
  14777. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  14778. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  14779. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  14780. s.bi_buf = 0;
  14781. s.bi_valid = 0;
  14782. /* Initialize the first block of the first file: */
  14783. init_block(s);
  14784. }
  14785. /* ===========================================================================
  14786. * Send a stored block
  14787. */
  14788. function _tr_stored_block(s, buf, stored_len, last)
  14789. //DeflateState *s;
  14790. //charf *buf; /* input block */
  14791. //ulg stored_len; /* length of input block */
  14792. //int last; /* one if this is the last block for a file */
  14793. {
  14794. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  14795. copy_block(s, buf, stored_len, true); /* with header */
  14796. }
  14797. /* ===========================================================================
  14798. * Send one empty static block to give enough lookahead for inflate.
  14799. * This takes 10 bits, of which 7 may remain in the bit buffer.
  14800. */
  14801. function _tr_align(s) {
  14802. send_bits(s, STATIC_TREES<<1, 3);
  14803. send_code(s, END_BLOCK, static_ltree);
  14804. bi_flush(s);
  14805. }
  14806. /* ===========================================================================
  14807. * Determine the best encoding for the current block: dynamic trees, static
  14808. * trees or store, and output the encoded block to the zip file.
  14809. */
  14810. function _tr_flush_block(s, buf, stored_len, last)
  14811. //DeflateState *s;
  14812. //charf *buf; /* input block, or NULL if too old */
  14813. //ulg stored_len; /* length of input block */
  14814. //int last; /* one if this is the last block for a file */
  14815. {
  14816. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  14817. var max_blindex = 0; /* index of last bit length code of non zero freq */
  14818. /* Build the Huffman trees unless a stored block is forced */
  14819. if (s.level > 0) {
  14820. /* Check if the file is binary or text */
  14821. if (s.strm.data_type === Z_UNKNOWN) {
  14822. s.strm.data_type = detect_data_type(s);
  14823. }
  14824. /* Construct the literal and distance trees */
  14825. build_tree(s, s.l_desc);
  14826. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  14827. // s->static_len));
  14828. build_tree(s, s.d_desc);
  14829. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  14830. // s->static_len));
  14831. /* At this point, opt_len and static_len are the total bit lengths of
  14832. * the compressed block data, excluding the tree representations.
  14833. */
  14834. /* Build the bit length tree for the above two trees, and get the index
  14835. * in bl_order of the last bit length code to send.
  14836. */
  14837. max_blindex = build_bl_tree(s);
  14838. /* Determine the best encoding. Compute the block lengths in bytes. */
  14839. opt_lenb = (s.opt_len+3+7) >>> 3;
  14840. static_lenb = (s.static_len+3+7) >>> 3;
  14841. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  14842. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  14843. // s->last_lit));
  14844. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  14845. } else {
  14846. // Assert(buf != (char*)0, "lost buf");
  14847. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  14848. }
  14849. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  14850. /* 4: two words for the lengths */
  14851. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  14852. * Otherwise we can't have processed more than WSIZE input bytes since
  14853. * the last block flush, because compression would have been
  14854. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  14855. * transform a block into a stored block.
  14856. */
  14857. _tr_stored_block(s, buf, stored_len, last);
  14858. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  14859. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  14860. compress_block(s, static_ltree, static_dtree);
  14861. } else {
  14862. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  14863. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  14864. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  14865. }
  14866. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  14867. /* The above check is made mod 2^32, for files larger than 512 MB
  14868. * and uLong implemented on 32 bits.
  14869. */
  14870. init_block(s);
  14871. if (last) {
  14872. bi_windup(s);
  14873. }
  14874. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  14875. // s->compressed_len-7*last));
  14876. }
  14877. /* ===========================================================================
  14878. * Save the match info and tally the frequency counts. Return true if
  14879. * the current block must be flushed.
  14880. */
  14881. function _tr_tally(s, dist, lc)
  14882. // deflate_state *s;
  14883. // unsigned dist; /* distance of matched string */
  14884. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  14885. {
  14886. //var out_length, in_length, dcode;
  14887. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  14888. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  14889. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  14890. s.last_lit++;
  14891. if (dist === 0) {
  14892. /* lc is the unmatched char */
  14893. s.dyn_ltree[lc*2]/*.Freq*/++;
  14894. } else {
  14895. s.matches++;
  14896. /* Here, lc is the match length - MIN_MATCH */
  14897. dist--; /* dist = match distance - 1 */
  14898. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  14899. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  14900. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  14901. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  14902. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  14903. }
  14904. // (!) This block is disabled in zlib defailts,
  14905. // don't enable it for binary compatibility
  14906. //#ifdef TRUNCATE_BLOCK
  14907. // /* Try to guess if it is profitable to stop the current block here */
  14908. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  14909. // /* Compute an upper bound for the compressed length */
  14910. // out_length = s.last_lit*8;
  14911. // in_length = s.strstart - s.block_start;
  14912. //
  14913. // for (dcode = 0; dcode < D_CODES; dcode++) {
  14914. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  14915. // }
  14916. // out_length >>>= 3;
  14917. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  14918. // // s->last_lit, in_length, out_length,
  14919. // // 100L - out_length*100L/in_length));
  14920. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  14921. // return true;
  14922. // }
  14923. // }
  14924. //#endif
  14925. return (s.last_lit === s.lit_bufsize-1);
  14926. /* We avoid equality with lit_bufsize because of wraparound at 64K
  14927. * on 16 bit machines and because stored blocks are restricted to
  14928. * 64K-1 bytes.
  14929. */
  14930. }
  14931. exports._tr_init = _tr_init;
  14932. exports._tr_stored_block = _tr_stored_block;
  14933. exports._tr_flush_block = _tr_flush_block;
  14934. exports._tr_tally = _tr_tally;
  14935. exports._tr_align = _tr_align;
  14936. },{"../utils/common":35}],47:[function(require,module,exports){
  14937. 'use strict';
  14938. function ZStream() {
  14939. /* next input byte */
  14940. this.input = null; // JS specific, because we have no pointers
  14941. this.next_in = 0;
  14942. /* number of bytes available at input */
  14943. this.avail_in = 0;
  14944. /* total number of input bytes read so far */
  14945. this.total_in = 0;
  14946. /* next output byte should be put there */
  14947. this.output = null; // JS specific, because we have no pointers
  14948. this.next_out = 0;
  14949. /* remaining free space at output */
  14950. this.avail_out = 0;
  14951. /* total number of bytes output so far */
  14952. this.total_out = 0;
  14953. /* last error message, NULL if no error */
  14954. this.msg = ''/*Z_NULL*/;
  14955. /* not visible by applications */
  14956. this.state = null;
  14957. /* best guess about the data type: binary or text */
  14958. this.data_type = 2/*Z_UNKNOWN*/;
  14959. /* adler32 value of the uncompressed data */
  14960. this.adler = 0;
  14961. }
  14962. module.exports = ZStream;
  14963. },{}],48:[function(require,module,exports){
  14964. module.exports = function arrayEquals(array) {
  14965. // if the other array is a falsy value, return
  14966. if (!array)
  14967. return false;
  14968. // compare lengths - can save a lot of time
  14969. if (this.length != array.length)
  14970. return false;
  14971. for (var i = 0, l = this.length; i < l; i++) {
  14972. // Check if we have nested arrays
  14973. if (this[i] instanceof Array && array[i] instanceof Array) {
  14974. // recurse into the nested arrays
  14975. if (!arrayEquals.apply(this[i], [array[i]]))
  14976. return false;
  14977. } else if (this[i] != array[i]) {
  14978. // Warning - two different object instances will never be equal:
  14979. // {x:20} != {x:20}
  14980. return false;
  14981. }
  14982. }
  14983. return true;
  14984. }
  14985. },{}],49:[function(require,module,exports){
  14986. exports.Interop = require('./interop');
  14987. },{"./interop":50}],50:[function(require,module,exports){
  14988. "use strict";
  14989. var transform = require('./transform');
  14990. var arrayEquals = require('./array-equals');
  14991. function Interop() {
  14992. /**
  14993. * This map holds the most recent Unified Plan offer/answer SDP that was
  14994. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  14995. * the SDP string as values.
  14996. *
  14997. * @type {{}}
  14998. */
  14999. this.cache = {};
  15000. }
  15001. module.exports = Interop;
  15002. /**
  15003. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  15004. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  15005. * application.
  15006. *
  15007. * @param desc
  15008. * @returns {*}
  15009. */
  15010. Interop.prototype.toPlanB = function(desc) {
  15011. //#region Preliminary input validation.
  15012. if (typeof desc !== 'object' || desc === null ||
  15013. typeof desc.sdp !== 'string') {
  15014. console.warn('An empty description was passed as an argument.');
  15015. return desc;
  15016. }
  15017. // Objectify the SDP for easier manipulation.
  15018. var session = transform.parse(desc.sdp);
  15019. // If the SDP contains no media, there's nothing to transform.
  15020. if (typeof session.media === 'undefined' ||
  15021. !Array.isArray(session.media) || session.media.length === 0) {
  15022. console.warn('The description has no media.');
  15023. return desc;
  15024. }
  15025. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  15026. // SDP has a video, an audio and a data "channel" at most.
  15027. if (session.media.length <= 3 && session.media.every(function(m) {
  15028. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  15029. })) {
  15030. console.warn('This description does not look like Unified Plan.');
  15031. return desc;
  15032. }
  15033. //#endregion
  15034. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  15035. // -> Unified Plan transformation.
  15036. this.cache[desc.type] = desc.sdp;
  15037. //#region Convert from Unified Plan to Plan B.
  15038. // We rebuild the session.media array.
  15039. var media = session.media;
  15040. session.media = [];
  15041. // Associative array that maps channel types to channel objects for fast
  15042. // access to channel objects by their type, e.g. type2bl['audio']->channel
  15043. // obj.
  15044. var type2bl = {};
  15045. // Used to build the group:BUNDLE value after the channels construction
  15046. // loop.
  15047. var types = [];
  15048. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  15049. media.forEach(function(unifiedLine) {
  15050. // rtcp-mux is required in the Plan B SDP.
  15051. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  15052. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  15053. unifiedLine.direction !== 'inactive') {
  15054. throw new Error('Cannot convert to Plan B because m-lines ' +
  15055. 'without the rtcp-mux attribute were found.');
  15056. }
  15057. if (unifiedLine.type === 'application') {
  15058. session.media.push(unifiedLine);
  15059. types.push(unifiedLine.mid);
  15060. return;
  15061. }
  15062. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  15063. // as the channel basis.
  15064. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  15065. type2bl[unifiedLine.type] = unifiedLine;
  15066. }
  15067. // Add sources to the channel and handle a=msid.
  15068. if (typeof unifiedLine.sources === 'object') {
  15069. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  15070. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  15071. type2bl[unifiedLine.type].sources = {};
  15072. // Assign the sources to the channel.
  15073. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  15074. if (typeof unifiedLine.msid !== 'undefined') {
  15075. // In Plan B the msid is an SSRC attribute. Also, we don't
  15076. // care about the obsolete label and mslabel attributes.
  15077. //
  15078. // Note that it is not guaranteed that the unifiedLine will have
  15079. // an msid. recvonly channels in particular don't have one.
  15080. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  15081. }
  15082. // NOTE ssrcs in ssrc groups will share msids, as
  15083. // draft-uberti-rtcweb-plan-00 mandates.
  15084. });
  15085. }
  15086. // Add ssrc groups to the channel.
  15087. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  15088. Array.isArray(unifiedLine.ssrcGroups)) {
  15089. // Create the ssrcGroups array, if it's not defined.
  15090. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  15091. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  15092. type2bl[unifiedLine.type].ssrcGroups = [];
  15093. }
  15094. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  15095. }
  15096. if (type2bl[unifiedLine.type] === unifiedLine) {
  15097. // Copy ICE related stuff from the principal media line.
  15098. unifiedLine.candidates = media[0].candidates;
  15099. unifiedLine.iceUfrag = media[0].iceUfrag;
  15100. unifiedLine.icePwd = media[0].icePwd;
  15101. unifiedLine.fingerprint = media[0].fingerprint;
  15102. // Plan B mids are in ['audio', 'video', 'data']
  15103. unifiedLine.mid = unifiedLine.type;
  15104. // Plan B doesn't support/need the bundle-only attribute.
  15105. delete unifiedLine.bundleOnly;
  15106. // In Plan B the msid is an SSRC attribute.
  15107. delete unifiedLine.msid;
  15108. // Used to build the group:BUNDLE value after this loop.
  15109. types.push(unifiedLine.type);
  15110. // Add the channel to the new media array.
  15111. session.media.push(unifiedLine);
  15112. }
  15113. });
  15114. // We regenerate the BUNDLE group with the new mids.
  15115. session.groups.some(function(group) {
  15116. if (group.type === 'BUNDLE') {
  15117. group.mids = types.join(' ');
  15118. return true;
  15119. }
  15120. });
  15121. // msid semantic
  15122. session.msidSemantic = {
  15123. semantic: 'WMS',
  15124. token: '*'
  15125. };
  15126. var resStr = transform.write(session);
  15127. return new RTCSessionDescription({
  15128. type: desc.type,
  15129. sdp: resStr
  15130. });
  15131. //#endregion
  15132. };
  15133. /**
  15134. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  15135. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  15136. * to FF.
  15137. *
  15138. * @param desc
  15139. * @returns {*}
  15140. */
  15141. Interop.prototype.toUnifiedPlan = function(desc) {
  15142. //#region Preliminary input validation.
  15143. if (typeof desc !== 'object' || desc === null ||
  15144. typeof desc.sdp !== 'string') {
  15145. console.warn('An empty description was passed as an argument.');
  15146. return desc;
  15147. }
  15148. var session = transform.parse(desc.sdp);
  15149. // If the SDP contains no media, there's nothing to transform.
  15150. if (typeof session.media === 'undefined' ||
  15151. !Array.isArray(session.media) || session.media.length === 0) {
  15152. console.warn('The description has no media.');
  15153. return desc;
  15154. }
  15155. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  15156. // a video, an audio and a data "channel" at most.
  15157. if (session.media.length > 3 || !session.media.every(function(m) {
  15158. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  15159. })) {
  15160. console.warn('This description does not look like Plan B.');
  15161. return desc;
  15162. }
  15163. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  15164. var mids = [];
  15165. session.media.forEach(function(m) {
  15166. mids.push(m.mid);
  15167. });
  15168. var hasBundle = false;
  15169. if (typeof session.groups !== 'undefined' &&
  15170. Array.isArray(session.groups)) {
  15171. hasBundle = session.groups.every(function(g) {
  15172. return g.type !== 'BUNDLE' ||
  15173. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  15174. });
  15175. }
  15176. if (!hasBundle) {
  15177. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  15178. " are not bundled were found.");
  15179. }
  15180. //#endregion
  15181. //#region Convert from Plan B to Unified Plan.
  15182. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  15183. // rebuild an equivalent Unified Plan offer/answer.
  15184. //
  15185. // For example, if this is a local answer (in Unified Plan style) that we
  15186. // convert to Plan B prior to handing it over to the application (the
  15187. // PeerConnection wrapper called us, for instance, after a successful
  15188. // createAnswer), we want to remember the m-line at which we've seen the
  15189. // (local) SSRC. That's because when the application wants to do call the
  15190. // SLD method, forcing us to do the inverse transformation (from Plan B to
  15191. // Unified Plan), we need to know to which m-line to assign the (local)
  15192. // SSRC. We also need to know all the other m-lines that the original
  15193. // answer had and include them in the transformed answer as well.
  15194. //
  15195. // Another example is if this is a remote offer that we convert to Plan B
  15196. // prior to giving it to the application, we want to remember the mid at
  15197. // which we've seen the (remote) SSRC.
  15198. //
  15199. // In the iteration that follows, we use the cached Unified Plan (if it
  15200. // exists) to assign mids to ssrcs.
  15201. var cached;
  15202. if (typeof this.cache[desc.type] !== 'undefined') {
  15203. cached = transform.parse(this.cache[desc.type]);
  15204. }
  15205. // A helper map that sends mids to m-line objects. We use it later to
  15206. // rebuild the Unified Plan style session.media array.
  15207. var mid2ul = {};
  15208. session.media.forEach(function(bLine) {
  15209. if ((typeof bLine.rtcpMux !== 'string' ||
  15210. bLine.rtcpMux !== 'rtcp-mux') &&
  15211. bLine.direction !== 'inactive') {
  15212. throw new Error("Cannot convert to Unified Plan because m-lines " +
  15213. "without the rtcp-mux attribute were found.");
  15214. }
  15215. if (bLine.type === 'application') {
  15216. mid2ul[bLine.mid] = bLine;
  15217. return;
  15218. }
  15219. // With rtcp-mux and bundle all the channels should have the same ICE
  15220. // stuff.
  15221. var sources = bLine.sources;
  15222. var ssrcGroups = bLine.ssrcGroups;
  15223. var candidates = bLine.candidates;
  15224. var iceUfrag = bLine.iceUfrag;
  15225. var icePwd = bLine.icePwd;
  15226. var fingerprint = bLine.fingerprint;
  15227. var port = bLine.port;
  15228. // We'll use the "bLine" object as a prototype for each new "mLine"
  15229. // that we create, but first we need to clean it up a bit.
  15230. delete bLine.sources;
  15231. delete bLine.ssrcGroups;
  15232. delete bLine.candidates;
  15233. delete bLine.iceUfrag;
  15234. delete bLine.icePwd;
  15235. delete bLine.fingerprint;
  15236. delete bLine.port;
  15237. delete bLine.mid;
  15238. // inverted ssrc group map
  15239. var ssrc2group = {};
  15240. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  15241. ssrcGroups.forEach(function (ssrcGroup) {
  15242. // TODO(gp) find out how to receive simulcast with FF. For the
  15243. // time being, hide it.
  15244. if (ssrcGroup.semantics === 'SIM') {
  15245. return;
  15246. }
  15247. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  15248. Array.isArray(ssrcGroup.ssrcs)) {
  15249. ssrcGroup.ssrcs.forEach(function (ssrc) {
  15250. if (typeof ssrc2group[ssrc] === 'undefined') {
  15251. ssrc2group[ssrc] = [];
  15252. }
  15253. ssrc2group[ssrc].push(ssrcGroup);
  15254. });
  15255. }
  15256. });
  15257. }
  15258. // ssrc to m-line index.
  15259. var ssrc2ml = {};
  15260. if (typeof sources === 'object') {
  15261. // Explode the Plan B channel sources with one m-line per source.
  15262. Object.keys(sources).forEach(function(ssrc) {
  15263. // The (unified) m-line for this SSRC. We either create it from
  15264. // scratch or, if it's a grouped SSRC, we re-use a related
  15265. // mline. In other words, if the source is grouped with another
  15266. // source, put the two together in the same m-line.
  15267. var unifiedLine;
  15268. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  15269. Array.isArray(ssrc2group[ssrc])) {
  15270. ssrc2group[ssrc].some(function (ssrcGroup) {
  15271. // ssrcGroup.ssrcs *is* an Array, no need to check
  15272. // again here.
  15273. return ssrcGroup.ssrcs.some(function (related) {
  15274. if (typeof ssrc2ml[related] === 'object') {
  15275. unifiedLine = ssrc2ml[related];
  15276. return true;
  15277. }
  15278. });
  15279. });
  15280. }
  15281. if (typeof unifiedLine === 'object') {
  15282. // the m-line already exists. Just add the source.
  15283. unifiedLine.sources[ssrc] = sources[ssrc];
  15284. delete sources[ssrc].msid;
  15285. } else {
  15286. // Use the "bLine" as a prototype for the "unifiedLine".
  15287. unifiedLine = Object.create(bLine);
  15288. ssrc2ml[ssrc] = unifiedLine;
  15289. if (typeof sources[ssrc].msid !== 'undefined') {
  15290. // Assign the msid of the source to the m-line. Note
  15291. // that it is not guaranteed that the source will have
  15292. // msid. In particular "recvonly" sources don't have an
  15293. // msid. Note that "recvonly" is a term only defined
  15294. // for m-lines.
  15295. unifiedLine.msid = sources[ssrc].msid;
  15296. delete sources[ssrc].msid;
  15297. }
  15298. // We assign one SSRC per media line.
  15299. unifiedLine.sources = {};
  15300. unifiedLine.sources[ssrc] = sources[ssrc];
  15301. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  15302. // Use the cached Unified Plan SDP (if it exists) to assign
  15303. // SSRCs to mids.
  15304. if (typeof cached !== 'undefined' &&
  15305. typeof cached.media !== 'undefined' &&
  15306. Array.isArray(cached.media)) {
  15307. cached.media.forEach(function (m) {
  15308. if (typeof m.sources === 'object') {
  15309. Object.keys(m.sources).forEach(function (s) {
  15310. if (s === ssrc) {
  15311. unifiedLine.mid = m.mid;
  15312. }
  15313. });
  15314. }
  15315. });
  15316. }
  15317. if (typeof unifiedLine.mid === 'undefined') {
  15318. // If this is an SSRC that we see for the first time
  15319. // assign it a new mid. This is typically the case when
  15320. // this method is called to transform a remote
  15321. // description for the first time or when there is a
  15322. // new SSRC in the remote description because a new
  15323. // peer has joined the conference. Local SSRCs should
  15324. // have already been added to the map in the toPlanB
  15325. // method.
  15326. //
  15327. // Because FF generates answers in Unified Plan style,
  15328. // we MUST already have a cached answer with all the
  15329. // local SSRCs mapped to some m-line/mid.
  15330. if (desc.type === 'answer') {
  15331. throw new Error("An unmapped SSRC was found.");
  15332. }
  15333. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  15334. }
  15335. // Include the candidates in the 1st media line.
  15336. unifiedLine.candidates = candidates;
  15337. unifiedLine.iceUfrag = iceUfrag;
  15338. unifiedLine.icePwd = icePwd;
  15339. unifiedLine.fingerprint = fingerprint;
  15340. unifiedLine.port = port;
  15341. mid2ul[unifiedLine.mid] = unifiedLine;
  15342. }
  15343. });
  15344. }
  15345. });
  15346. // Rebuild the media array in the right order and add the missing mLines
  15347. // (missing from the Plan B SDP).
  15348. session.media = [];
  15349. mids = []; // reuse
  15350. if (desc.type === 'answer') {
  15351. // The media lines in the answer must match the media lines in the
  15352. // offer. The order is important too. Here we assume that Firefox is the
  15353. // answerer, so we merely have to use the reconstructed (unified) answer
  15354. // to update the cached (unified) answer accordingly.
  15355. //
  15356. // In the general case, one would have to use the cached (unified) offer
  15357. // to find the m-lines that are missing from the reconstructed answer,
  15358. // potentially grabbing them from the cached (unified) answer. One has
  15359. // to be carefull with this approach because inactive m-lines do not
  15360. // always have an mid, making it tricky (impossible?) to find where
  15361. // exactly and which m-lines are missing from the reconstructed answer.
  15362. for (var i = 0; i < cached.media.length; i++) {
  15363. var unifiedLine = cached.media[i];
  15364. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  15365. // The mid isn't in the reconstructed (unified) answer.
  15366. // This is either a (unified) m-line containing a remote
  15367. // track only, or a (unified) m-line containing a remote
  15368. // track and a local track that has been removed.
  15369. // In either case, it MUST exist in the cached
  15370. // (unified) answer.
  15371. //
  15372. // In case this is a removed local track, clean-up
  15373. // the (unified) m-line and make sure it's 'recvonly' or
  15374. // 'inactive'.
  15375. delete unifiedLine.msid;
  15376. delete unifiedLine.sources;
  15377. delete unifiedLine.ssrcGroups;
  15378. if (!unifiedLine.direction
  15379. || unifiedLine.direction === 'sendrecv')
  15380. unifiedLine.direction = 'recvonly';
  15381. if (!unifiedLine.direction
  15382. || unifiedLine.direction === 'sendonly')
  15383. unifiedLine.direction = 'inactive';
  15384. } else {
  15385. // This is an (unified) m-line/channel that contains a local
  15386. // track (sendrecv or sendonly channel) or it's a unified
  15387. // recvonly m-line/channel. In either case, since we're
  15388. // going from PlanB -> Unified Plan this m-line MUST
  15389. // exist in the cached answer.
  15390. }
  15391. session.media.push(unifiedLine);
  15392. if (typeof unifiedLine.mid === 'string') {
  15393. // inactive lines don't/may not have an mid.
  15394. mids.push(unifiedLine.mid);
  15395. }
  15396. }
  15397. } else {
  15398. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  15399. // under any circumstances. If we are no longer interested in sending a
  15400. // track, we just remove the msid and ssrc attributes and set it to
  15401. // either a=recvonly (as the reofferer, we must use recvonly if the
  15402. // other side was previously sending on the m-section, but we can also
  15403. // leave the possibility open if it wasn't previously in use), or
  15404. // a=inacive.
  15405. if (typeof cached !== 'undefined' &&
  15406. typeof cached.media !== 'undefined' &&
  15407. Array.isArray(cached.media)) {
  15408. cached.media.forEach(function(unifiedLine) {
  15409. mids.push(unifiedLine.mid);
  15410. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  15411. session.media.push(mid2ul[unifiedLine.mid]);
  15412. } else {
  15413. delete unifiedLine.msid;
  15414. delete unifiedLine.sources;
  15415. delete unifiedLine.ssrcGroups;
  15416. if (!unifiedLine.direction
  15417. || unifiedLine.direction === 'sendrecv')
  15418. unifiedLine.direction = 'recvonly';
  15419. if (!unifiedLine.direction
  15420. || unifiedLine.direction === 'sendonly')
  15421. unifiedLine.direction = 'inactive';
  15422. session.media.push(unifiedLine);
  15423. }
  15424. });
  15425. }
  15426. // Add all the remaining (new) m-lines of the transformed SDP.
  15427. Object.keys(mid2ul).forEach(function(mid) {
  15428. if (mids.indexOf(mid) === -1) {
  15429. mids.push(mid);
  15430. if (typeof mid2ul[mid].direction === 'recvonly') {
  15431. // This is a remote recvonly channel. Add its SSRC to the
  15432. // appropriate sendrecv or sendonly channel.
  15433. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  15434. session.media.some(function (unifiedLine) {
  15435. if ((unifiedLine.direction === 'sendrecv' ||
  15436. unifiedLine.direction === 'sendonly') &&
  15437. unifiedLine.type === mid2ul[mid].type) {
  15438. // mid2ul[mid] shouldn't have any ssrc-groups
  15439. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  15440. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  15441. });
  15442. return true;
  15443. }
  15444. });
  15445. } else {
  15446. session.media.push(mid2ul[mid]);
  15447. }
  15448. }
  15449. });
  15450. }
  15451. // We regenerate the BUNDLE group (since we regenerated the mids)
  15452. session.groups.some(function(group) {
  15453. if (group.type === 'BUNDLE') {
  15454. group.mids = mids.join(' ');
  15455. return true;
  15456. }
  15457. });
  15458. // msid semantic
  15459. session.msidSemantic = {
  15460. semantic: 'WMS',
  15461. token: '*'
  15462. };
  15463. var resStr = transform.write(session);
  15464. // Cache the transformed SDP (Unified Plan) for later re-use in this
  15465. // function.
  15466. this.cache[desc.type] = resStr;
  15467. return new RTCSessionDescription({
  15468. type: desc.type,
  15469. sdp: resStr
  15470. });
  15471. //#endregion
  15472. };
  15473. },{"./array-equals":48,"./transform":51}],51:[function(require,module,exports){
  15474. var transform = require('sdp-transform');
  15475. exports.write = function(session, opts) {
  15476. if (typeof session !== 'undefined' &&
  15477. typeof session.media !== 'undefined' &&
  15478. Array.isArray(session.media)) {
  15479. session.media.forEach(function (mLine) {
  15480. // expand sources to ssrcs
  15481. if (typeof mLine.sources !== 'undefined' &&
  15482. Object.keys(mLine.sources).length !== 0) {
  15483. mLine.ssrcs = [];
  15484. Object.keys(mLine.sources).forEach(function (ssrc) {
  15485. var source = mLine.sources[ssrc];
  15486. Object.keys(source).forEach(function (attribute) {
  15487. mLine.ssrcs.push({
  15488. id: ssrc,
  15489. attribute: attribute,
  15490. value: source[attribute]
  15491. });
  15492. });
  15493. });
  15494. delete mLine.sources;
  15495. }
  15496. // join ssrcs in ssrc groups
  15497. if (typeof mLine.ssrcGroups !== 'undefined' &&
  15498. Array.isArray(mLine.ssrcGroups)) {
  15499. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  15500. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  15501. Array.isArray(ssrcGroup.ssrcs)) {
  15502. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  15503. }
  15504. });
  15505. }
  15506. });
  15507. }
  15508. // join group mids
  15509. if (typeof session !== 'undefined' &&
  15510. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  15511. session.groups.forEach(function (g) {
  15512. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  15513. g.mids = g.mids.join(' ');
  15514. }
  15515. });
  15516. }
  15517. return transform.write(session, opts);
  15518. };
  15519. exports.parse = function(sdp) {
  15520. var session = transform.parse(sdp);
  15521. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  15522. Array.isArray(session.media)) {
  15523. session.media.forEach(function (mLine) {
  15524. // group sources attributes by ssrc
  15525. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  15526. mLine.sources = {};
  15527. mLine.ssrcs.forEach(function (ssrc) {
  15528. if (!mLine.sources[ssrc.id])
  15529. mLine.sources[ssrc.id] = {};
  15530. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  15531. });
  15532. delete mLine.ssrcs;
  15533. }
  15534. // split ssrcs in ssrc groups
  15535. if (typeof mLine.ssrcGroups !== 'undefined' &&
  15536. Array.isArray(mLine.ssrcGroups)) {
  15537. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  15538. if (typeof ssrcGroup.ssrcs === 'string') {
  15539. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  15540. }
  15541. });
  15542. }
  15543. });
  15544. }
  15545. // split group mids
  15546. if (typeof session !== 'undefined' &&
  15547. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  15548. session.groups.forEach(function (g) {
  15549. if (typeof g.mids === 'string') {
  15550. g.mids = g.mids.split(' ');
  15551. }
  15552. });
  15553. }
  15554. return session;
  15555. };
  15556. },{"sdp-transform":53}],52:[function(require,module,exports){
  15557. var grammar = module.exports = {
  15558. v: [{
  15559. name: 'version',
  15560. reg: /^(\d*)$/
  15561. }],
  15562. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  15563. // NB: sessionId will be a String in most cases because it is huge
  15564. name: 'origin',
  15565. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  15566. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  15567. format: "%s %s %d %s IP%d %s"
  15568. }],
  15569. // default parsing of these only (though some of these feel outdated)
  15570. s: [{ name: 'name' }],
  15571. i: [{ name: 'description' }],
  15572. u: [{ name: 'uri' }],
  15573. e: [{ name: 'email' }],
  15574. p: [{ name: 'phone' }],
  15575. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  15576. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  15577. //k: [{}], // outdated thing ignored
  15578. t: [{ //t=0 0
  15579. name: 'timing',
  15580. reg: /^(\d*) (\d*)/,
  15581. names: ['start', 'stop'],
  15582. format: "%d %d"
  15583. }],
  15584. c: [{ //c=IN IP4 10.47.197.26
  15585. name: 'connection',
  15586. reg: /^IN IP(\d) (\S*)/,
  15587. names: ['version', 'ip'],
  15588. format: "IN IP%d %s"
  15589. }],
  15590. b: [{ //b=AS:4000
  15591. push: 'bandwidth',
  15592. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  15593. names: ['type', 'limit'],
  15594. format: "%s:%s"
  15595. }],
  15596. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  15597. // NB: special - pushes to session
  15598. // TODO: rtp/fmtp should be filtered by the payloads found here?
  15599. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  15600. names: ['type', 'port', 'protocol', 'payloads'],
  15601. format: "%s %d %s %s"
  15602. }],
  15603. a: [
  15604. { //a=rtpmap:110 opus/48000/2
  15605. push: 'rtp',
  15606. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  15607. names: ['payload', 'codec', 'rate', 'encoding'],
  15608. format: function (o) {
  15609. return (o.encoding) ?
  15610. "rtpmap:%d %s/%s/%s":
  15611. "rtpmap:%d %s/%s";
  15612. }
  15613. },
  15614. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  15615. push: 'fmtp',
  15616. reg: /^fmtp:(\d*) (\S*)/,
  15617. names: ['payload', 'config'],
  15618. format: "fmtp:%d %s"
  15619. },
  15620. { //a=control:streamid=0
  15621. name: 'control',
  15622. reg: /^control:(.*)/,
  15623. format: "control:%s"
  15624. },
  15625. { //a=rtcp:65179 IN IP4 193.84.77.194
  15626. name: 'rtcp',
  15627. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  15628. names: ['port', 'netType', 'ipVer', 'address'],
  15629. format: function (o) {
  15630. return (o.address != null) ?
  15631. "rtcp:%d %s IP%d %s":
  15632. "rtcp:%d";
  15633. }
  15634. },
  15635. { //a=rtcp-fb:98 trr-int 100
  15636. push: 'rtcpFbTrrInt',
  15637. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  15638. names: ['payload', 'value'],
  15639. format: "rtcp-fb:%d trr-int %d"
  15640. },
  15641. { //a=rtcp-fb:98 nack rpsi
  15642. push: 'rtcpFb',
  15643. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  15644. names: ['payload', 'type', 'subtype'],
  15645. format: function (o) {
  15646. return (o.subtype != null) ?
  15647. "rtcp-fb:%s %s %s":
  15648. "rtcp-fb:%s %s";
  15649. }
  15650. },
  15651. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  15652. //a=extmap:1/recvonly URI-gps-string
  15653. push: 'ext',
  15654. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  15655. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  15656. format: function (o) {
  15657. return (o.config != null) ?
  15658. "extmap:%s %s %s":
  15659. "extmap:%s %s";
  15660. }
  15661. },
  15662. {
  15663. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  15664. push: 'crypto',
  15665. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  15666. names: ['id', 'suite', 'config', 'sessionConfig'],
  15667. format: function (o) {
  15668. return (o.sessionConfig != null) ?
  15669. "crypto:%d %s %s %s":
  15670. "crypto:%d %s %s";
  15671. }
  15672. },
  15673. { //a=setup:actpass
  15674. name: 'setup',
  15675. reg: /^setup:(\w*)/,
  15676. format: "setup:%s"
  15677. },
  15678. { //a=mid:1
  15679. name: 'mid',
  15680. reg: /^mid:([^\s]*)/,
  15681. format: "mid:%s"
  15682. },
  15683. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  15684. name: 'msid',
  15685. reg: /^msid:(.*)/,
  15686. format: "msid:%s"
  15687. },
  15688. { //a=ptime:20
  15689. name: 'ptime',
  15690. reg: /^ptime:(\d*)/,
  15691. format: "ptime:%d"
  15692. },
  15693. { //a=maxptime:60
  15694. name: 'maxptime',
  15695. reg: /^maxptime:(\d*)/,
  15696. format: "maxptime:%d"
  15697. },
  15698. { //a=sendrecv
  15699. name: 'direction',
  15700. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  15701. },
  15702. { //a=ice-lite
  15703. name: 'icelite',
  15704. reg: /^(ice-lite)/
  15705. },
  15706. { //a=ice-ufrag:F7gI
  15707. name: 'iceUfrag',
  15708. reg: /^ice-ufrag:(\S*)/,
  15709. format: "ice-ufrag:%s"
  15710. },
  15711. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  15712. name: 'icePwd',
  15713. reg: /^ice-pwd:(\S*)/,
  15714. format: "ice-pwd:%s"
  15715. },
  15716. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  15717. name: 'fingerprint',
  15718. reg: /^fingerprint:(\S*) (\S*)/,
  15719. names: ['type', 'hash'],
  15720. format: "fingerprint:%s %s"
  15721. },
  15722. {
  15723. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  15724. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  15725. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  15726. push:'candidates',
  15727. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  15728. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  15729. format: function (o) {
  15730. var str = "candidate:%s %d %s %d %s %d typ %s";
  15731. // NB: candidate has two optional chunks, so %void middle one if it's missing
  15732. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  15733. if (o.generation != null) {
  15734. str += " generation %d";
  15735. }
  15736. return str;
  15737. }
  15738. },
  15739. { //a=end-of-candidates (keep after the candidates line for readability)
  15740. name: 'endOfCandidates',
  15741. reg: /^(end-of-candidates)/
  15742. },
  15743. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  15744. name: 'remoteCandidates',
  15745. reg: /^remote-candidates:(.*)/,
  15746. format: "remote-candidates:%s"
  15747. },
  15748. { //a=ice-options:google-ice
  15749. name: 'iceOptions',
  15750. reg: /^ice-options:(\S*)/,
  15751. format: "ice-options:%s"
  15752. },
  15753. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  15754. push: "ssrcs",
  15755. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  15756. names: ['id', 'attribute', 'value'],
  15757. format: "ssrc:%d %s:%s"
  15758. },
  15759. { //a=ssrc-group:FEC 1 2
  15760. push: "ssrcGroups",
  15761. reg: /^ssrc-group:(\w*) (.*)/,
  15762. names: ['semantics', 'ssrcs'],
  15763. format: "ssrc-group:%s %s"
  15764. },
  15765. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  15766. name: "msidSemantic",
  15767. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  15768. names: ['semantic', 'token'],
  15769. format: "msid-semantic: %s %s" // space after ":" is not accidental
  15770. },
  15771. { //a=group:BUNDLE audio video
  15772. push: 'groups',
  15773. reg: /^group:(\w*) (.*)/,
  15774. names: ['type', 'mids'],
  15775. format: "group:%s %s"
  15776. },
  15777. { //a=rtcp-mux
  15778. name: 'rtcpMux',
  15779. reg: /^(rtcp-mux)/
  15780. },
  15781. { //a=rtcp-rsize
  15782. name: 'rtcpRsize',
  15783. reg: /^(rtcp-rsize)/
  15784. },
  15785. { // any a= that we don't understand is kepts verbatim on media.invalid
  15786. push: 'invalid',
  15787. names: ["value"]
  15788. }
  15789. ]
  15790. };
  15791. // set sensible defaults to avoid polluting the grammar with boring details
  15792. Object.keys(grammar).forEach(function (key) {
  15793. var objs = grammar[key];
  15794. objs.forEach(function (obj) {
  15795. if (!obj.reg) {
  15796. obj.reg = /(.*)/;
  15797. }
  15798. if (!obj.format) {
  15799. obj.format = "%s";
  15800. }
  15801. });
  15802. });
  15803. },{}],53:[function(require,module,exports){
  15804. var parser = require('./parser');
  15805. var writer = require('./writer');
  15806. exports.write = writer;
  15807. exports.parse = parser.parse;
  15808. exports.parseFmtpConfig = parser.parseFmtpConfig;
  15809. exports.parsePayloads = parser.parsePayloads;
  15810. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  15811. },{"./parser":54,"./writer":55}],54:[function(require,module,exports){
  15812. var toIntIfInt = function (v) {
  15813. return String(Number(v)) === v ? Number(v) : v;
  15814. };
  15815. var attachProperties = function (match, location, names, rawName) {
  15816. if (rawName && !names) {
  15817. location[rawName] = toIntIfInt(match[1]);
  15818. }
  15819. else {
  15820. for (var i = 0; i < names.length; i += 1) {
  15821. if (match[i+1] != null) {
  15822. location[names[i]] = toIntIfInt(match[i+1]);
  15823. }
  15824. }
  15825. }
  15826. };
  15827. var parseReg = function (obj, location, content) {
  15828. var needsBlank = obj.name && obj.names;
  15829. if (obj.push && !location[obj.push]) {
  15830. location[obj.push] = [];
  15831. }
  15832. else if (needsBlank && !location[obj.name]) {
  15833. location[obj.name] = {};
  15834. }
  15835. var keyLocation = obj.push ?
  15836. {} : // blank object that will be pushed
  15837. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  15838. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  15839. if (obj.push) {
  15840. location[obj.push].push(keyLocation);
  15841. }
  15842. };
  15843. var grammar = require('./grammar');
  15844. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  15845. exports.parse = function (sdp) {
  15846. var session = {}
  15847. , media = []
  15848. , location = session; // points at where properties go under (one of the above)
  15849. // parse lines we understand
  15850. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  15851. var type = l[0];
  15852. var content = l.slice(2);
  15853. if (type === 'm') {
  15854. media.push({rtp: [], fmtp: []});
  15855. location = media[media.length-1]; // point at latest media line
  15856. }
  15857. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  15858. var obj = grammar[type][j];
  15859. if (obj.reg.test(content)) {
  15860. return parseReg(obj, location, content);
  15861. }
  15862. }
  15863. });
  15864. session.media = media; // link it up
  15865. return session;
  15866. };
  15867. var fmtpReducer = function (acc, expr) {
  15868. var s = expr.split('=');
  15869. if (s.length === 2) {
  15870. acc[s[0]] = toIntIfInt(s[1]);
  15871. }
  15872. return acc;
  15873. };
  15874. exports.parseFmtpConfig = function (str) {
  15875. return str.split(';').reduce(fmtpReducer, {});
  15876. };
  15877. exports.parsePayloads = function (str) {
  15878. return str.split(' ').map(Number);
  15879. };
  15880. exports.parseRemoteCandidates = function (str) {
  15881. var candidates = [];
  15882. var parts = str.split(' ').map(toIntIfInt);
  15883. for (var i = 0; i < parts.length; i += 3) {
  15884. candidates.push({
  15885. component: parts[i],
  15886. ip: parts[i + 1],
  15887. port: parts[i + 2]
  15888. });
  15889. }
  15890. return candidates;
  15891. };
  15892. },{"./grammar":52}],55:[function(require,module,exports){
  15893. var grammar = require('./grammar');
  15894. // customized util.format - discards excess arguments and can void middle ones
  15895. var formatRegExp = /%[sdv%]/g;
  15896. var format = function (formatStr) {
  15897. var i = 1;
  15898. var args = arguments;
  15899. var len = args.length;
  15900. return formatStr.replace(formatRegExp, function (x) {
  15901. if (i >= len) {
  15902. return x; // missing argument
  15903. }
  15904. var arg = args[i];
  15905. i += 1;
  15906. switch (x) {
  15907. case '%%':
  15908. return '%';
  15909. case '%s':
  15910. return String(arg);
  15911. case '%d':
  15912. return Number(arg);
  15913. case '%v':
  15914. return '';
  15915. }
  15916. });
  15917. // NB: we discard excess arguments - they are typically undefined from makeLine
  15918. };
  15919. var makeLine = function (type, obj, location) {
  15920. var str = obj.format instanceof Function ?
  15921. (obj.format(obj.push ? location : location[obj.name])) :
  15922. obj.format;
  15923. var args = [type + '=' + str];
  15924. if (obj.names) {
  15925. for (var i = 0; i < obj.names.length; i += 1) {
  15926. var n = obj.names[i];
  15927. if (obj.name) {
  15928. args.push(location[obj.name][n]);
  15929. }
  15930. else { // for mLine and push attributes
  15931. args.push(location[obj.names[i]]);
  15932. }
  15933. }
  15934. }
  15935. else {
  15936. args.push(location[obj.name]);
  15937. }
  15938. return format.apply(null, args);
  15939. };
  15940. // RFC specified order
  15941. // TODO: extend this with all the rest
  15942. var defaultOuterOrder = [
  15943. 'v', 'o', 's', 'i',
  15944. 'u', 'e', 'p', 'c',
  15945. 'b', 't', 'r', 'z', 'a'
  15946. ];
  15947. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  15948. module.exports = function (session, opts) {
  15949. opts = opts || {};
  15950. // ensure certain properties exist
  15951. if (session.version == null) {
  15952. session.version = 0; // "v=0" must be there (only defined version atm)
  15953. }
  15954. if (session.name == null) {
  15955. session.name = " "; // "s= " must be there if no meaningful name set
  15956. }
  15957. session.media.forEach(function (mLine) {
  15958. if (mLine.payloads == null) {
  15959. mLine.payloads = "";
  15960. }
  15961. });
  15962. var outerOrder = opts.outerOrder || defaultOuterOrder;
  15963. var innerOrder = opts.innerOrder || defaultInnerOrder;
  15964. var sdp = [];
  15965. // loop through outerOrder for matching properties on session
  15966. outerOrder.forEach(function (type) {
  15967. grammar[type].forEach(function (obj) {
  15968. if (obj.name in session && session[obj.name] != null) {
  15969. sdp.push(makeLine(type, obj, session));
  15970. }
  15971. else if (obj.push in session && session[obj.push] != null) {
  15972. session[obj.push].forEach(function (el) {
  15973. sdp.push(makeLine(type, obj, el));
  15974. });
  15975. }
  15976. });
  15977. });
  15978. // then for each media line, follow the innerOrder
  15979. session.media.forEach(function (mLine) {
  15980. sdp.push(makeLine('m', grammar.m[0], mLine));
  15981. innerOrder.forEach(function (type) {
  15982. grammar[type].forEach(function (obj) {
  15983. if (obj.name in mLine && mLine[obj.name] != null) {
  15984. sdp.push(makeLine(type, obj, mLine));
  15985. }
  15986. else if (obj.push in mLine && mLine[obj.push] != null) {
  15987. mLine[obj.push].forEach(function (el) {
  15988. sdp.push(makeLine(type, obj, el));
  15989. });
  15990. }
  15991. });
  15992. });
  15993. });
  15994. return sdp.join('\r\n') + '\r\n';
  15995. };
  15996. },{"./grammar":52}],56:[function(require,module,exports){
  15997. var transform = require('sdp-transform');
  15998. var transformUtils = require('./transform-utils');
  15999. var parseSsrcs = transformUtils.parseSsrcs;
  16000. var writeSsrcs = transformUtils.writeSsrcs;
  16001. //region Constants
  16002. var DEFAULT_NUM_OF_LAYERS = 3;
  16003. //endregion
  16004. //region Ctor
  16005. function Simulcast(options) {
  16006. this.options = options ? options : {};
  16007. if (!this.options.numOfLayers) {
  16008. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  16009. }
  16010. this.layers = [];
  16011. }
  16012. //endregion
  16013. //region Stateless private utility functions
  16014. /**
  16015. * Returns a random integer between min (included) and max (excluded)
  16016. * Using Math.round() gives a non-uniform distribution!
  16017. * @returns {number}
  16018. */
  16019. function generateSSRC() {
  16020. var min = 0, max = 0xffffffff;
  16021. return Math.floor(Math.random() * (max - min)) + min;
  16022. };
  16023. function processVideo(session, action) {
  16024. if (session == null || !Array.isArray(session.media)) {
  16025. return;
  16026. }
  16027. session.media.forEach(function (mLine) {
  16028. if (mLine.type === 'video') {
  16029. action(mLine);
  16030. }
  16031. });
  16032. }
  16033. function validateDescription(desc)
  16034. {
  16035. return desc && desc != null
  16036. && desc.type && desc.type != ''
  16037. && desc.sdp && desc.sdp != '';
  16038. }
  16039. function explodeRemoteSimulcast(mLine) {
  16040. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16041. return;
  16042. }
  16043. var sources = parseSsrcs(mLine);
  16044. var order = [];
  16045. // Find the SIM group and explode its sources.
  16046. var j = mLine.ssrcGroups.length;
  16047. while (j--) {
  16048. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  16049. continue;
  16050. }
  16051. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  16052. for (var i = 0; i < simulcastSsrcs.length; i++) {
  16053. var ssrc = simulcastSsrcs[i];
  16054. order.push(ssrc);
  16055. var parts = sources[ssrc].msid.split(' ');
  16056. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  16057. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  16058. // Remove all the groups that this SSRC participates in.
  16059. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16060. if (relatedGroup.semantics === 'SIM') {
  16061. return;
  16062. }
  16063. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  16064. if (relatedSsrcs.indexOf(ssrc) === -1) {
  16065. return;
  16066. }
  16067. // Nuke all the related SSRCs.
  16068. relatedSsrcs.forEach(function (relatedSSRC) {
  16069. sources[relatedSSRC].msid = sources[ssrc].msid;
  16070. sources[relatedSSRC].cname = sources[ssrc].cname;
  16071. if (relatedSSRC !== ssrc) {
  16072. order.push(relatedSSRC);
  16073. }
  16074. });
  16075. // Schedule the related group for nuking.
  16076. })
  16077. }
  16078. mLine.ssrcs = writeSsrcs(sources, order);
  16079. mLine.ssrcGroups.splice(j, 1);
  16080. };
  16081. }
  16082. function squeezeRemoteSimulcast(mLine) {
  16083. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  16084. return;
  16085. }
  16086. var sources = parseSsrcs(mLine);
  16087. // Find the SIM group and nuke it.
  16088. mLine.ssrcGroups.some(function (simulcastGroup) {
  16089. if (simulcastGroup.semantics !== 'SIM') {
  16090. return false;
  16091. }
  16092. // Schedule the SIM group for nuking.
  16093. simulcastGroup.nuke = true;
  16094. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  16095. // Nuke all the higher layer SSRCs.
  16096. for (var i = 1; i < simulcastSsrcs.length; i++) {
  16097. var ssrc = simulcastSsrcs[i];
  16098. delete sources[ssrc];
  16099. // Remove all the groups that this SSRC participates in.
  16100. mLine.ssrcGroups.forEach(function (relatedGroup) {
  16101. if (relatedGroup.semantics === 'SIM') {
  16102. return;
  16103. }
  16104. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  16105. if (relatedSsrcs.indexOf(ssrc) === -1) {
  16106. return;
  16107. }
  16108. // Nuke all the related SSRCs.
  16109. relatedSsrcs.forEach(function (relatedSSRC) {
  16110. delete sources[relatedSSRC];
  16111. });
  16112. // Schedule the related group for nuking.
  16113. relatedGroup.nuke = true;
  16114. })
  16115. }
  16116. return true;
  16117. });
  16118. mLine.ssrcs = writeSsrcs(sources);
  16119. // Nuke all the scheduled groups.
  16120. var i = mLine.ssrcGroups.length;
  16121. while (i--) {
  16122. if (mLine.ssrcGroups[i].nuke) {
  16123. mLine.ssrcGroups.splice(i, 1);
  16124. }
  16125. }
  16126. }
  16127. function removeGoogConference(mLine) {
  16128. if (!mLine || !Array.isArray(mLine.invalid)) {
  16129. return;
  16130. }
  16131. var i = mLine.invalid.length;
  16132. while (i--) {
  16133. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  16134. mLine.invalid.splice(i, 1);
  16135. }
  16136. }
  16137. }
  16138. function assertGoogConference(mLine) {
  16139. if (!mLine) {
  16140. return;
  16141. }
  16142. if (!Array.isArray(mLine.invalid)) {
  16143. mLine.invalid = [];
  16144. }
  16145. if (!mLine.invalid.some(
  16146. function (i) { return i.value === 'x-google-flag:conference' })) {
  16147. mLine.invalid.push({'value': 'x-google-flag:conference'});
  16148. }
  16149. }
  16150. //endregion
  16151. //region "Private" functions
  16152. /**
  16153. *
  16154. * @param mLine
  16155. * @private
  16156. */
  16157. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  16158. if (!mLine || mLine.type !== 'video') {
  16159. return;
  16160. }
  16161. var sources = parseSsrcs(mLine);
  16162. if (Object.keys(sources).length === 0) {
  16163. // no sources, disable simulcast.
  16164. if (this.layers.length !== 0) {
  16165. this.layers = [];
  16166. }
  16167. return;
  16168. }
  16169. // find the base layer (we'll reuse its msid and cname).
  16170. var baseLayerSSRC = Object.keys(sources)[0];
  16171. var baseLayer = sources[baseLayerSSRC];
  16172. // todo(gp) handle screen sharing.
  16173. // check if base CNAME has changed and reinitialise layers.
  16174. if (this.layers.length > 0
  16175. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  16176. this.layers = [];
  16177. }
  16178. // (re)initialise layers
  16179. if (this.layers.length < 1) {
  16180. // first push the base layer.
  16181. this.layers.push({
  16182. ssrc: baseLayerSSRC,
  16183. msid: baseLayer.msid,
  16184. cname: baseLayer.cname
  16185. });
  16186. var rtx = false; // RFC 4588
  16187. if (Array.isArray(mLine.rtp)) {
  16188. rtx = mLine.rtp.some(
  16189. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  16190. }
  16191. if (rtx) {
  16192. this.layers[0].rtx = generateSSRC();
  16193. }
  16194. // now push additional layers.
  16195. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  16196. var layer = { ssrc: generateSSRC() };
  16197. if (rtx) {
  16198. layer.rtx = generateSSRC();
  16199. }
  16200. this.layers.push(layer);
  16201. }
  16202. }
  16203. };
  16204. /**
  16205. *
  16206. * @param mLine
  16207. * @private
  16208. */
  16209. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  16210. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  16211. var sources = {};
  16212. var msid = this.layers[0].msid;
  16213. var cname = this.layers[0].cname;
  16214. var simulcastSsrcs = [];
  16215. var ssrcGroups = [];
  16216. for (var i = 0; i < this.layers.length; i++) {
  16217. var layer = this.layers[i];
  16218. sources[layer.ssrc] = { msid: msid, cname: cname };
  16219. simulcastSsrcs.push(layer.ssrc);
  16220. if (layer.rtx) {
  16221. sources[layer.rtx] = {
  16222. msid: msid,
  16223. cname: cname
  16224. }
  16225. ssrcGroups.push({
  16226. semantics: 'FID',
  16227. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  16228. });
  16229. }
  16230. }
  16231. ssrcGroups.push({
  16232. semantics: 'SIM',
  16233. ssrcs: simulcastSsrcs.join(' ')
  16234. });
  16235. mLine.ssrcGroups = ssrcGroups;
  16236. mLine.ssrcs = writeSsrcs(sources);
  16237. }
  16238. }
  16239. //endregion
  16240. //region "Public" functions
  16241. Simulcast.prototype.isSupported = function () {
  16242. return window.chrome;
  16243. // TODO this needs improvements. For example I doubt that Chrome in Android
  16244. // has simulcast support. Also, only recent versions of Chromium have native
  16245. // simulcast support.
  16246. }
  16247. /**
  16248. *
  16249. * @param desc
  16250. * @returns {RTCSessionDescription}
  16251. */
  16252. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  16253. if (!validateDescription(desc)) {
  16254. return desc;
  16255. }
  16256. var session = transform.parse(desc.sdp);
  16257. var self = this;
  16258. processVideo(session, function (mLine) {
  16259. // Handle simulcast reception.
  16260. if (self.options.explodeRemoteSimulcast) {
  16261. explodeRemoteSimulcast(mLine);
  16262. } else {
  16263. squeezeRemoteSimulcast(mLine);
  16264. }
  16265. // If native simulcast is enabled, we must append the x-goog-conference
  16266. // attribute to the SDP.
  16267. if (self.layers.length < 1) {
  16268. removeGoogConference(mLine);
  16269. } else {
  16270. assertGoogConference(mLine);
  16271. }
  16272. });
  16273. return new RTCSessionDescription({
  16274. type: desc.type,
  16275. sdp: transform.write(session)
  16276. });
  16277. };
  16278. /**
  16279. *
  16280. * @param desc
  16281. * @returns {RTCSessionDescription}
  16282. */
  16283. Simulcast.prototype.mungeLocalDescription = function (desc) {
  16284. if (!validateDescription(desc) || !this.isSupported()) {
  16285. return desc;
  16286. }
  16287. var session = transform.parse(desc.sdp);
  16288. var self = this;
  16289. processVideo(session, function (mLine) {
  16290. // Initialize native simulcast layers, if not already done.
  16291. self._maybeInitializeLayers(mLine);
  16292. // Update the SDP with the simulcast layers.
  16293. self._restoreSimulcastView(mLine);
  16294. });
  16295. return new RTCSessionDescription({
  16296. type: desc.type,
  16297. sdp: transform.write(session)
  16298. });
  16299. };
  16300. //endregion
  16301. module.exports = Simulcast;
  16302. },{"./transform-utils":57,"sdp-transform":59}],57:[function(require,module,exports){
  16303. exports.writeSsrcs = function(sources, order) {
  16304. var ssrcs = [];
  16305. // expand sources to ssrcs
  16306. if (typeof sources !== 'undefined' &&
  16307. Object.keys(sources).length !== 0) {
  16308. if (Array.isArray(order)) {
  16309. for (var i = 0; i < order.length; i++) {
  16310. var ssrc = order[i];
  16311. var source = sources[ssrc];
  16312. Object.keys(source).forEach(function (attribute) {
  16313. ssrcs.push({
  16314. id: ssrc,
  16315. attribute: attribute,
  16316. value: source[attribute]
  16317. });
  16318. });
  16319. }
  16320. } else {
  16321. Object.keys(sources).forEach(function (ssrc) {
  16322. var source = sources[ssrc];
  16323. Object.keys(source).forEach(function (attribute) {
  16324. ssrcs.push({
  16325. id: ssrc,
  16326. attribute: attribute,
  16327. value: source[attribute]
  16328. });
  16329. });
  16330. });
  16331. }
  16332. }
  16333. return ssrcs;
  16334. };
  16335. exports.parseSsrcs = function (mLine) {
  16336. var sources = {};
  16337. // group sources attributes by ssrc.
  16338. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  16339. mLine.ssrcs.forEach(function (ssrc) {
  16340. if (!sources[ssrc.id])
  16341. sources[ssrc.id] = {};
  16342. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  16343. });
  16344. }
  16345. return sources;
  16346. };
  16347. },{}],58:[function(require,module,exports){
  16348. arguments[4][52][0].apply(exports,arguments)
  16349. },{"dup":52}],59:[function(require,module,exports){
  16350. arguments[4][53][0].apply(exports,arguments)
  16351. },{"./parser":60,"./writer":61,"dup":53}],60:[function(require,module,exports){
  16352. arguments[4][54][0].apply(exports,arguments)
  16353. },{"./grammar":58,"dup":54}],61:[function(require,module,exports){
  16354. arguments[4][55][0].apply(exports,arguments)
  16355. },{"./grammar":58,"dup":55}],62:[function(require,module,exports){
  16356. arguments[4][52][0].apply(exports,arguments)
  16357. },{"dup":52}],63:[function(require,module,exports){
  16358. arguments[4][53][0].apply(exports,arguments)
  16359. },{"./parser":64,"./writer":65,"dup":53}],64:[function(require,module,exports){
  16360. arguments[4][54][0].apply(exports,arguments)
  16361. },{"./grammar":62,"dup":54}],65:[function(require,module,exports){
  16362. arguments[4][55][0].apply(exports,arguments)
  16363. },{"./grammar":62,"dup":55}],66:[function(require,module,exports){
  16364. var MediaStreamType = {
  16365. VIDEO_TYPE: "Video",
  16366. AUDIO_TYPE: "Audio"
  16367. };
  16368. module.exports = MediaStreamType;
  16369. },{}],67:[function(require,module,exports){
  16370. var RTCEvents = {
  16371. RTC_READY: "rtc.ready",
  16372. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  16373. LASTN_CHANGED: "rtc.lastn_changed",
  16374. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  16375. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  16376. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  16377. AUDIO_MUTE: "rtc.audio_mute",
  16378. VIDEO_MUTE: "rtc.video_mute"
  16379. };
  16380. module.exports = RTCEvents;
  16381. },{}],68:[function(require,module,exports){
  16382. var Resolutions = {
  16383. "1080": {
  16384. width: 1920,
  16385. height: 1080,
  16386. order: 7
  16387. },
  16388. "fullhd": {
  16389. width: 1920,
  16390. height: 1080,
  16391. order: 7
  16392. },
  16393. "720": {
  16394. width: 1280,
  16395. height: 720,
  16396. order: 6
  16397. },
  16398. "hd": {
  16399. width: 1280,
  16400. height: 720,
  16401. order: 6
  16402. },
  16403. "960": {
  16404. width: 960,
  16405. height: 720,
  16406. order: 5
  16407. },
  16408. "640": {
  16409. width: 640,
  16410. height: 480,
  16411. order: 4
  16412. },
  16413. "vga": {
  16414. width: 640,
  16415. height: 480,
  16416. order: 4
  16417. },
  16418. "360": {
  16419. width: 640,
  16420. height: 360,
  16421. order: 3
  16422. },
  16423. "320": {
  16424. width: 320,
  16425. height: 240,
  16426. order: 2
  16427. },
  16428. "180": {
  16429. width: 320,
  16430. height: 180,
  16431. order: 1
  16432. }
  16433. };
  16434. module.exports = Resolutions;
  16435. },{}],69:[function(require,module,exports){
  16436. var StreamEventTypes = {
  16437. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  16438. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  16439. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  16440. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  16441. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  16442. };
  16443. module.exports = StreamEventTypes;
  16444. },{}],70:[function(require,module,exports){
  16445. var UIEvents = {
  16446. NICKNAME_CHANGED: "UI.nickname_changed",
  16447. SELECTED_ENDPOINT: "UI.selected_endpoint",
  16448. PINNED_ENDPOINT: "UI.pinned_endpoint",
  16449. LARGEVIDEO_INIT: "UI.largevideo_init"
  16450. };
  16451. module.exports = UIEvents;
  16452. },{}],71:[function(require,module,exports){
  16453. var AuthenticationEvents = {
  16454. /**
  16455. * Event callback arguments:
  16456. * function(authenticationEnabled, userIdentity)
  16457. * authenticationEnabled - indicates whether authentication has been enabled
  16458. * in this session
  16459. * userIdentity - if user has been logged in then it contains user name. If
  16460. * contains 'null' or 'undefined' then user is not logged in.
  16461. */
  16462. IDENTITY_UPDATED: "authentication.identity_updated"
  16463. };
  16464. module.exports = AuthenticationEvents;
  16465. },{}],72:[function(require,module,exports){
  16466. var DesktopSharingEventTypes = {
  16467. INIT: "ds.init",
  16468. SWITCHING_DONE: "ds.switching_done",
  16469. NEW_STREAM_CREATED: "ds.new_stream_created"
  16470. };
  16471. module.exports = DesktopSharingEventTypes;
  16472. },{}],73:[function(require,module,exports){
  16473. var XMPPEvents = {
  16474. CONNECTION_FAILED: "xmpp.connection.failed",
  16475. // Indicates an interrupted connection event.
  16476. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  16477. // Indicates a restored connection event.
  16478. CONNECTION_RESTORED: "xmpp.connection.restored",
  16479. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  16480. CALL_INCOMING: "xmpp.callincoming.jingle",
  16481. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  16482. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  16483. KICKED: "xmpp.kicked",
  16484. BRIDGE_DOWN: "xmpp.bridge_down",
  16485. USER_ID_CHANGED: "xmpp.user_id_changed",
  16486. // We joined the MUC
  16487. MUC_JOINED: "xmpp.muc_joined",
  16488. // A member joined the MUC
  16489. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  16490. // A member left the MUC
  16491. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  16492. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  16493. MUC_DESTROYED: "xmpp.muc_destroyed",
  16494. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  16495. REMOTE_STATS: "xmpp.remote_stats",
  16496. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  16497. PRESENCE_STATUS: "xmpp.presence_status",
  16498. RESERVATION_ERROR: "xmpp.room_reservation_error",
  16499. SUBJECT_CHANGED: "xmpp.subject_changed",
  16500. MESSAGE_RECEIVED: "xmpp.message_received",
  16501. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  16502. PASSWORD_REQUIRED: "xmpp.password_required",
  16503. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  16504. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  16505. ETHERPAD: "xmpp.etherpad",
  16506. DEVICE_AVAILABLE: "xmpp.device_available",
  16507. VIDEO_TYPE: "xmpp.video_type",
  16508. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  16509. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  16510. AUDIO_MUTED: "xmpp.audio_muted",
  16511. VIDEO_MUTED: "xmpp.video_muted",
  16512. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  16513. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  16514. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  16515. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  16516. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  16517. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  16518. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  16519. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  16520. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  16521. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  16522. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  16523. // xmpp is connected and obtained user media
  16524. READY_TO_JOIN: 'xmpp.ready_to_join',
  16525. FOCUS_LEFT: "xmpp.focus_left"
  16526. };
  16527. module.exports = XMPPEvents;
  16528. },{}],74:[function(require,module,exports){
  16529. // Copyright Joyent, Inc. and other Node contributors.
  16530. //
  16531. // Permission is hereby granted, free of charge, to any person obtaining a
  16532. // copy of this software and associated documentation files (the
  16533. // "Software"), to deal in the Software without restriction, including
  16534. // without limitation the rights to use, copy, modify, merge, publish,
  16535. // distribute, sublicense, and/or sell copies of the Software, and to permit
  16536. // persons to whom the Software is furnished to do so, subject to the
  16537. // following conditions:
  16538. //
  16539. // The above copyright notice and this permission notice shall be included
  16540. // in all copies or substantial portions of the Software.
  16541. //
  16542. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16543. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16544. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  16545. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  16546. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16547. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  16548. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  16549. function EventEmitter() {
  16550. this._events = this._events || {};
  16551. this._maxListeners = this._maxListeners || undefined;
  16552. }
  16553. module.exports = EventEmitter;
  16554. // Backwards-compat with node 0.10.x
  16555. EventEmitter.EventEmitter = EventEmitter;
  16556. EventEmitter.prototype._events = undefined;
  16557. EventEmitter.prototype._maxListeners = undefined;
  16558. // By default EventEmitters will print a warning if more than 10 listeners are
  16559. // added to it. This is a useful default which helps finding memory leaks.
  16560. EventEmitter.defaultMaxListeners = 10;
  16561. // Obviously not all Emitters should be limited to 10. This function allows
  16562. // that to be increased. Set to zero for unlimited.
  16563. EventEmitter.prototype.setMaxListeners = function(n) {
  16564. if (!isNumber(n) || n < 0 || isNaN(n))
  16565. throw TypeError('n must be a positive number');
  16566. this._maxListeners = n;
  16567. return this;
  16568. };
  16569. EventEmitter.prototype.emit = function(type) {
  16570. var er, handler, len, args, i, listeners;
  16571. if (!this._events)
  16572. this._events = {};
  16573. // If there is no 'error' event listener then throw.
  16574. if (type === 'error') {
  16575. if (!this._events.error ||
  16576. (isObject(this._events.error) && !this._events.error.length)) {
  16577. er = arguments[1];
  16578. if (er instanceof Error) {
  16579. throw er; // Unhandled 'error' event
  16580. }
  16581. throw TypeError('Uncaught, unspecified "error" event.');
  16582. }
  16583. }
  16584. handler = this._events[type];
  16585. if (isUndefined(handler))
  16586. return false;
  16587. if (isFunction(handler)) {
  16588. switch (arguments.length) {
  16589. // fast cases
  16590. case 1:
  16591. handler.call(this);
  16592. break;
  16593. case 2:
  16594. handler.call(this, arguments[1]);
  16595. break;
  16596. case 3:
  16597. handler.call(this, arguments[1], arguments[2]);
  16598. break;
  16599. // slower
  16600. default:
  16601. len = arguments.length;
  16602. args = new Array(len - 1);
  16603. for (i = 1; i < len; i++)
  16604. args[i - 1] = arguments[i];
  16605. handler.apply(this, args);
  16606. }
  16607. } else if (isObject(handler)) {
  16608. len = arguments.length;
  16609. args = new Array(len - 1);
  16610. for (i = 1; i < len; i++)
  16611. args[i - 1] = arguments[i];
  16612. listeners = handler.slice();
  16613. len = listeners.length;
  16614. for (i = 0; i < len; i++)
  16615. listeners[i].apply(this, args);
  16616. }
  16617. return true;
  16618. };
  16619. EventEmitter.prototype.addListener = function(type, listener) {
  16620. var m;
  16621. if (!isFunction(listener))
  16622. throw TypeError('listener must be a function');
  16623. if (!this._events)
  16624. this._events = {};
  16625. // To avoid recursion in the case that type === "newListener"! Before
  16626. // adding it to the listeners, first emit "newListener".
  16627. if (this._events.newListener)
  16628. this.emit('newListener', type,
  16629. isFunction(listener.listener) ?
  16630. listener.listener : listener);
  16631. if (!this._events[type])
  16632. // Optimize the case of one listener. Don't need the extra array object.
  16633. this._events[type] = listener;
  16634. else if (isObject(this._events[type]))
  16635. // If we've already got an array, just append.
  16636. this._events[type].push(listener);
  16637. else
  16638. // Adding the second element, need to change to array.
  16639. this._events[type] = [this._events[type], listener];
  16640. // Check for listener leak
  16641. if (isObject(this._events[type]) && !this._events[type].warned) {
  16642. var m;
  16643. if (!isUndefined(this._maxListeners)) {
  16644. m = this._maxListeners;
  16645. } else {
  16646. m = EventEmitter.defaultMaxListeners;
  16647. }
  16648. if (m && m > 0 && this._events[type].length > m) {
  16649. this._events[type].warned = true;
  16650. console.error('(node) warning: possible EventEmitter memory ' +
  16651. 'leak detected. %d listeners added. ' +
  16652. 'Use emitter.setMaxListeners() to increase limit.',
  16653. this._events[type].length);
  16654. if (typeof console.trace === 'function') {
  16655. // not supported in IE 10
  16656. console.trace();
  16657. }
  16658. }
  16659. }
  16660. return this;
  16661. };
  16662. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  16663. EventEmitter.prototype.once = function(type, listener) {
  16664. if (!isFunction(listener))
  16665. throw TypeError('listener must be a function');
  16666. var fired = false;
  16667. function g() {
  16668. this.removeListener(type, g);
  16669. if (!fired) {
  16670. fired = true;
  16671. listener.apply(this, arguments);
  16672. }
  16673. }
  16674. g.listener = listener;
  16675. this.on(type, g);
  16676. return this;
  16677. };
  16678. // emits a 'removeListener' event iff the listener was removed
  16679. EventEmitter.prototype.removeListener = function(type, listener) {
  16680. var list, position, length, i;
  16681. if (!isFunction(listener))
  16682. throw TypeError('listener must be a function');
  16683. if (!this._events || !this._events[type])
  16684. return this;
  16685. list = this._events[type];
  16686. length = list.length;
  16687. position = -1;
  16688. if (list === listener ||
  16689. (isFunction(list.listener) && list.listener === listener)) {
  16690. delete this._events[type];
  16691. if (this._events.removeListener)
  16692. this.emit('removeListener', type, listener);
  16693. } else if (isObject(list)) {
  16694. for (i = length; i-- > 0;) {
  16695. if (list[i] === listener ||
  16696. (list[i].listener && list[i].listener === listener)) {
  16697. position = i;
  16698. break;
  16699. }
  16700. }
  16701. if (position < 0)
  16702. return this;
  16703. if (list.length === 1) {
  16704. list.length = 0;
  16705. delete this._events[type];
  16706. } else {
  16707. list.splice(position, 1);
  16708. }
  16709. if (this._events.removeListener)
  16710. this.emit('removeListener', type, listener);
  16711. }
  16712. return this;
  16713. };
  16714. EventEmitter.prototype.removeAllListeners = function(type) {
  16715. var key, listeners;
  16716. if (!this._events)
  16717. return this;
  16718. // not listening for removeListener, no need to emit
  16719. if (!this._events.removeListener) {
  16720. if (arguments.length === 0)
  16721. this._events = {};
  16722. else if (this._events[type])
  16723. delete this._events[type];
  16724. return this;
  16725. }
  16726. // emit removeListener for all listeners on all events
  16727. if (arguments.length === 0) {
  16728. for (key in this._events) {
  16729. if (key === 'removeListener') continue;
  16730. this.removeAllListeners(key);
  16731. }
  16732. this.removeAllListeners('removeListener');
  16733. this._events = {};
  16734. return this;
  16735. }
  16736. listeners = this._events[type];
  16737. if (isFunction(listeners)) {
  16738. this.removeListener(type, listeners);
  16739. } else {
  16740. // LIFO order
  16741. while (listeners.length)
  16742. this.removeListener(type, listeners[listeners.length - 1]);
  16743. }
  16744. delete this._events[type];
  16745. return this;
  16746. };
  16747. EventEmitter.prototype.listeners = function(type) {
  16748. var ret;
  16749. if (!this._events || !this._events[type])
  16750. ret = [];
  16751. else if (isFunction(this._events[type]))
  16752. ret = [this._events[type]];
  16753. else
  16754. ret = this._events[type].slice();
  16755. return ret;
  16756. };
  16757. EventEmitter.listenerCount = function(emitter, type) {
  16758. var ret;
  16759. if (!emitter._events || !emitter._events[type])
  16760. ret = 0;
  16761. else if (isFunction(emitter._events[type]))
  16762. ret = 1;
  16763. else
  16764. ret = emitter._events[type].length;
  16765. return ret;
  16766. };
  16767. function isFunction(arg) {
  16768. return typeof arg === 'function';
  16769. }
  16770. function isNumber(arg) {
  16771. return typeof arg === 'number';
  16772. }
  16773. function isObject(arg) {
  16774. return typeof arg === 'object' && arg !== null;
  16775. }
  16776. function isUndefined(arg) {
  16777. return arg === void 0;
  16778. }
  16779. },{}],75:[function(require,module,exports){
  16780. // shim for using process in browser
  16781. var process = module.exports = {};
  16782. var queue = [];
  16783. var draining = false;
  16784. function drainQueue() {
  16785. if (draining) {
  16786. return;
  16787. }
  16788. draining = true;
  16789. var currentQueue;
  16790. var len = queue.length;
  16791. while(len) {
  16792. currentQueue = queue;
  16793. queue = [];
  16794. var i = -1;
  16795. while (++i < len) {
  16796. currentQueue[i]();
  16797. }
  16798. len = queue.length;
  16799. }
  16800. draining = false;
  16801. }
  16802. process.nextTick = function (fun) {
  16803. queue.push(fun);
  16804. if (!draining) {
  16805. setTimeout(drainQueue, 0);
  16806. }
  16807. };
  16808. process.title = 'browser';
  16809. process.browser = true;
  16810. process.env = {};
  16811. process.argv = [];
  16812. process.version = ''; // empty string to avoid regexp issues
  16813. function noop() {}
  16814. process.on = noop;
  16815. process.addListener = noop;
  16816. process.once = noop;
  16817. process.off = noop;
  16818. process.removeListener = noop;
  16819. process.removeAllListeners = noop;
  16820. process.emit = noop;
  16821. process.binding = function (name) {
  16822. throw new Error('process.binding is not supported');
  16823. };
  16824. // TODO(shtylman)
  16825. process.cwd = function () { return '/' };
  16826. process.chdir = function (dir) {
  16827. throw new Error('process.chdir is not supported');
  16828. };
  16829. process.umask = function() { return 0; };
  16830. },{}]},{},[7])(7)
  16831. });